4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
24 * Copyright (c) 2013 by Delphix. All rights reserved.
25 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
29 * DVA-based Adjustable Replacement Cache
31 * While much of the theory of operation used here is
32 * based on the self-tuning, low overhead replacement cache
33 * presented by Megiddo and Modha at FAST 2003, there are some
34 * significant differences:
36 * 1. The Megiddo and Modha model assumes any page is evictable.
37 * Pages in its cache cannot be "locked" into memory. This makes
38 * the eviction algorithm simple: evict the last page in the list.
39 * This also make the performance characteristics easy to reason
40 * about. Our cache is not so simple. At any given moment, some
41 * subset of the blocks in the cache are un-evictable because we
42 * have handed out a reference to them. Blocks are only evictable
43 * when there are no external references active. This makes
44 * eviction far more problematic: we choose to evict the evictable
45 * blocks that are the "lowest" in the list.
47 * There are times when it is not possible to evict the requested
48 * space. In these circumstances we are unable to adjust the cache
49 * size. To prevent the cache growing unbounded at these times we
50 * implement a "cache throttle" that slows the flow of new data
51 * into the cache until we can make space available.
53 * 2. The Megiddo and Modha model assumes a fixed cache size.
54 * Pages are evicted when the cache is full and there is a cache
55 * miss. Our model has a variable sized cache. It grows with
56 * high use, but also tries to react to memory pressure from the
57 * operating system: decreasing its size when system memory is
60 * 3. The Megiddo and Modha model assumes a fixed page size. All
61 * elements of the cache are therefore exactly the same size. So
62 * when adjusting the cache size following a cache miss, its simply
63 * a matter of choosing a single page to evict. In our model, we
64 * have variable sized cache blocks (rangeing from 512 bytes to
65 * 128K bytes). We therefore choose a set of blocks to evict to make
66 * space for a cache miss that approximates as closely as possible
67 * the space used by the new block.
69 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70 * by N. Megiddo & D. Modha, FAST 2003
76 * A new reference to a cache buffer can be obtained in two
77 * ways: 1) via a hash table lookup using the DVA as a key,
78 * or 2) via one of the ARC lists. The arc_read() interface
79 * uses method 1, while the internal arc algorithms for
80 * adjusting the cache use method 2. We therefore provide two
81 * types of locks: 1) the hash table lock array, and 2) the
84 * Buffers do not have their own mutexs, rather they rely on the
85 * hash table mutexs for the bulk of their protection (i.e. most
86 * fields in the arc_buf_hdr_t are protected by these mutexs).
88 * buf_hash_find() returns the appropriate mutex (held) when it
89 * locates the requested buffer in the hash table. It returns
90 * NULL for the mutex if the buffer was not in the table.
92 * buf_hash_remove() expects the appropriate hash mutex to be
93 * already held before it is invoked.
95 * Each arc state also has a mutex which is used to protect the
96 * buffer list associated with the state. When attempting to
97 * obtain a hash table lock while holding an arc list lock you
98 * must use: mutex_tryenter() to avoid deadlock. Also note that
99 * the active state mutex must be held before the ghost state mutex.
101 * Arc buffers may have an associated eviction callback function.
102 * This function will be invoked prior to removing the buffer (e.g.
103 * in arc_do_user_evicts()). Note however that the data associated
104 * with the buffer may be evicted prior to the callback. The callback
105 * must be made with *no locks held* (to prevent deadlock). Additionally,
106 * the users of callbacks must ensure that their private data is
107 * protected from simultaneous callbacks from arc_buf_evict()
108 * and arc_do_user_evicts().
110 * Note that the majority of the performance stats are manipulated
111 * with atomic operations.
113 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
115 * - L2ARC buflist creation
116 * - L2ARC buflist eviction
117 * - L2ARC write completion, which walks L2ARC buflists
118 * - ARC header destruction, as it removes from L2ARC buflists
119 * - ARC header release, as it removes from L2ARC buflists
124 #include <sys/zio_compress.h>
125 #include <sys/zfs_context.h>
127 #include <sys/refcount.h>
128 #include <sys/vdev.h>
129 #include <sys/vdev_impl.h>
131 #include <sys/dnlc.h>
133 #include <sys/callb.h>
134 #include <sys/kstat.h>
135 #include <sys/trim_map.h>
136 #include <zfs_fletcher.h>
139 #include <vm/vm_pageout.h>
143 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
144 boolean_t arc_watch = B_FALSE;
149 static kmutex_t arc_reclaim_thr_lock;
150 static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
151 static uint8_t arc_thread_exit;
153 extern int zfs_write_limit_shift;
154 extern uint64_t zfs_write_limit_max;
155 extern kmutex_t zfs_write_limit_lock;
157 #define ARC_REDUCE_DNLC_PERCENT 3
158 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
160 typedef enum arc_reclaim_strategy {
161 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
162 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
163 } arc_reclaim_strategy_t;
165 /* number of seconds before growing cache again */
166 static int arc_grow_retry = 60;
168 /* shift of arc_c for calculating both min and max arc_p */
169 static int arc_p_min_shift = 4;
171 /* log2(fraction of arc to reclaim) */
172 static int arc_shrink_shift = 5;
175 * minimum lifespan of a prefetch block in clock ticks
176 * (initialized in arc_init())
178 static int arc_min_prefetch_lifespan;
181 extern int zfs_prefetch_disable;
184 * The arc has filled available memory and has now warmed up.
186 static boolean_t arc_warm;
189 * These tunables are for performance analysis.
191 uint64_t zfs_arc_max;
192 uint64_t zfs_arc_min;
193 uint64_t zfs_arc_meta_limit = 0;
194 int zfs_arc_grow_retry = 0;
195 int zfs_arc_shrink_shift = 0;
196 int zfs_arc_p_min_shift = 0;
197 int zfs_disable_dup_eviction = 0;
199 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
200 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
201 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
202 SYSCTL_DECL(_vfs_zfs);
203 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
205 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
209 * Note that buffers can be in one of 6 states:
210 * ARC_anon - anonymous (discussed below)
211 * ARC_mru - recently used, currently cached
212 * ARC_mru_ghost - recentely used, no longer in cache
213 * ARC_mfu - frequently used, currently cached
214 * ARC_mfu_ghost - frequently used, no longer in cache
215 * ARC_l2c_only - exists in L2ARC but not other states
216 * When there are no active references to the buffer, they are
217 * are linked onto a list in one of these arc states. These are
218 * the only buffers that can be evicted or deleted. Within each
219 * state there are multiple lists, one for meta-data and one for
220 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
221 * etc.) is tracked separately so that it can be managed more
222 * explicitly: favored over data, limited explicitly.
224 * Anonymous buffers are buffers that are not associated with
225 * a DVA. These are buffers that hold dirty block copies
226 * before they are written to stable storage. By definition,
227 * they are "ref'd" and are considered part of arc_mru
228 * that cannot be freed. Generally, they will aquire a DVA
229 * as they are written and migrate onto the arc_mru list.
231 * The ARC_l2c_only state is for buffers that are in the second
232 * level ARC but no longer in any of the ARC_m* lists. The second
233 * level ARC itself may also contain buffers that are in any of
234 * the ARC_m* states - meaning that a buffer can exist in two
235 * places. The reason for the ARC_l2c_only state is to keep the
236 * buffer header in the hash table, so that reads that hit the
237 * second level ARC benefit from these fast lookups.
240 #define ARCS_LOCK_PAD CACHE_LINE_SIZE
244 unsigned char pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
249 * must be power of two for mask use to work
252 #define ARC_BUFC_NUMDATALISTS 16
253 #define ARC_BUFC_NUMMETADATALISTS 16
254 #define ARC_BUFC_NUMLISTS (ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
256 typedef struct arc_state {
257 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
258 uint64_t arcs_size; /* total amount of data in this state */
259 list_t arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
260 struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
263 #define ARCS_LOCK(s, i) (&((s)->arcs_locks[(i)].arcs_lock))
266 static arc_state_t ARC_anon;
267 static arc_state_t ARC_mru;
268 static arc_state_t ARC_mru_ghost;
269 static arc_state_t ARC_mfu;
270 static arc_state_t ARC_mfu_ghost;
271 static arc_state_t ARC_l2c_only;
273 typedef struct arc_stats {
274 kstat_named_t arcstat_hits;
275 kstat_named_t arcstat_misses;
276 kstat_named_t arcstat_demand_data_hits;
277 kstat_named_t arcstat_demand_data_misses;
278 kstat_named_t arcstat_demand_metadata_hits;
279 kstat_named_t arcstat_demand_metadata_misses;
280 kstat_named_t arcstat_prefetch_data_hits;
281 kstat_named_t arcstat_prefetch_data_misses;
282 kstat_named_t arcstat_prefetch_metadata_hits;
283 kstat_named_t arcstat_prefetch_metadata_misses;
284 kstat_named_t arcstat_mru_hits;
285 kstat_named_t arcstat_mru_ghost_hits;
286 kstat_named_t arcstat_mfu_hits;
287 kstat_named_t arcstat_mfu_ghost_hits;
288 kstat_named_t arcstat_allocated;
289 kstat_named_t arcstat_deleted;
290 kstat_named_t arcstat_stolen;
291 kstat_named_t arcstat_recycle_miss;
293 * Number of buffers that could not be evicted because the hash lock
294 * was held by another thread. The lock may not necessarily be held
295 * by something using the same buffer, since hash locks are shared
296 * by multiple buffers.
298 kstat_named_t arcstat_mutex_miss;
300 * Number of buffers skipped because they have I/O in progress, are
301 * indrect prefetch buffers that have not lived long enough, or are
302 * not from the spa we're trying to evict from.
304 kstat_named_t arcstat_evict_skip;
305 kstat_named_t arcstat_evict_l2_cached;
306 kstat_named_t arcstat_evict_l2_eligible;
307 kstat_named_t arcstat_evict_l2_ineligible;
308 kstat_named_t arcstat_hash_elements;
309 kstat_named_t arcstat_hash_elements_max;
310 kstat_named_t arcstat_hash_collisions;
311 kstat_named_t arcstat_hash_chains;
312 kstat_named_t arcstat_hash_chain_max;
313 kstat_named_t arcstat_p;
314 kstat_named_t arcstat_c;
315 kstat_named_t arcstat_c_min;
316 kstat_named_t arcstat_c_max;
317 kstat_named_t arcstat_size;
318 kstat_named_t arcstat_hdr_size;
319 kstat_named_t arcstat_data_size;
320 kstat_named_t arcstat_other_size;
321 kstat_named_t arcstat_l2_hits;
322 kstat_named_t arcstat_l2_misses;
323 kstat_named_t arcstat_l2_feeds;
324 kstat_named_t arcstat_l2_rw_clash;
325 kstat_named_t arcstat_l2_read_bytes;
326 kstat_named_t arcstat_l2_write_bytes;
327 kstat_named_t arcstat_l2_writes_sent;
328 kstat_named_t arcstat_l2_writes_done;
329 kstat_named_t arcstat_l2_writes_error;
330 kstat_named_t arcstat_l2_writes_hdr_miss;
331 kstat_named_t arcstat_l2_evict_lock_retry;
332 kstat_named_t arcstat_l2_evict_reading;
333 kstat_named_t arcstat_l2_free_on_write;
334 kstat_named_t arcstat_l2_abort_lowmem;
335 kstat_named_t arcstat_l2_cksum_bad;
336 kstat_named_t arcstat_l2_io_error;
337 kstat_named_t arcstat_l2_size;
338 kstat_named_t arcstat_l2_asize;
339 kstat_named_t arcstat_l2_hdr_size;
340 kstat_named_t arcstat_l2_compress_successes;
341 kstat_named_t arcstat_l2_compress_zeros;
342 kstat_named_t arcstat_l2_compress_failures;
343 kstat_named_t arcstat_l2_write_trylock_fail;
344 kstat_named_t arcstat_l2_write_passed_headroom;
345 kstat_named_t arcstat_l2_write_spa_mismatch;
346 kstat_named_t arcstat_l2_write_in_l2;
347 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
348 kstat_named_t arcstat_l2_write_not_cacheable;
349 kstat_named_t arcstat_l2_write_full;
350 kstat_named_t arcstat_l2_write_buffer_iter;
351 kstat_named_t arcstat_l2_write_pios;
352 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
353 kstat_named_t arcstat_l2_write_buffer_list_iter;
354 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
355 kstat_named_t arcstat_memory_throttle_count;
356 kstat_named_t arcstat_duplicate_buffers;
357 kstat_named_t arcstat_duplicate_buffers_size;
358 kstat_named_t arcstat_duplicate_reads;
361 static arc_stats_t arc_stats = {
362 { "hits", KSTAT_DATA_UINT64 },
363 { "misses", KSTAT_DATA_UINT64 },
364 { "demand_data_hits", KSTAT_DATA_UINT64 },
365 { "demand_data_misses", KSTAT_DATA_UINT64 },
366 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
367 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
368 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
369 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
370 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
371 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
372 { "mru_hits", KSTAT_DATA_UINT64 },
373 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
374 { "mfu_hits", KSTAT_DATA_UINT64 },
375 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
376 { "allocated", KSTAT_DATA_UINT64 },
377 { "deleted", KSTAT_DATA_UINT64 },
378 { "stolen", KSTAT_DATA_UINT64 },
379 { "recycle_miss", KSTAT_DATA_UINT64 },
380 { "mutex_miss", KSTAT_DATA_UINT64 },
381 { "evict_skip", KSTAT_DATA_UINT64 },
382 { "evict_l2_cached", KSTAT_DATA_UINT64 },
383 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
384 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
385 { "hash_elements", KSTAT_DATA_UINT64 },
386 { "hash_elements_max", KSTAT_DATA_UINT64 },
387 { "hash_collisions", KSTAT_DATA_UINT64 },
388 { "hash_chains", KSTAT_DATA_UINT64 },
389 { "hash_chain_max", KSTAT_DATA_UINT64 },
390 { "p", KSTAT_DATA_UINT64 },
391 { "c", KSTAT_DATA_UINT64 },
392 { "c_min", KSTAT_DATA_UINT64 },
393 { "c_max", KSTAT_DATA_UINT64 },
394 { "size", KSTAT_DATA_UINT64 },
395 { "hdr_size", KSTAT_DATA_UINT64 },
396 { "data_size", KSTAT_DATA_UINT64 },
397 { "other_size", KSTAT_DATA_UINT64 },
398 { "l2_hits", KSTAT_DATA_UINT64 },
399 { "l2_misses", KSTAT_DATA_UINT64 },
400 { "l2_feeds", KSTAT_DATA_UINT64 },
401 { "l2_rw_clash", KSTAT_DATA_UINT64 },
402 { "l2_read_bytes", KSTAT_DATA_UINT64 },
403 { "l2_write_bytes", KSTAT_DATA_UINT64 },
404 { "l2_writes_sent", KSTAT_DATA_UINT64 },
405 { "l2_writes_done", KSTAT_DATA_UINT64 },
406 { "l2_writes_error", KSTAT_DATA_UINT64 },
407 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
408 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
409 { "l2_evict_reading", KSTAT_DATA_UINT64 },
410 { "l2_free_on_write", KSTAT_DATA_UINT64 },
411 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
412 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
413 { "l2_io_error", KSTAT_DATA_UINT64 },
414 { "l2_size", KSTAT_DATA_UINT64 },
415 { "l2_asize", KSTAT_DATA_UINT64 },
416 { "l2_hdr_size", KSTAT_DATA_UINT64 },
417 { "l2_compress_successes", KSTAT_DATA_UINT64 },
418 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
419 { "l2_compress_failures", KSTAT_DATA_UINT64 },
420 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
421 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
422 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
423 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
424 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
425 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
426 { "l2_write_full", KSTAT_DATA_UINT64 },
427 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
428 { "l2_write_pios", KSTAT_DATA_UINT64 },
429 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
430 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
431 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
432 { "memory_throttle_count", KSTAT_DATA_UINT64 },
433 { "duplicate_buffers", KSTAT_DATA_UINT64 },
434 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
435 { "duplicate_reads", KSTAT_DATA_UINT64 }
438 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
440 #define ARCSTAT_INCR(stat, val) \
441 atomic_add_64(&arc_stats.stat.value.ui64, (val))
443 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
444 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
446 #define ARCSTAT_MAX(stat, val) { \
448 while ((val) > (m = arc_stats.stat.value.ui64) && \
449 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
453 #define ARCSTAT_MAXSTAT(stat) \
454 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
457 * We define a macro to allow ARC hits/misses to be easily broken down by
458 * two separate conditions, giving a total of four different subtypes for
459 * each of hits and misses (so eight statistics total).
461 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
464 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
466 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
470 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
472 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
477 static arc_state_t *arc_anon;
478 static arc_state_t *arc_mru;
479 static arc_state_t *arc_mru_ghost;
480 static arc_state_t *arc_mfu;
481 static arc_state_t *arc_mfu_ghost;
482 static arc_state_t *arc_l2c_only;
485 * There are several ARC variables that are critical to export as kstats --
486 * but we don't want to have to grovel around in the kstat whenever we wish to
487 * manipulate them. For these variables, we therefore define them to be in
488 * terms of the statistic variable. This assures that we are not introducing
489 * the possibility of inconsistency by having shadow copies of the variables,
490 * while still allowing the code to be readable.
492 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
493 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
494 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
495 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
496 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
498 #define L2ARC_IS_VALID_COMPRESS(_c_) \
499 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
501 static int arc_no_grow; /* Don't try to grow cache size */
502 static uint64_t arc_tempreserve;
503 static uint64_t arc_loaned_bytes;
504 static uint64_t arc_meta_used;
505 static uint64_t arc_meta_limit;
506 static uint64_t arc_meta_max = 0;
507 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, arc_meta_used, CTLFLAG_RD, &arc_meta_used, 0,
508 "ARC metadata used");
509 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, arc_meta_limit, CTLFLAG_RW, &arc_meta_limit, 0,
510 "ARC metadata limit");
512 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
514 typedef struct arc_callback arc_callback_t;
516 struct arc_callback {
518 arc_done_func_t *acb_done;
520 zio_t *acb_zio_dummy;
521 arc_callback_t *acb_next;
524 typedef struct arc_write_callback arc_write_callback_t;
526 struct arc_write_callback {
528 arc_done_func_t *awcb_ready;
529 arc_done_func_t *awcb_done;
534 /* protected by hash lock */
539 kmutex_t b_freeze_lock;
540 zio_cksum_t *b_freeze_cksum;
543 arc_buf_hdr_t *b_hash_next;
548 arc_callback_t *b_acb;
552 arc_buf_contents_t b_type;
556 /* protected by arc state mutex */
557 arc_state_t *b_state;
558 list_node_t b_arc_node;
560 /* updated atomically */
561 clock_t b_arc_access;
563 /* self protecting */
566 l2arc_buf_hdr_t *b_l2hdr;
567 list_node_t b_l2node;
570 static arc_buf_t *arc_eviction_list;
571 static kmutex_t arc_eviction_mtx;
572 static arc_buf_hdr_t arc_eviction_hdr;
573 static void arc_get_data_buf(arc_buf_t *buf);
574 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
575 static int arc_evict_needed(arc_buf_contents_t type);
576 static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
578 static void arc_buf_watch(arc_buf_t *buf);
581 static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
583 #define GHOST_STATE(state) \
584 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
585 (state) == arc_l2c_only)
588 * Private ARC flags. These flags are private ARC only flags that will show up
589 * in b_flags in the arc_hdr_buf_t. Some flags are publicly declared, and can
590 * be passed in as arc_flags in things like arc_read. However, these flags
591 * should never be passed and should only be set by ARC code. When adding new
592 * public flags, make sure not to smash the private ones.
595 #define ARC_IN_HASH_TABLE (1 << 9) /* this buffer is hashed */
596 #define ARC_IO_IN_PROGRESS (1 << 10) /* I/O in progress for buf */
597 #define ARC_IO_ERROR (1 << 11) /* I/O failed for buf */
598 #define ARC_FREED_IN_READ (1 << 12) /* buf freed while in read */
599 #define ARC_BUF_AVAILABLE (1 << 13) /* block not in active use */
600 #define ARC_INDIRECT (1 << 14) /* this is an indirect block */
601 #define ARC_FREE_IN_PROGRESS (1 << 15) /* hdr about to be freed */
602 #define ARC_L2_WRITING (1 << 16) /* L2ARC write in progress */
603 #define ARC_L2_EVICTED (1 << 17) /* evicted during I/O */
604 #define ARC_L2_WRITE_HEAD (1 << 18) /* head of write list */
606 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_IN_HASH_TABLE)
607 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS)
608 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_IO_ERROR)
609 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_PREFETCH)
610 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FREED_IN_READ)
611 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_BUF_AVAILABLE)
612 #define HDR_FREE_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
613 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_L2CACHE)
614 #define HDR_L2_READING(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS && \
615 (hdr)->b_l2hdr != NULL)
616 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_L2_WRITING)
617 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_L2_EVICTED)
618 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_L2_WRITE_HEAD)
624 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
625 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
628 * Hash table routines
631 #define HT_LOCK_PAD CACHE_LINE_SIZE
636 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
640 #define BUF_LOCKS 256
641 typedef struct buf_hash_table {
643 arc_buf_hdr_t **ht_table;
644 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
647 static buf_hash_table_t buf_hash_table;
649 #define BUF_HASH_INDEX(spa, dva, birth) \
650 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
651 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
652 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
653 #define HDR_LOCK(hdr) \
654 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
656 uint64_t zfs_crc64_table[256];
662 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
663 #define L2ARC_HEADROOM 2 /* num of writes */
665 * If we discover during ARC scan any buffers to be compressed, we boost
666 * our headroom for the next scanning cycle by this percentage multiple.
668 #define L2ARC_HEADROOM_BOOST 200
669 #define L2ARC_FEED_SECS 1 /* caching interval secs */
670 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
672 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
673 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
675 /* L2ARC Performance Tunables */
676 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
677 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
678 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
679 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
680 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
681 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
682 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
683 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
684 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
686 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
687 &l2arc_write_max, 0, "max write size");
688 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
689 &l2arc_write_boost, 0, "extra write during warmup");
690 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
691 &l2arc_headroom, 0, "number of dev writes");
692 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
693 &l2arc_feed_secs, 0, "interval seconds");
694 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
695 &l2arc_feed_min_ms, 0, "min interval milliseconds");
697 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
698 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
699 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
700 &l2arc_feed_again, 0, "turbo warmup");
701 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
702 &l2arc_norw, 0, "no reads during writes");
704 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
705 &ARC_anon.arcs_size, 0, "size of anonymous state");
706 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
707 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
708 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
709 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
711 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
712 &ARC_mru.arcs_size, 0, "size of mru state");
713 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
714 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
715 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
716 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
718 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
719 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
720 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
721 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
722 "size of metadata in mru ghost state");
723 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
724 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
725 "size of data in mru ghost state");
727 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
728 &ARC_mfu.arcs_size, 0, "size of mfu state");
729 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
730 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
731 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
732 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
734 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
735 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
736 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
737 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
738 "size of metadata in mfu ghost state");
739 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
740 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
741 "size of data in mfu ghost state");
743 SYSCTL_QUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
744 &ARC_l2c_only.arcs_size, 0, "size of mru state");
749 typedef struct l2arc_dev {
750 vdev_t *l2ad_vdev; /* vdev */
751 spa_t *l2ad_spa; /* spa */
752 uint64_t l2ad_hand; /* next write location */
753 uint64_t l2ad_start; /* first addr on device */
754 uint64_t l2ad_end; /* last addr on device */
755 uint64_t l2ad_evict; /* last addr eviction reached */
756 boolean_t l2ad_first; /* first sweep through */
757 boolean_t l2ad_writing; /* currently writing */
758 list_t *l2ad_buflist; /* buffer list */
759 list_node_t l2ad_node; /* device list node */
762 static list_t L2ARC_dev_list; /* device list */
763 static list_t *l2arc_dev_list; /* device list pointer */
764 static kmutex_t l2arc_dev_mtx; /* device list mutex */
765 static l2arc_dev_t *l2arc_dev_last; /* last device used */
766 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
767 static list_t L2ARC_free_on_write; /* free after write buf list */
768 static list_t *l2arc_free_on_write; /* free after write list ptr */
769 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
770 static uint64_t l2arc_ndev; /* number of devices */
772 typedef struct l2arc_read_callback {
773 arc_buf_t *l2rcb_buf; /* read buffer */
774 spa_t *l2rcb_spa; /* spa */
775 blkptr_t l2rcb_bp; /* original blkptr */
776 zbookmark_t l2rcb_zb; /* original bookmark */
777 int l2rcb_flags; /* original flags */
778 enum zio_compress l2rcb_compress; /* applied compress */
779 } l2arc_read_callback_t;
781 typedef struct l2arc_write_callback {
782 l2arc_dev_t *l2wcb_dev; /* device info */
783 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
784 } l2arc_write_callback_t;
786 struct l2arc_buf_hdr {
787 /* protected by arc_buf_hdr mutex */
788 l2arc_dev_t *b_dev; /* L2ARC device */
789 uint64_t b_daddr; /* disk address, offset byte */
790 /* compression applied to buffer data */
791 enum zio_compress b_compress;
792 /* real alloc'd buffer size depending on b_compress applied */
794 /* temporary buffer holder for in-flight compressed data */
798 typedef struct l2arc_data_free {
799 /* protected by l2arc_free_on_write_mtx */
802 void (*l2df_func)(void *, size_t);
803 list_node_t l2df_list_node;
806 static kmutex_t l2arc_feed_thr_lock;
807 static kcondvar_t l2arc_feed_thr_cv;
808 static uint8_t l2arc_thread_exit;
810 static void l2arc_read_done(zio_t *zio);
811 static void l2arc_hdr_stat_add(void);
812 static void l2arc_hdr_stat_remove(void);
814 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
815 static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
816 enum zio_compress c);
817 static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
820 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
822 uint8_t *vdva = (uint8_t *)dva;
823 uint64_t crc = -1ULL;
826 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
828 for (i = 0; i < sizeof (dva_t); i++)
829 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
831 crc ^= (spa>>8) ^ birth;
836 #define BUF_EMPTY(buf) \
837 ((buf)->b_dva.dva_word[0] == 0 && \
838 (buf)->b_dva.dva_word[1] == 0 && \
841 #define BUF_EQUAL(spa, dva, birth, buf) \
842 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
843 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
844 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
847 buf_discard_identity(arc_buf_hdr_t *hdr)
849 hdr->b_dva.dva_word[0] = 0;
850 hdr->b_dva.dva_word[1] = 0;
855 static arc_buf_hdr_t *
856 buf_hash_find(uint64_t spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
858 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
859 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
862 mutex_enter(hash_lock);
863 for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
864 buf = buf->b_hash_next) {
865 if (BUF_EQUAL(spa, dva, birth, buf)) {
870 mutex_exit(hash_lock);
876 * Insert an entry into the hash table. If there is already an element
877 * equal to elem in the hash table, then the already existing element
878 * will be returned and the new element will not be inserted.
879 * Otherwise returns NULL.
881 static arc_buf_hdr_t *
882 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
884 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
885 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
889 ASSERT(!HDR_IN_HASH_TABLE(buf));
891 mutex_enter(hash_lock);
892 for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
893 fbuf = fbuf->b_hash_next, i++) {
894 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
898 buf->b_hash_next = buf_hash_table.ht_table[idx];
899 buf_hash_table.ht_table[idx] = buf;
900 buf->b_flags |= ARC_IN_HASH_TABLE;
902 /* collect some hash table performance data */
904 ARCSTAT_BUMP(arcstat_hash_collisions);
906 ARCSTAT_BUMP(arcstat_hash_chains);
908 ARCSTAT_MAX(arcstat_hash_chain_max, i);
911 ARCSTAT_BUMP(arcstat_hash_elements);
912 ARCSTAT_MAXSTAT(arcstat_hash_elements);
918 buf_hash_remove(arc_buf_hdr_t *buf)
920 arc_buf_hdr_t *fbuf, **bufp;
921 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
923 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
924 ASSERT(HDR_IN_HASH_TABLE(buf));
926 bufp = &buf_hash_table.ht_table[idx];
927 while ((fbuf = *bufp) != buf) {
928 ASSERT(fbuf != NULL);
929 bufp = &fbuf->b_hash_next;
931 *bufp = buf->b_hash_next;
932 buf->b_hash_next = NULL;
933 buf->b_flags &= ~ARC_IN_HASH_TABLE;
935 /* collect some hash table performance data */
936 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
938 if (buf_hash_table.ht_table[idx] &&
939 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
940 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
944 * Global data structures and functions for the buf kmem cache.
946 static kmem_cache_t *hdr_cache;
947 static kmem_cache_t *buf_cache;
954 kmem_free(buf_hash_table.ht_table,
955 (buf_hash_table.ht_mask + 1) * sizeof (void *));
956 for (i = 0; i < BUF_LOCKS; i++)
957 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
958 kmem_cache_destroy(hdr_cache);
959 kmem_cache_destroy(buf_cache);
963 * Constructor callback - called when the cache is empty
964 * and a new buf is requested.
968 hdr_cons(void *vbuf, void *unused, int kmflag)
970 arc_buf_hdr_t *buf = vbuf;
972 bzero(buf, sizeof (arc_buf_hdr_t));
973 refcount_create(&buf->b_refcnt);
974 cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
975 mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
976 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
983 buf_cons(void *vbuf, void *unused, int kmflag)
985 arc_buf_t *buf = vbuf;
987 bzero(buf, sizeof (arc_buf_t));
988 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
989 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
995 * Destructor callback - called when a cached buf is
996 * no longer required.
1000 hdr_dest(void *vbuf, void *unused)
1002 arc_buf_hdr_t *buf = vbuf;
1004 ASSERT(BUF_EMPTY(buf));
1005 refcount_destroy(&buf->b_refcnt);
1006 cv_destroy(&buf->b_cv);
1007 mutex_destroy(&buf->b_freeze_lock);
1008 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1013 buf_dest(void *vbuf, void *unused)
1015 arc_buf_t *buf = vbuf;
1017 mutex_destroy(&buf->b_evict_lock);
1018 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1022 * Reclaim callback -- invoked when memory is low.
1026 hdr_recl(void *unused)
1028 dprintf("hdr_recl called\n");
1030 * umem calls the reclaim func when we destroy the buf cache,
1031 * which is after we do arc_fini().
1034 cv_signal(&arc_reclaim_thr_cv);
1041 uint64_t hsize = 1ULL << 12;
1045 * The hash table is big enough to fill all of physical memory
1046 * with an average 64K block size. The table will take up
1047 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
1049 while (hsize * 65536 < (uint64_t)physmem * PAGESIZE)
1052 buf_hash_table.ht_mask = hsize - 1;
1053 buf_hash_table.ht_table =
1054 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1055 if (buf_hash_table.ht_table == NULL) {
1056 ASSERT(hsize > (1ULL << 8));
1061 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1062 0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1063 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1064 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1066 for (i = 0; i < 256; i++)
1067 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1068 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1070 for (i = 0; i < BUF_LOCKS; i++) {
1071 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1072 NULL, MUTEX_DEFAULT, NULL);
1076 #define ARC_MINTIME (hz>>4) /* 62 ms */
1079 arc_cksum_verify(arc_buf_t *buf)
1083 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1086 mutex_enter(&buf->b_hdr->b_freeze_lock);
1087 if (buf->b_hdr->b_freeze_cksum == NULL ||
1088 (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1089 mutex_exit(&buf->b_hdr->b_freeze_lock);
1092 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1093 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1094 panic("buffer modified while frozen!");
1095 mutex_exit(&buf->b_hdr->b_freeze_lock);
1099 arc_cksum_equal(arc_buf_t *buf)
1104 mutex_enter(&buf->b_hdr->b_freeze_lock);
1105 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1106 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1107 mutex_exit(&buf->b_hdr->b_freeze_lock);
1113 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1115 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1118 mutex_enter(&buf->b_hdr->b_freeze_lock);
1119 if (buf->b_hdr->b_freeze_cksum != NULL) {
1120 mutex_exit(&buf->b_hdr->b_freeze_lock);
1123 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1124 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1125 buf->b_hdr->b_freeze_cksum);
1126 mutex_exit(&buf->b_hdr->b_freeze_lock);
1129 #endif /* illumos */
1134 typedef struct procctl {
1142 arc_buf_unwatch(arc_buf_t *buf)
1149 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1150 ctl.prwatch.pr_size = 0;
1151 ctl.prwatch.pr_wflags = 0;
1152 result = write(arc_procfd, &ctl, sizeof (ctl));
1153 ASSERT3U(result, ==, sizeof (ctl));
1160 arc_buf_watch(arc_buf_t *buf)
1167 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1168 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1169 ctl.prwatch.pr_wflags = WA_WRITE;
1170 result = write(arc_procfd, &ctl, sizeof (ctl));
1171 ASSERT3U(result, ==, sizeof (ctl));
1175 #endif /* illumos */
1178 arc_buf_thaw(arc_buf_t *buf)
1180 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1181 if (buf->b_hdr->b_state != arc_anon)
1182 panic("modifying non-anon buffer!");
1183 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1184 panic("modifying buffer while i/o in progress!");
1185 arc_cksum_verify(buf);
1188 mutex_enter(&buf->b_hdr->b_freeze_lock);
1189 if (buf->b_hdr->b_freeze_cksum != NULL) {
1190 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1191 buf->b_hdr->b_freeze_cksum = NULL;
1194 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1195 if (buf->b_hdr->b_thawed)
1196 kmem_free(buf->b_hdr->b_thawed, 1);
1197 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1200 mutex_exit(&buf->b_hdr->b_freeze_lock);
1203 arc_buf_unwatch(buf);
1204 #endif /* illumos */
1208 arc_buf_freeze(arc_buf_t *buf)
1210 kmutex_t *hash_lock;
1212 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1215 hash_lock = HDR_LOCK(buf->b_hdr);
1216 mutex_enter(hash_lock);
1218 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1219 buf->b_hdr->b_state == arc_anon);
1220 arc_cksum_compute(buf, B_FALSE);
1221 mutex_exit(hash_lock);
1226 get_buf_info(arc_buf_hdr_t *ab, arc_state_t *state, list_t **list, kmutex_t **lock)
1228 uint64_t buf_hashid = buf_hash(ab->b_spa, &ab->b_dva, ab->b_birth);
1230 if (ab->b_type == ARC_BUFC_METADATA)
1231 buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1233 buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1234 buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1237 *list = &state->arcs_lists[buf_hashid];
1238 *lock = ARCS_LOCK(state, buf_hashid);
1243 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1245 ASSERT(MUTEX_HELD(hash_lock));
1247 if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1248 (ab->b_state != arc_anon)) {
1249 uint64_t delta = ab->b_size * ab->b_datacnt;
1250 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1254 get_buf_info(ab, ab->b_state, &list, &lock);
1255 ASSERT(!MUTEX_HELD(lock));
1257 ASSERT(list_link_active(&ab->b_arc_node));
1258 list_remove(list, ab);
1259 if (GHOST_STATE(ab->b_state)) {
1260 ASSERT0(ab->b_datacnt);
1261 ASSERT3P(ab->b_buf, ==, NULL);
1265 ASSERT3U(*size, >=, delta);
1266 atomic_add_64(size, -delta);
1268 /* remove the prefetch flag if we get a reference */
1269 if (ab->b_flags & ARC_PREFETCH)
1270 ab->b_flags &= ~ARC_PREFETCH;
1275 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1278 arc_state_t *state = ab->b_state;
1280 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1281 ASSERT(!GHOST_STATE(state));
1283 if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1284 (state != arc_anon)) {
1285 uint64_t *size = &state->arcs_lsize[ab->b_type];
1289 get_buf_info(ab, state, &list, &lock);
1290 ASSERT(!MUTEX_HELD(lock));
1292 ASSERT(!list_link_active(&ab->b_arc_node));
1293 list_insert_head(list, ab);
1294 ASSERT(ab->b_datacnt > 0);
1295 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1302 * Move the supplied buffer to the indicated state. The mutex
1303 * for the buffer must be held by the caller.
1306 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1308 arc_state_t *old_state = ab->b_state;
1309 int64_t refcnt = refcount_count(&ab->b_refcnt);
1310 uint64_t from_delta, to_delta;
1314 ASSERT(MUTEX_HELD(hash_lock));
1315 ASSERT(new_state != old_state);
1316 ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1317 ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1318 ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1320 from_delta = to_delta = ab->b_datacnt * ab->b_size;
1323 * If this buffer is evictable, transfer it from the
1324 * old state list to the new state list.
1327 if (old_state != arc_anon) {
1329 uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1331 get_buf_info(ab, old_state, &list, &lock);
1332 use_mutex = !MUTEX_HELD(lock);
1336 ASSERT(list_link_active(&ab->b_arc_node));
1337 list_remove(list, ab);
1340 * If prefetching out of the ghost cache,
1341 * we will have a non-zero datacnt.
1343 if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1344 /* ghost elements have a ghost size */
1345 ASSERT(ab->b_buf == NULL);
1346 from_delta = ab->b_size;
1348 ASSERT3U(*size, >=, from_delta);
1349 atomic_add_64(size, -from_delta);
1354 if (new_state != arc_anon) {
1356 uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1358 get_buf_info(ab, new_state, &list, &lock);
1359 use_mutex = !MUTEX_HELD(lock);
1363 list_insert_head(list, ab);
1365 /* ghost elements have a ghost size */
1366 if (GHOST_STATE(new_state)) {
1367 ASSERT(ab->b_datacnt == 0);
1368 ASSERT(ab->b_buf == NULL);
1369 to_delta = ab->b_size;
1371 atomic_add_64(size, to_delta);
1378 ASSERT(!BUF_EMPTY(ab));
1379 if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1380 buf_hash_remove(ab);
1382 /* adjust state sizes */
1384 atomic_add_64(&new_state->arcs_size, to_delta);
1386 ASSERT3U(old_state->arcs_size, >=, from_delta);
1387 atomic_add_64(&old_state->arcs_size, -from_delta);
1389 ab->b_state = new_state;
1391 /* adjust l2arc hdr stats */
1392 if (new_state == arc_l2c_only)
1393 l2arc_hdr_stat_add();
1394 else if (old_state == arc_l2c_only)
1395 l2arc_hdr_stat_remove();
1399 arc_space_consume(uint64_t space, arc_space_type_t type)
1401 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1404 case ARC_SPACE_DATA:
1405 ARCSTAT_INCR(arcstat_data_size, space);
1407 case ARC_SPACE_OTHER:
1408 ARCSTAT_INCR(arcstat_other_size, space);
1410 case ARC_SPACE_HDRS:
1411 ARCSTAT_INCR(arcstat_hdr_size, space);
1413 case ARC_SPACE_L2HDRS:
1414 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1418 atomic_add_64(&arc_meta_used, space);
1419 atomic_add_64(&arc_size, space);
1423 arc_space_return(uint64_t space, arc_space_type_t type)
1425 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1428 case ARC_SPACE_DATA:
1429 ARCSTAT_INCR(arcstat_data_size, -space);
1431 case ARC_SPACE_OTHER:
1432 ARCSTAT_INCR(arcstat_other_size, -space);
1434 case ARC_SPACE_HDRS:
1435 ARCSTAT_INCR(arcstat_hdr_size, -space);
1437 case ARC_SPACE_L2HDRS:
1438 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1442 ASSERT(arc_meta_used >= space);
1443 if (arc_meta_max < arc_meta_used)
1444 arc_meta_max = arc_meta_used;
1445 atomic_add_64(&arc_meta_used, -space);
1446 ASSERT(arc_size >= space);
1447 atomic_add_64(&arc_size, -space);
1451 arc_data_buf_alloc(uint64_t size)
1453 if (arc_evict_needed(ARC_BUFC_DATA))
1454 cv_signal(&arc_reclaim_thr_cv);
1455 atomic_add_64(&arc_size, size);
1456 return (zio_data_buf_alloc(size));
1460 arc_data_buf_free(void *buf, uint64_t size)
1462 zio_data_buf_free(buf, size);
1463 ASSERT(arc_size >= size);
1464 atomic_add_64(&arc_size, -size);
1468 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1473 ASSERT3U(size, >, 0);
1474 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1475 ASSERT(BUF_EMPTY(hdr));
1478 hdr->b_spa = spa_load_guid(spa);
1479 hdr->b_state = arc_anon;
1480 hdr->b_arc_access = 0;
1481 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1484 buf->b_efunc = NULL;
1485 buf->b_private = NULL;
1488 arc_get_data_buf(buf);
1491 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1492 (void) refcount_add(&hdr->b_refcnt, tag);
1497 static char *arc_onloan_tag = "onloan";
1500 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1501 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1502 * buffers must be returned to the arc before they can be used by the DMU or
1506 arc_loan_buf(spa_t *spa, int size)
1510 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1512 atomic_add_64(&arc_loaned_bytes, size);
1517 * Return a loaned arc buffer to the arc.
1520 arc_return_buf(arc_buf_t *buf, void *tag)
1522 arc_buf_hdr_t *hdr = buf->b_hdr;
1524 ASSERT(buf->b_data != NULL);
1525 (void) refcount_add(&hdr->b_refcnt, tag);
1526 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1528 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1531 /* Detach an arc_buf from a dbuf (tag) */
1533 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1537 ASSERT(buf->b_data != NULL);
1539 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1540 (void) refcount_remove(&hdr->b_refcnt, tag);
1541 buf->b_efunc = NULL;
1542 buf->b_private = NULL;
1544 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1548 arc_buf_clone(arc_buf_t *from)
1551 arc_buf_hdr_t *hdr = from->b_hdr;
1552 uint64_t size = hdr->b_size;
1554 ASSERT(hdr->b_state != arc_anon);
1556 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1559 buf->b_efunc = NULL;
1560 buf->b_private = NULL;
1561 buf->b_next = hdr->b_buf;
1563 arc_get_data_buf(buf);
1564 bcopy(from->b_data, buf->b_data, size);
1567 * This buffer already exists in the arc so create a duplicate
1568 * copy for the caller. If the buffer is associated with user data
1569 * then track the size and number of duplicates. These stats will be
1570 * updated as duplicate buffers are created and destroyed.
1572 if (hdr->b_type == ARC_BUFC_DATA) {
1573 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1574 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1576 hdr->b_datacnt += 1;
1581 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1584 kmutex_t *hash_lock;
1587 * Check to see if this buffer is evicted. Callers
1588 * must verify b_data != NULL to know if the add_ref
1591 mutex_enter(&buf->b_evict_lock);
1592 if (buf->b_data == NULL) {
1593 mutex_exit(&buf->b_evict_lock);
1596 hash_lock = HDR_LOCK(buf->b_hdr);
1597 mutex_enter(hash_lock);
1599 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1600 mutex_exit(&buf->b_evict_lock);
1602 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1603 add_reference(hdr, hash_lock, tag);
1604 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1605 arc_access(hdr, hash_lock);
1606 mutex_exit(hash_lock);
1607 ARCSTAT_BUMP(arcstat_hits);
1608 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1609 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1610 data, metadata, hits);
1614 * Free the arc data buffer. If it is an l2arc write in progress,
1615 * the buffer is placed on l2arc_free_on_write to be freed later.
1618 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1620 arc_buf_hdr_t *hdr = buf->b_hdr;
1622 if (HDR_L2_WRITING(hdr)) {
1623 l2arc_data_free_t *df;
1624 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1625 df->l2df_data = buf->b_data;
1626 df->l2df_size = hdr->b_size;
1627 df->l2df_func = free_func;
1628 mutex_enter(&l2arc_free_on_write_mtx);
1629 list_insert_head(l2arc_free_on_write, df);
1630 mutex_exit(&l2arc_free_on_write_mtx);
1631 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1633 free_func(buf->b_data, hdr->b_size);
1638 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
1642 /* free up data associated with the buf */
1644 arc_state_t *state = buf->b_hdr->b_state;
1645 uint64_t size = buf->b_hdr->b_size;
1646 arc_buf_contents_t type = buf->b_hdr->b_type;
1648 arc_cksum_verify(buf);
1650 arc_buf_unwatch(buf);
1651 #endif /* illumos */
1654 if (type == ARC_BUFC_METADATA) {
1655 arc_buf_data_free(buf, zio_buf_free);
1656 arc_space_return(size, ARC_SPACE_DATA);
1658 ASSERT(type == ARC_BUFC_DATA);
1659 arc_buf_data_free(buf, zio_data_buf_free);
1660 ARCSTAT_INCR(arcstat_data_size, -size);
1661 atomic_add_64(&arc_size, -size);
1664 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1665 uint64_t *cnt = &state->arcs_lsize[type];
1667 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1668 ASSERT(state != arc_anon);
1670 ASSERT3U(*cnt, >=, size);
1671 atomic_add_64(cnt, -size);
1673 ASSERT3U(state->arcs_size, >=, size);
1674 atomic_add_64(&state->arcs_size, -size);
1678 * If we're destroying a duplicate buffer make sure
1679 * that the appropriate statistics are updated.
1681 if (buf->b_hdr->b_datacnt > 1 &&
1682 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1683 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1684 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1686 ASSERT(buf->b_hdr->b_datacnt > 0);
1687 buf->b_hdr->b_datacnt -= 1;
1690 /* only remove the buf if requested */
1694 /* remove the buf from the hdr list */
1695 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1697 *bufp = buf->b_next;
1700 ASSERT(buf->b_efunc == NULL);
1702 /* clean up the buf */
1704 kmem_cache_free(buf_cache, buf);
1708 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1710 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1711 ASSERT3P(hdr->b_state, ==, arc_anon);
1712 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1713 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1715 if (l2hdr != NULL) {
1716 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1718 * To prevent arc_free() and l2arc_evict() from
1719 * attempting to free the same buffer at the same time,
1720 * a FREE_IN_PROGRESS flag is given to arc_free() to
1721 * give it priority. l2arc_evict() can't destroy this
1722 * header while we are waiting on l2arc_buflist_mtx.
1724 * The hdr may be removed from l2ad_buflist before we
1725 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1727 if (!buflist_held) {
1728 mutex_enter(&l2arc_buflist_mtx);
1729 l2hdr = hdr->b_l2hdr;
1732 if (l2hdr != NULL) {
1733 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1735 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1736 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1737 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1738 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1739 if (hdr->b_state == arc_l2c_only)
1740 l2arc_hdr_stat_remove();
1741 hdr->b_l2hdr = NULL;
1745 mutex_exit(&l2arc_buflist_mtx);
1748 if (!BUF_EMPTY(hdr)) {
1749 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1750 buf_discard_identity(hdr);
1752 while (hdr->b_buf) {
1753 arc_buf_t *buf = hdr->b_buf;
1756 mutex_enter(&arc_eviction_mtx);
1757 mutex_enter(&buf->b_evict_lock);
1758 ASSERT(buf->b_hdr != NULL);
1759 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1760 hdr->b_buf = buf->b_next;
1761 buf->b_hdr = &arc_eviction_hdr;
1762 buf->b_next = arc_eviction_list;
1763 arc_eviction_list = buf;
1764 mutex_exit(&buf->b_evict_lock);
1765 mutex_exit(&arc_eviction_mtx);
1767 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1770 if (hdr->b_freeze_cksum != NULL) {
1771 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1772 hdr->b_freeze_cksum = NULL;
1774 if (hdr->b_thawed) {
1775 kmem_free(hdr->b_thawed, 1);
1776 hdr->b_thawed = NULL;
1779 ASSERT(!list_link_active(&hdr->b_arc_node));
1780 ASSERT3P(hdr->b_hash_next, ==, NULL);
1781 ASSERT3P(hdr->b_acb, ==, NULL);
1782 kmem_cache_free(hdr_cache, hdr);
1786 arc_buf_free(arc_buf_t *buf, void *tag)
1788 arc_buf_hdr_t *hdr = buf->b_hdr;
1789 int hashed = hdr->b_state != arc_anon;
1791 ASSERT(buf->b_efunc == NULL);
1792 ASSERT(buf->b_data != NULL);
1795 kmutex_t *hash_lock = HDR_LOCK(hdr);
1797 mutex_enter(hash_lock);
1799 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1801 (void) remove_reference(hdr, hash_lock, tag);
1802 if (hdr->b_datacnt > 1) {
1803 arc_buf_destroy(buf, FALSE, TRUE);
1805 ASSERT(buf == hdr->b_buf);
1806 ASSERT(buf->b_efunc == NULL);
1807 hdr->b_flags |= ARC_BUF_AVAILABLE;
1809 mutex_exit(hash_lock);
1810 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1813 * We are in the middle of an async write. Don't destroy
1814 * this buffer unless the write completes before we finish
1815 * decrementing the reference count.
1817 mutex_enter(&arc_eviction_mtx);
1818 (void) remove_reference(hdr, NULL, tag);
1819 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1820 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1821 mutex_exit(&arc_eviction_mtx);
1823 arc_hdr_destroy(hdr);
1825 if (remove_reference(hdr, NULL, tag) > 0)
1826 arc_buf_destroy(buf, FALSE, TRUE);
1828 arc_hdr_destroy(hdr);
1833 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1835 arc_buf_hdr_t *hdr = buf->b_hdr;
1836 kmutex_t *hash_lock = HDR_LOCK(hdr);
1837 boolean_t no_callback = (buf->b_efunc == NULL);
1839 if (hdr->b_state == arc_anon) {
1840 ASSERT(hdr->b_datacnt == 1);
1841 arc_buf_free(buf, tag);
1842 return (no_callback);
1845 mutex_enter(hash_lock);
1847 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1848 ASSERT(hdr->b_state != arc_anon);
1849 ASSERT(buf->b_data != NULL);
1851 (void) remove_reference(hdr, hash_lock, tag);
1852 if (hdr->b_datacnt > 1) {
1854 arc_buf_destroy(buf, FALSE, TRUE);
1855 } else if (no_callback) {
1856 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1857 ASSERT(buf->b_efunc == NULL);
1858 hdr->b_flags |= ARC_BUF_AVAILABLE;
1860 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1861 refcount_is_zero(&hdr->b_refcnt));
1862 mutex_exit(hash_lock);
1863 return (no_callback);
1867 arc_buf_size(arc_buf_t *buf)
1869 return (buf->b_hdr->b_size);
1873 * Called from the DMU to determine if the current buffer should be
1874 * evicted. In order to ensure proper locking, the eviction must be initiated
1875 * from the DMU. Return true if the buffer is associated with user data and
1876 * duplicate buffers still exist.
1879 arc_buf_eviction_needed(arc_buf_t *buf)
1882 boolean_t evict_needed = B_FALSE;
1884 if (zfs_disable_dup_eviction)
1887 mutex_enter(&buf->b_evict_lock);
1891 * We are in arc_do_user_evicts(); let that function
1892 * perform the eviction.
1894 ASSERT(buf->b_data == NULL);
1895 mutex_exit(&buf->b_evict_lock);
1897 } else if (buf->b_data == NULL) {
1899 * We have already been added to the arc eviction list;
1900 * recommend eviction.
1902 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1903 mutex_exit(&buf->b_evict_lock);
1907 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1908 evict_needed = B_TRUE;
1910 mutex_exit(&buf->b_evict_lock);
1911 return (evict_needed);
1915 * Evict buffers from list until we've removed the specified number of
1916 * bytes. Move the removed buffers to the appropriate evict state.
1917 * If the recycle flag is set, then attempt to "recycle" a buffer:
1918 * - look for a buffer to evict that is `bytes' long.
1919 * - return the data block from this buffer rather than freeing it.
1920 * This flag is used by callers that are trying to make space for a
1921 * new buffer in a full arc cache.
1923 * This function makes a "best effort". It skips over any buffers
1924 * it can't get a hash_lock on, and so may not catch all candidates.
1925 * It may also return without evicting as much space as requested.
1928 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1929 arc_buf_contents_t type)
1931 arc_state_t *evicted_state;
1932 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1933 int64_t bytes_remaining;
1934 arc_buf_hdr_t *ab, *ab_prev = NULL;
1935 list_t *evicted_list, *list, *evicted_list_start, *list_start;
1936 kmutex_t *lock, *evicted_lock;
1937 kmutex_t *hash_lock;
1938 boolean_t have_lock;
1939 void *stolen = NULL;
1940 static int evict_metadata_offset, evict_data_offset;
1941 int i, idx, offset, list_count, count;
1943 ASSERT(state == arc_mru || state == arc_mfu);
1945 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1947 if (type == ARC_BUFC_METADATA) {
1949 list_count = ARC_BUFC_NUMMETADATALISTS;
1950 list_start = &state->arcs_lists[0];
1951 evicted_list_start = &evicted_state->arcs_lists[0];
1952 idx = evict_metadata_offset;
1954 offset = ARC_BUFC_NUMMETADATALISTS;
1955 list_start = &state->arcs_lists[offset];
1956 evicted_list_start = &evicted_state->arcs_lists[offset];
1957 list_count = ARC_BUFC_NUMDATALISTS;
1958 idx = evict_data_offset;
1960 bytes_remaining = evicted_state->arcs_lsize[type];
1964 list = &list_start[idx];
1965 evicted_list = &evicted_list_start[idx];
1966 lock = ARCS_LOCK(state, (offset + idx));
1967 evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
1970 mutex_enter(evicted_lock);
1972 for (ab = list_tail(list); ab; ab = ab_prev) {
1973 ab_prev = list_prev(list, ab);
1974 bytes_remaining -= (ab->b_size * ab->b_datacnt);
1975 /* prefetch buffers have a minimum lifespan */
1976 if (HDR_IO_IN_PROGRESS(ab) ||
1977 (spa && ab->b_spa != spa) ||
1978 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1979 ddi_get_lbolt() - ab->b_arc_access <
1980 arc_min_prefetch_lifespan)) {
1984 /* "lookahead" for better eviction candidate */
1985 if (recycle && ab->b_size != bytes &&
1986 ab_prev && ab_prev->b_size == bytes)
1988 hash_lock = HDR_LOCK(ab);
1989 have_lock = MUTEX_HELD(hash_lock);
1990 if (have_lock || mutex_tryenter(hash_lock)) {
1991 ASSERT0(refcount_count(&ab->b_refcnt));
1992 ASSERT(ab->b_datacnt > 0);
1994 arc_buf_t *buf = ab->b_buf;
1995 if (!mutex_tryenter(&buf->b_evict_lock)) {
2000 bytes_evicted += ab->b_size;
2001 if (recycle && ab->b_type == type &&
2002 ab->b_size == bytes &&
2003 !HDR_L2_WRITING(ab)) {
2004 stolen = buf->b_data;
2009 mutex_enter(&arc_eviction_mtx);
2010 arc_buf_destroy(buf,
2011 buf->b_data == stolen, FALSE);
2012 ab->b_buf = buf->b_next;
2013 buf->b_hdr = &arc_eviction_hdr;
2014 buf->b_next = arc_eviction_list;
2015 arc_eviction_list = buf;
2016 mutex_exit(&arc_eviction_mtx);
2017 mutex_exit(&buf->b_evict_lock);
2019 mutex_exit(&buf->b_evict_lock);
2020 arc_buf_destroy(buf,
2021 buf->b_data == stolen, TRUE);
2026 ARCSTAT_INCR(arcstat_evict_l2_cached,
2029 if (l2arc_write_eligible(ab->b_spa, ab)) {
2030 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2034 arcstat_evict_l2_ineligible,
2039 if (ab->b_datacnt == 0) {
2040 arc_change_state(evicted_state, ab, hash_lock);
2041 ASSERT(HDR_IN_HASH_TABLE(ab));
2042 ab->b_flags |= ARC_IN_HASH_TABLE;
2043 ab->b_flags &= ~ARC_BUF_AVAILABLE;
2044 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2047 mutex_exit(hash_lock);
2048 if (bytes >= 0 && bytes_evicted >= bytes)
2050 if (bytes_remaining > 0) {
2051 mutex_exit(evicted_lock);
2053 idx = ((idx + 1) & (list_count - 1));
2062 mutex_exit(evicted_lock);
2065 idx = ((idx + 1) & (list_count - 1));
2068 if (bytes_evicted < bytes) {
2069 if (count < list_count)
2072 dprintf("only evicted %lld bytes from %x",
2073 (longlong_t)bytes_evicted, state);
2075 if (type == ARC_BUFC_METADATA)
2076 evict_metadata_offset = idx;
2078 evict_data_offset = idx;
2081 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2084 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2087 * We have just evicted some data into the ghost state, make
2088 * sure we also adjust the ghost state size if necessary.
2091 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
2092 int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
2093 arc_mru_ghost->arcs_size - arc_c;
2095 if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
2097 MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
2098 arc_evict_ghost(arc_mru_ghost, 0, todelete);
2099 } else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
2100 int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
2101 arc_mru_ghost->arcs_size +
2102 arc_mfu_ghost->arcs_size - arc_c);
2103 arc_evict_ghost(arc_mfu_ghost, 0, todelete);
2107 ARCSTAT_BUMP(arcstat_stolen);
2113 * Remove buffers from list until we've removed the specified number of
2114 * bytes. Destroy the buffers that are removed.
2117 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2119 arc_buf_hdr_t *ab, *ab_prev;
2120 arc_buf_hdr_t marker = { 0 };
2121 list_t *list, *list_start;
2122 kmutex_t *hash_lock, *lock;
2123 uint64_t bytes_deleted = 0;
2124 uint64_t bufs_skipped = 0;
2125 static int evict_offset;
2126 int list_count, idx = evict_offset;
2127 int offset, count = 0;
2129 ASSERT(GHOST_STATE(state));
2132 * data lists come after metadata lists
2134 list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2135 list_count = ARC_BUFC_NUMDATALISTS;
2136 offset = ARC_BUFC_NUMMETADATALISTS;
2139 list = &list_start[idx];
2140 lock = ARCS_LOCK(state, idx + offset);
2143 for (ab = list_tail(list); ab; ab = ab_prev) {
2144 ab_prev = list_prev(list, ab);
2145 if (spa && ab->b_spa != spa)
2148 /* ignore markers */
2152 hash_lock = HDR_LOCK(ab);
2153 /* caller may be trying to modify this buffer, skip it */
2154 if (MUTEX_HELD(hash_lock))
2156 if (mutex_tryenter(hash_lock)) {
2157 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2158 ASSERT(ab->b_buf == NULL);
2159 ARCSTAT_BUMP(arcstat_deleted);
2160 bytes_deleted += ab->b_size;
2162 if (ab->b_l2hdr != NULL) {
2164 * This buffer is cached on the 2nd Level ARC;
2165 * don't destroy the header.
2167 arc_change_state(arc_l2c_only, ab, hash_lock);
2168 mutex_exit(hash_lock);
2170 arc_change_state(arc_anon, ab, hash_lock);
2171 mutex_exit(hash_lock);
2172 arc_hdr_destroy(ab);
2175 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2176 if (bytes >= 0 && bytes_deleted >= bytes)
2178 } else if (bytes < 0) {
2180 * Insert a list marker and then wait for the
2181 * hash lock to become available. Once its
2182 * available, restart from where we left off.
2184 list_insert_after(list, ab, &marker);
2186 mutex_enter(hash_lock);
2187 mutex_exit(hash_lock);
2189 ab_prev = list_prev(list, &marker);
2190 list_remove(list, &marker);
2195 idx = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2198 if (count < list_count)
2202 if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2203 (bytes < 0 || bytes_deleted < bytes)) {
2204 list_start = &state->arcs_lists[0];
2205 list_count = ARC_BUFC_NUMMETADATALISTS;
2211 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2215 if (bytes_deleted < bytes)
2216 dprintf("only deleted %lld bytes from %p",
2217 (longlong_t)bytes_deleted, state);
2223 int64_t adjustment, delta;
2229 adjustment = MIN((int64_t)(arc_size - arc_c),
2230 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2233 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2234 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2235 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2236 adjustment -= delta;
2239 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2240 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2241 (void) arc_evict(arc_mru, 0, delta, FALSE,
2249 adjustment = arc_size - arc_c;
2251 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2252 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2253 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2254 adjustment -= delta;
2257 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2258 int64_t delta = MIN(adjustment,
2259 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2260 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2265 * Adjust ghost lists
2268 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2270 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2271 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2272 arc_evict_ghost(arc_mru_ghost, 0, delta);
2276 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2278 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2279 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2280 arc_evict_ghost(arc_mfu_ghost, 0, delta);
2285 arc_do_user_evicts(void)
2287 static arc_buf_t *tmp_arc_eviction_list;
2290 * Move list over to avoid LOR
2293 mutex_enter(&arc_eviction_mtx);
2294 tmp_arc_eviction_list = arc_eviction_list;
2295 arc_eviction_list = NULL;
2296 mutex_exit(&arc_eviction_mtx);
2298 while (tmp_arc_eviction_list != NULL) {
2299 arc_buf_t *buf = tmp_arc_eviction_list;
2300 tmp_arc_eviction_list = buf->b_next;
2301 mutex_enter(&buf->b_evict_lock);
2303 mutex_exit(&buf->b_evict_lock);
2305 if (buf->b_efunc != NULL)
2306 VERIFY(buf->b_efunc(buf) == 0);
2308 buf->b_efunc = NULL;
2309 buf->b_private = NULL;
2310 kmem_cache_free(buf_cache, buf);
2313 if (arc_eviction_list != NULL)
2318 * Flush all *evictable* data from the cache for the given spa.
2319 * NOTE: this will not touch "active" (i.e. referenced) data.
2322 arc_flush(spa_t *spa)
2327 guid = spa_load_guid(spa);
2329 while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2330 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2334 while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2335 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2339 while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2340 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2344 while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2345 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2350 arc_evict_ghost(arc_mru_ghost, guid, -1);
2351 arc_evict_ghost(arc_mfu_ghost, guid, -1);
2353 mutex_enter(&arc_reclaim_thr_lock);
2354 arc_do_user_evicts();
2355 mutex_exit(&arc_reclaim_thr_lock);
2356 ASSERT(spa || arc_eviction_list == NULL);
2362 if (arc_c > arc_c_min) {
2366 to_free = arc_c >> arc_shrink_shift;
2368 to_free = arc_c >> arc_shrink_shift;
2370 if (arc_c > arc_c_min + to_free)
2371 atomic_add_64(&arc_c, -to_free);
2375 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2376 if (arc_c > arc_size)
2377 arc_c = MAX(arc_size, arc_c_min);
2379 arc_p = (arc_c >> 1);
2380 ASSERT(arc_c >= arc_c_min);
2381 ASSERT((int64_t)arc_p >= 0);
2384 if (arc_size > arc_c)
2388 static int needfree = 0;
2391 arc_reclaim_needed(void)
2400 * Cooperate with pagedaemon when it's time for it to scan
2401 * and reclaim some pages.
2403 if (vm_paging_needed())
2408 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2413 * check that we're out of range of the pageout scanner. It starts to
2414 * schedule paging if freemem is less than lotsfree and needfree.
2415 * lotsfree is the high-water mark for pageout, and needfree is the
2416 * number of needed free pages. We add extra pages here to make sure
2417 * the scanner doesn't start up while we're freeing memory.
2419 if (freemem < lotsfree + needfree + extra)
2423 * check to make sure that swapfs has enough space so that anon
2424 * reservations can still succeed. anon_resvmem() checks that the
2425 * availrmem is greater than swapfs_minfree, and the number of reserved
2426 * swap pages. We also add a bit of extra here just to prevent
2427 * circumstances from getting really dire.
2429 if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2434 * If we're on an i386 platform, it's possible that we'll exhaust the
2435 * kernel heap space before we ever run out of available physical
2436 * memory. Most checks of the size of the heap_area compare against
2437 * tune.t_minarmem, which is the minimum available real memory that we
2438 * can have in the system. However, this is generally fixed at 25 pages
2439 * which is so low that it's useless. In this comparison, we seek to
2440 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2441 * heap is allocated. (Or, in the calculation, if less than 1/4th is
2444 if (btop(vmem_size(heap_arena, VMEM_FREE)) <
2445 (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
2449 if (kmem_used() > (kmem_size() * 3) / 4)
2454 if (spa_get_random(100) == 0)
2460 extern kmem_cache_t *zio_buf_cache[];
2461 extern kmem_cache_t *zio_data_buf_cache[];
2464 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2467 kmem_cache_t *prev_cache = NULL;
2468 kmem_cache_t *prev_data_cache = NULL;
2471 if (arc_meta_used >= arc_meta_limit) {
2473 * We are exceeding our meta-data cache limit.
2474 * Purge some DNLC entries to release holds on meta-data.
2476 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2480 * Reclaim unused memory from all kmem caches.
2487 * An aggressive reclamation will shrink the cache size as well as
2488 * reap free buffers from the arc kmem caches.
2490 if (strat == ARC_RECLAIM_AGGR)
2493 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2494 if (zio_buf_cache[i] != prev_cache) {
2495 prev_cache = zio_buf_cache[i];
2496 kmem_cache_reap_now(zio_buf_cache[i]);
2498 if (zio_data_buf_cache[i] != prev_data_cache) {
2499 prev_data_cache = zio_data_buf_cache[i];
2500 kmem_cache_reap_now(zio_data_buf_cache[i]);
2503 kmem_cache_reap_now(buf_cache);
2504 kmem_cache_reap_now(hdr_cache);
2508 arc_reclaim_thread(void *dummy __unused)
2510 clock_t growtime = 0;
2511 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2514 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2516 mutex_enter(&arc_reclaim_thr_lock);
2517 while (arc_thread_exit == 0) {
2518 if (arc_reclaim_needed()) {
2521 if (last_reclaim == ARC_RECLAIM_CONS) {
2522 last_reclaim = ARC_RECLAIM_AGGR;
2524 last_reclaim = ARC_RECLAIM_CONS;
2528 last_reclaim = ARC_RECLAIM_AGGR;
2532 /* reset the growth delay for every reclaim */
2533 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2535 if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2537 * If needfree is TRUE our vm_lowmem hook
2538 * was called and in that case we must free some
2539 * memory, so switch to aggressive mode.
2542 last_reclaim = ARC_RECLAIM_AGGR;
2544 arc_kmem_reap_now(last_reclaim);
2547 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2548 arc_no_grow = FALSE;
2553 if (arc_eviction_list != NULL)
2554 arc_do_user_evicts();
2563 /* block until needed, or one second, whichever is shorter */
2564 CALLB_CPR_SAFE_BEGIN(&cpr);
2565 (void) cv_timedwait(&arc_reclaim_thr_cv,
2566 &arc_reclaim_thr_lock, hz);
2567 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2570 arc_thread_exit = 0;
2571 cv_broadcast(&arc_reclaim_thr_cv);
2572 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2577 * Adapt arc info given the number of bytes we are trying to add and
2578 * the state that we are comming from. This function is only called
2579 * when we are adding new content to the cache.
2582 arc_adapt(int bytes, arc_state_t *state)
2585 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2587 if (state == arc_l2c_only)
2592 * Adapt the target size of the MRU list:
2593 * - if we just hit in the MRU ghost list, then increase
2594 * the target size of the MRU list.
2595 * - if we just hit in the MFU ghost list, then increase
2596 * the target size of the MFU list by decreasing the
2597 * target size of the MRU list.
2599 if (state == arc_mru_ghost) {
2600 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2601 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2602 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2604 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2605 } else if (state == arc_mfu_ghost) {
2608 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2609 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2610 mult = MIN(mult, 10);
2612 delta = MIN(bytes * mult, arc_p);
2613 arc_p = MAX(arc_p_min, arc_p - delta);
2615 ASSERT((int64_t)arc_p >= 0);
2617 if (arc_reclaim_needed()) {
2618 cv_signal(&arc_reclaim_thr_cv);
2625 if (arc_c >= arc_c_max)
2629 * If we're within (2 * maxblocksize) bytes of the target
2630 * cache size, increment the target cache size
2632 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2633 atomic_add_64(&arc_c, (int64_t)bytes);
2634 if (arc_c > arc_c_max)
2636 else if (state == arc_anon)
2637 atomic_add_64(&arc_p, (int64_t)bytes);
2641 ASSERT((int64_t)arc_p >= 0);
2645 * Check if the cache has reached its limits and eviction is required
2649 arc_evict_needed(arc_buf_contents_t type)
2651 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2657 * If zio data pages are being allocated out of a separate heap segment,
2658 * then enforce that the size of available vmem for this area remains
2659 * above about 1/32nd free.
2661 if (type == ARC_BUFC_DATA && zio_arena != NULL &&
2662 vmem_size(zio_arena, VMEM_FREE) <
2663 (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
2668 if (arc_reclaim_needed())
2671 return (arc_size > arc_c);
2675 * The buffer, supplied as the first argument, needs a data block.
2676 * So, if we are at cache max, determine which cache should be victimized.
2677 * We have the following cases:
2679 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2680 * In this situation if we're out of space, but the resident size of the MFU is
2681 * under the limit, victimize the MFU cache to satisfy this insertion request.
2683 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2684 * Here, we've used up all of the available space for the MRU, so we need to
2685 * evict from our own cache instead. Evict from the set of resident MRU
2688 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2689 * c minus p represents the MFU space in the cache, since p is the size of the
2690 * cache that is dedicated to the MRU. In this situation there's still space on
2691 * the MFU side, so the MRU side needs to be victimized.
2693 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2694 * MFU's resident set is consuming more space than it has been allotted. In
2695 * this situation, we must victimize our own cache, the MFU, for this insertion.
2698 arc_get_data_buf(arc_buf_t *buf)
2700 arc_state_t *state = buf->b_hdr->b_state;
2701 uint64_t size = buf->b_hdr->b_size;
2702 arc_buf_contents_t type = buf->b_hdr->b_type;
2704 arc_adapt(size, state);
2707 * We have not yet reached cache maximum size,
2708 * just allocate a new buffer.
2710 if (!arc_evict_needed(type)) {
2711 if (type == ARC_BUFC_METADATA) {
2712 buf->b_data = zio_buf_alloc(size);
2713 arc_space_consume(size, ARC_SPACE_DATA);
2715 ASSERT(type == ARC_BUFC_DATA);
2716 buf->b_data = zio_data_buf_alloc(size);
2717 ARCSTAT_INCR(arcstat_data_size, size);
2718 atomic_add_64(&arc_size, size);
2724 * If we are prefetching from the mfu ghost list, this buffer
2725 * will end up on the mru list; so steal space from there.
2727 if (state == arc_mfu_ghost)
2728 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2729 else if (state == arc_mru_ghost)
2732 if (state == arc_mru || state == arc_anon) {
2733 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2734 state = (arc_mfu->arcs_lsize[type] >= size &&
2735 arc_p > mru_used) ? arc_mfu : arc_mru;
2738 uint64_t mfu_space = arc_c - arc_p;
2739 state = (arc_mru->arcs_lsize[type] >= size &&
2740 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2742 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2743 if (type == ARC_BUFC_METADATA) {
2744 buf->b_data = zio_buf_alloc(size);
2745 arc_space_consume(size, ARC_SPACE_DATA);
2747 ASSERT(type == ARC_BUFC_DATA);
2748 buf->b_data = zio_data_buf_alloc(size);
2749 ARCSTAT_INCR(arcstat_data_size, size);
2750 atomic_add_64(&arc_size, size);
2752 ARCSTAT_BUMP(arcstat_recycle_miss);
2754 ASSERT(buf->b_data != NULL);
2757 * Update the state size. Note that ghost states have a
2758 * "ghost size" and so don't need to be updated.
2760 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2761 arc_buf_hdr_t *hdr = buf->b_hdr;
2763 atomic_add_64(&hdr->b_state->arcs_size, size);
2764 if (list_link_active(&hdr->b_arc_node)) {
2765 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2766 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2769 * If we are growing the cache, and we are adding anonymous
2770 * data, and we have outgrown arc_p, update arc_p
2772 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2773 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2774 arc_p = MIN(arc_c, arc_p + size);
2776 ARCSTAT_BUMP(arcstat_allocated);
2780 * This routine is called whenever a buffer is accessed.
2781 * NOTE: the hash lock is dropped in this function.
2784 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2788 ASSERT(MUTEX_HELD(hash_lock));
2790 if (buf->b_state == arc_anon) {
2792 * This buffer is not in the cache, and does not
2793 * appear in our "ghost" list. Add the new buffer
2797 ASSERT(buf->b_arc_access == 0);
2798 buf->b_arc_access = ddi_get_lbolt();
2799 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2800 arc_change_state(arc_mru, buf, hash_lock);
2802 } else if (buf->b_state == arc_mru) {
2803 now = ddi_get_lbolt();
2806 * If this buffer is here because of a prefetch, then either:
2807 * - clear the flag if this is a "referencing" read
2808 * (any subsequent access will bump this into the MFU state).
2810 * - move the buffer to the head of the list if this is
2811 * another prefetch (to make it less likely to be evicted).
2813 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2814 if (refcount_count(&buf->b_refcnt) == 0) {
2815 ASSERT(list_link_active(&buf->b_arc_node));
2817 buf->b_flags &= ~ARC_PREFETCH;
2818 ARCSTAT_BUMP(arcstat_mru_hits);
2820 buf->b_arc_access = now;
2825 * This buffer has been "accessed" only once so far,
2826 * but it is still in the cache. Move it to the MFU
2829 if (now > buf->b_arc_access + ARC_MINTIME) {
2831 * More than 125ms have passed since we
2832 * instantiated this buffer. Move it to the
2833 * most frequently used state.
2835 buf->b_arc_access = now;
2836 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2837 arc_change_state(arc_mfu, buf, hash_lock);
2839 ARCSTAT_BUMP(arcstat_mru_hits);
2840 } else if (buf->b_state == arc_mru_ghost) {
2841 arc_state_t *new_state;
2843 * This buffer has been "accessed" recently, but
2844 * was evicted from the cache. Move it to the
2848 if (buf->b_flags & ARC_PREFETCH) {
2849 new_state = arc_mru;
2850 if (refcount_count(&buf->b_refcnt) > 0)
2851 buf->b_flags &= ~ARC_PREFETCH;
2852 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2854 new_state = arc_mfu;
2855 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2858 buf->b_arc_access = ddi_get_lbolt();
2859 arc_change_state(new_state, buf, hash_lock);
2861 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2862 } else if (buf->b_state == arc_mfu) {
2864 * This buffer has been accessed more than once and is
2865 * still in the cache. Keep it in the MFU state.
2867 * NOTE: an add_reference() that occurred when we did
2868 * the arc_read() will have kicked this off the list.
2869 * If it was a prefetch, we will explicitly move it to
2870 * the head of the list now.
2872 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2873 ASSERT(refcount_count(&buf->b_refcnt) == 0);
2874 ASSERT(list_link_active(&buf->b_arc_node));
2876 ARCSTAT_BUMP(arcstat_mfu_hits);
2877 buf->b_arc_access = ddi_get_lbolt();
2878 } else if (buf->b_state == arc_mfu_ghost) {
2879 arc_state_t *new_state = arc_mfu;
2881 * This buffer has been accessed more than once but has
2882 * been evicted from the cache. Move it back to the
2886 if (buf->b_flags & ARC_PREFETCH) {
2888 * This is a prefetch access...
2889 * move this block back to the MRU state.
2891 ASSERT0(refcount_count(&buf->b_refcnt));
2892 new_state = arc_mru;
2895 buf->b_arc_access = ddi_get_lbolt();
2896 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2897 arc_change_state(new_state, buf, hash_lock);
2899 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2900 } else if (buf->b_state == arc_l2c_only) {
2902 * This buffer is on the 2nd Level ARC.
2905 buf->b_arc_access = ddi_get_lbolt();
2906 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2907 arc_change_state(arc_mfu, buf, hash_lock);
2909 ASSERT(!"invalid arc state");
2913 /* a generic arc_done_func_t which you can use */
2916 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2918 if (zio == NULL || zio->io_error == 0)
2919 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2920 VERIFY(arc_buf_remove_ref(buf, arg));
2923 /* a generic arc_done_func_t */
2925 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2927 arc_buf_t **bufp = arg;
2928 if (zio && zio->io_error) {
2929 VERIFY(arc_buf_remove_ref(buf, arg));
2933 ASSERT(buf->b_data);
2938 arc_read_done(zio_t *zio)
2940 arc_buf_hdr_t *hdr, *found;
2942 arc_buf_t *abuf; /* buffer we're assigning to callback */
2943 kmutex_t *hash_lock;
2944 arc_callback_t *callback_list, *acb;
2945 int freeable = FALSE;
2947 buf = zio->io_private;
2951 * The hdr was inserted into hash-table and removed from lists
2952 * prior to starting I/O. We should find this header, since
2953 * it's in the hash table, and it should be legit since it's
2954 * not possible to evict it during the I/O. The only possible
2955 * reason for it not to be found is if we were freed during the
2958 found = buf_hash_find(hdr->b_spa, &hdr->b_dva, hdr->b_birth,
2961 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
2962 (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2963 (found == hdr && HDR_L2_READING(hdr)));
2965 hdr->b_flags &= ~ARC_L2_EVICTED;
2966 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2967 hdr->b_flags &= ~ARC_L2CACHE;
2969 /* byteswap if necessary */
2970 callback_list = hdr->b_acb;
2971 ASSERT(callback_list != NULL);
2972 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
2973 dmu_object_byteswap_t bswap =
2974 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
2975 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2976 byteswap_uint64_array :
2977 dmu_ot_byteswap[bswap].ob_func;
2978 func(buf->b_data, hdr->b_size);
2981 arc_cksum_compute(buf, B_FALSE);
2984 #endif /* illumos */
2986 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
2988 * Only call arc_access on anonymous buffers. This is because
2989 * if we've issued an I/O for an evicted buffer, we've already
2990 * called arc_access (to prevent any simultaneous readers from
2991 * getting confused).
2993 arc_access(hdr, hash_lock);
2996 /* create copies of the data buffer for the callers */
2998 for (acb = callback_list; acb; acb = acb->acb_next) {
2999 if (acb->acb_done) {
3001 ARCSTAT_BUMP(arcstat_duplicate_reads);
3002 abuf = arc_buf_clone(buf);
3004 acb->acb_buf = abuf;
3009 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3010 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3012 ASSERT(buf->b_efunc == NULL);
3013 ASSERT(hdr->b_datacnt == 1);
3014 hdr->b_flags |= ARC_BUF_AVAILABLE;
3017 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3019 if (zio->io_error != 0) {
3020 hdr->b_flags |= ARC_IO_ERROR;
3021 if (hdr->b_state != arc_anon)
3022 arc_change_state(arc_anon, hdr, hash_lock);
3023 if (HDR_IN_HASH_TABLE(hdr))
3024 buf_hash_remove(hdr);
3025 freeable = refcount_is_zero(&hdr->b_refcnt);
3029 * Broadcast before we drop the hash_lock to avoid the possibility
3030 * that the hdr (and hence the cv) might be freed before we get to
3031 * the cv_broadcast().
3033 cv_broadcast(&hdr->b_cv);
3036 mutex_exit(hash_lock);
3039 * This block was freed while we waited for the read to
3040 * complete. It has been removed from the hash table and
3041 * moved to the anonymous state (so that it won't show up
3044 ASSERT3P(hdr->b_state, ==, arc_anon);
3045 freeable = refcount_is_zero(&hdr->b_refcnt);
3048 /* execute each callback and free its structure */
3049 while ((acb = callback_list) != NULL) {
3051 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3053 if (acb->acb_zio_dummy != NULL) {
3054 acb->acb_zio_dummy->io_error = zio->io_error;
3055 zio_nowait(acb->acb_zio_dummy);
3058 callback_list = acb->acb_next;
3059 kmem_free(acb, sizeof (arc_callback_t));
3063 arc_hdr_destroy(hdr);
3067 * "Read" the block block at the specified DVA (in bp) via the
3068 * cache. If the block is found in the cache, invoke the provided
3069 * callback immediately and return. Note that the `zio' parameter
3070 * in the callback will be NULL in this case, since no IO was
3071 * required. If the block is not in the cache pass the read request
3072 * on to the spa with a substitute callback function, so that the
3073 * requested block will be added to the cache.
3075 * If a read request arrives for a block that has a read in-progress,
3076 * either wait for the in-progress read to complete (and return the
3077 * results); or, if this is a read with a "done" func, add a record
3078 * to the read to invoke the "done" func when the read completes,
3079 * and return; or just return.
3081 * arc_read_done() will invoke all the requested "done" functions
3082 * for readers of this block.
3085 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3086 void *private, int priority, int zio_flags, uint32_t *arc_flags,
3087 const zbookmark_t *zb)
3090 arc_buf_t *buf = NULL;
3091 kmutex_t *hash_lock;
3093 uint64_t guid = spa_load_guid(spa);
3096 hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3098 if (hdr && hdr->b_datacnt > 0) {
3100 *arc_flags |= ARC_CACHED;
3102 if (HDR_IO_IN_PROGRESS(hdr)) {
3104 if (*arc_flags & ARC_WAIT) {
3105 cv_wait(&hdr->b_cv, hash_lock);
3106 mutex_exit(hash_lock);
3109 ASSERT(*arc_flags & ARC_NOWAIT);
3112 arc_callback_t *acb = NULL;
3114 acb = kmem_zalloc(sizeof (arc_callback_t),
3116 acb->acb_done = done;
3117 acb->acb_private = private;
3119 acb->acb_zio_dummy = zio_null(pio,
3120 spa, NULL, NULL, NULL, zio_flags);
3122 ASSERT(acb->acb_done != NULL);
3123 acb->acb_next = hdr->b_acb;
3125 add_reference(hdr, hash_lock, private);
3126 mutex_exit(hash_lock);
3129 mutex_exit(hash_lock);
3133 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3136 add_reference(hdr, hash_lock, private);
3138 * If this block is already in use, create a new
3139 * copy of the data so that we will be guaranteed
3140 * that arc_release() will always succeed.
3144 ASSERT(buf->b_data);
3145 if (HDR_BUF_AVAILABLE(hdr)) {
3146 ASSERT(buf->b_efunc == NULL);
3147 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3149 buf = arc_buf_clone(buf);
3152 } else if (*arc_flags & ARC_PREFETCH &&
3153 refcount_count(&hdr->b_refcnt) == 0) {
3154 hdr->b_flags |= ARC_PREFETCH;
3156 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3157 arc_access(hdr, hash_lock);
3158 if (*arc_flags & ARC_L2CACHE)
3159 hdr->b_flags |= ARC_L2CACHE;
3160 if (*arc_flags & ARC_L2COMPRESS)
3161 hdr->b_flags |= ARC_L2COMPRESS;
3162 mutex_exit(hash_lock);
3163 ARCSTAT_BUMP(arcstat_hits);
3164 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3165 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3166 data, metadata, hits);
3169 done(NULL, buf, private);
3171 uint64_t size = BP_GET_LSIZE(bp);
3172 arc_callback_t *acb;
3175 boolean_t devw = B_FALSE;
3178 /* this block is not in the cache */
3179 arc_buf_hdr_t *exists;
3180 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3181 buf = arc_buf_alloc(spa, size, private, type);
3183 hdr->b_dva = *BP_IDENTITY(bp);
3184 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3185 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3186 exists = buf_hash_insert(hdr, &hash_lock);
3188 /* somebody beat us to the hash insert */
3189 mutex_exit(hash_lock);
3190 buf_discard_identity(hdr);
3191 (void) arc_buf_remove_ref(buf, private);
3192 goto top; /* restart the IO request */
3194 /* if this is a prefetch, we don't have a reference */
3195 if (*arc_flags & ARC_PREFETCH) {
3196 (void) remove_reference(hdr, hash_lock,
3198 hdr->b_flags |= ARC_PREFETCH;
3200 if (*arc_flags & ARC_L2CACHE)
3201 hdr->b_flags |= ARC_L2CACHE;
3202 if (*arc_flags & ARC_L2COMPRESS)
3203 hdr->b_flags |= ARC_L2COMPRESS;
3204 if (BP_GET_LEVEL(bp) > 0)
3205 hdr->b_flags |= ARC_INDIRECT;
3207 /* this block is in the ghost cache */
3208 ASSERT(GHOST_STATE(hdr->b_state));
3209 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3210 ASSERT0(refcount_count(&hdr->b_refcnt));
3211 ASSERT(hdr->b_buf == NULL);
3213 /* if this is a prefetch, we don't have a reference */
3214 if (*arc_flags & ARC_PREFETCH)
3215 hdr->b_flags |= ARC_PREFETCH;
3217 add_reference(hdr, hash_lock, private);
3218 if (*arc_flags & ARC_L2CACHE)
3219 hdr->b_flags |= ARC_L2CACHE;
3220 if (*arc_flags & ARC_L2COMPRESS)
3221 hdr->b_flags |= ARC_L2COMPRESS;
3222 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3225 buf->b_efunc = NULL;
3226 buf->b_private = NULL;
3229 ASSERT(hdr->b_datacnt == 0);
3231 arc_get_data_buf(buf);
3232 arc_access(hdr, hash_lock);
3235 ASSERT(!GHOST_STATE(hdr->b_state));
3237 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3238 acb->acb_done = done;
3239 acb->acb_private = private;
3241 ASSERT(hdr->b_acb == NULL);
3243 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3245 if (HDR_L2CACHE(hdr) && hdr->b_l2hdr != NULL &&
3246 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3247 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3248 addr = hdr->b_l2hdr->b_daddr;
3250 * Lock out device removal.
3252 if (vdev_is_dead(vd) ||
3253 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3257 mutex_exit(hash_lock);
3260 * At this point, we have a level 1 cache miss. Try again in
3261 * L2ARC if possible.
3263 ASSERT3U(hdr->b_size, ==, size);
3264 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3265 uint64_t, size, zbookmark_t *, zb);
3266 ARCSTAT_BUMP(arcstat_misses);
3267 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3268 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3269 data, metadata, misses);
3271 curthread->td_ru.ru_inblock++;
3274 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3276 * Read from the L2ARC if the following are true:
3277 * 1. The L2ARC vdev was previously cached.
3278 * 2. This buffer still has L2ARC metadata.
3279 * 3. This buffer isn't currently writing to the L2ARC.
3280 * 4. The L2ARC entry wasn't evicted, which may
3281 * also have invalidated the vdev.
3282 * 5. This isn't prefetch and l2arc_noprefetch is set.
3284 if (hdr->b_l2hdr != NULL &&
3285 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3286 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3287 l2arc_read_callback_t *cb;
3289 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3290 ARCSTAT_BUMP(arcstat_l2_hits);
3292 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3294 cb->l2rcb_buf = buf;
3295 cb->l2rcb_spa = spa;
3298 cb->l2rcb_flags = zio_flags;
3299 cb->l2rcb_compress = hdr->b_l2hdr->b_compress;
3301 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3302 addr + size < vd->vdev_psize -
3303 VDEV_LABEL_END_SIZE);
3306 * l2arc read. The SCL_L2ARC lock will be
3307 * released by l2arc_read_done().
3308 * Issue a null zio if the underlying buffer
3309 * was squashed to zero size by compression.
3311 if (hdr->b_l2hdr->b_compress ==
3312 ZIO_COMPRESS_EMPTY) {
3313 rzio = zio_null(pio, spa, vd,
3314 l2arc_read_done, cb,
3315 zio_flags | ZIO_FLAG_DONT_CACHE |
3317 ZIO_FLAG_DONT_PROPAGATE |
3318 ZIO_FLAG_DONT_RETRY);
3320 rzio = zio_read_phys(pio, vd, addr,
3321 hdr->b_l2hdr->b_asize,
3322 buf->b_data, ZIO_CHECKSUM_OFF,
3323 l2arc_read_done, cb, priority,
3324 zio_flags | ZIO_FLAG_DONT_CACHE |
3326 ZIO_FLAG_DONT_PROPAGATE |
3327 ZIO_FLAG_DONT_RETRY, B_FALSE);
3329 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3331 ARCSTAT_INCR(arcstat_l2_read_bytes,
3332 hdr->b_l2hdr->b_asize);
3334 if (*arc_flags & ARC_NOWAIT) {
3339 ASSERT(*arc_flags & ARC_WAIT);
3340 if (zio_wait(rzio) == 0)
3343 /* l2arc read error; goto zio_read() */
3345 DTRACE_PROBE1(l2arc__miss,
3346 arc_buf_hdr_t *, hdr);
3347 ARCSTAT_BUMP(arcstat_l2_misses);
3348 if (HDR_L2_WRITING(hdr))
3349 ARCSTAT_BUMP(arcstat_l2_rw_clash);
3350 spa_config_exit(spa, SCL_L2ARC, vd);
3354 spa_config_exit(spa, SCL_L2ARC, vd);
3355 if (l2arc_ndev != 0) {
3356 DTRACE_PROBE1(l2arc__miss,
3357 arc_buf_hdr_t *, hdr);
3358 ARCSTAT_BUMP(arcstat_l2_misses);
3362 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3363 arc_read_done, buf, priority, zio_flags, zb);
3365 if (*arc_flags & ARC_WAIT)
3366 return (zio_wait(rzio));
3368 ASSERT(*arc_flags & ARC_NOWAIT);
3375 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3377 ASSERT(buf->b_hdr != NULL);
3378 ASSERT(buf->b_hdr->b_state != arc_anon);
3379 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3380 ASSERT(buf->b_efunc == NULL);
3381 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3383 buf->b_efunc = func;
3384 buf->b_private = private;
3388 * This is used by the DMU to let the ARC know that a buffer is
3389 * being evicted, so the ARC should clean up. If this arc buf
3390 * is not yet in the evicted state, it will be put there.
3393 arc_buf_evict(arc_buf_t *buf)
3396 kmutex_t *hash_lock;
3398 list_t *list, *evicted_list;
3399 kmutex_t *lock, *evicted_lock;
3401 mutex_enter(&buf->b_evict_lock);
3405 * We are in arc_do_user_evicts().
3407 ASSERT(buf->b_data == NULL);
3408 mutex_exit(&buf->b_evict_lock);
3410 } else if (buf->b_data == NULL) {
3411 arc_buf_t copy = *buf; /* structure assignment */
3413 * We are on the eviction list; process this buffer now
3414 * but let arc_do_user_evicts() do the reaping.
3416 buf->b_efunc = NULL;
3417 mutex_exit(&buf->b_evict_lock);
3418 VERIFY(copy.b_efunc(©) == 0);
3421 hash_lock = HDR_LOCK(hdr);
3422 mutex_enter(hash_lock);
3424 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3426 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3427 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3430 * Pull this buffer off of the hdr
3433 while (*bufp != buf)
3434 bufp = &(*bufp)->b_next;
3435 *bufp = buf->b_next;
3437 ASSERT(buf->b_data != NULL);
3438 arc_buf_destroy(buf, FALSE, FALSE);
3440 if (hdr->b_datacnt == 0) {
3441 arc_state_t *old_state = hdr->b_state;
3442 arc_state_t *evicted_state;
3444 ASSERT(hdr->b_buf == NULL);
3445 ASSERT(refcount_is_zero(&hdr->b_refcnt));
3448 (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3450 get_buf_info(hdr, old_state, &list, &lock);
3451 get_buf_info(hdr, evicted_state, &evicted_list, &evicted_lock);
3453 mutex_enter(evicted_lock);
3455 arc_change_state(evicted_state, hdr, hash_lock);
3456 ASSERT(HDR_IN_HASH_TABLE(hdr));
3457 hdr->b_flags |= ARC_IN_HASH_TABLE;
3458 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3460 mutex_exit(evicted_lock);
3463 mutex_exit(hash_lock);
3464 mutex_exit(&buf->b_evict_lock);
3466 VERIFY(buf->b_efunc(buf) == 0);
3467 buf->b_efunc = NULL;
3468 buf->b_private = NULL;
3471 kmem_cache_free(buf_cache, buf);
3476 * Release this buffer from the cache, making it an anonymous buffer. This
3477 * must be done after a read and prior to modifying the buffer contents.
3478 * If the buffer has more than one reference, we must make
3479 * a new hdr for the buffer.
3482 arc_release(arc_buf_t *buf, void *tag)
3485 kmutex_t *hash_lock = NULL;
3486 l2arc_buf_hdr_t *l2hdr;
3490 * It would be nice to assert that if it's DMU metadata (level >
3491 * 0 || it's the dnode file), then it must be syncing context.
3492 * But we don't know that information at this level.
3495 mutex_enter(&buf->b_evict_lock);
3498 /* this buffer is not on any list */
3499 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3501 if (hdr->b_state == arc_anon) {
3502 /* this buffer is already released */
3503 ASSERT(buf->b_efunc == NULL);
3505 hash_lock = HDR_LOCK(hdr);
3506 mutex_enter(hash_lock);
3508 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3511 l2hdr = hdr->b_l2hdr;
3513 mutex_enter(&l2arc_buflist_mtx);
3514 hdr->b_l2hdr = NULL;
3515 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3517 buf_size = hdr->b_size;
3520 * Do we have more than one buf?
3522 if (hdr->b_datacnt > 1) {
3523 arc_buf_hdr_t *nhdr;
3525 uint64_t blksz = hdr->b_size;
3526 uint64_t spa = hdr->b_spa;
3527 arc_buf_contents_t type = hdr->b_type;
3528 uint32_t flags = hdr->b_flags;
3530 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3532 * Pull the data off of this hdr and attach it to
3533 * a new anonymous hdr.
3535 (void) remove_reference(hdr, hash_lock, tag);
3537 while (*bufp != buf)
3538 bufp = &(*bufp)->b_next;
3539 *bufp = buf->b_next;
3542 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3543 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3544 if (refcount_is_zero(&hdr->b_refcnt)) {
3545 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3546 ASSERT3U(*size, >=, hdr->b_size);
3547 atomic_add_64(size, -hdr->b_size);
3551 * We're releasing a duplicate user data buffer, update
3552 * our statistics accordingly.
3554 if (hdr->b_type == ARC_BUFC_DATA) {
3555 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3556 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3559 hdr->b_datacnt -= 1;
3560 arc_cksum_verify(buf);
3562 arc_buf_unwatch(buf);
3563 #endif /* illumos */
3565 mutex_exit(hash_lock);
3567 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3568 nhdr->b_size = blksz;
3570 nhdr->b_type = type;
3572 nhdr->b_state = arc_anon;
3573 nhdr->b_arc_access = 0;
3574 nhdr->b_flags = flags & ARC_L2_WRITING;
3575 nhdr->b_l2hdr = NULL;
3576 nhdr->b_datacnt = 1;
3577 nhdr->b_freeze_cksum = NULL;
3578 (void) refcount_add(&nhdr->b_refcnt, tag);
3580 mutex_exit(&buf->b_evict_lock);
3581 atomic_add_64(&arc_anon->arcs_size, blksz);
3583 mutex_exit(&buf->b_evict_lock);
3584 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3585 ASSERT(!list_link_active(&hdr->b_arc_node));
3586 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3587 if (hdr->b_state != arc_anon)
3588 arc_change_state(arc_anon, hdr, hash_lock);
3589 hdr->b_arc_access = 0;
3591 mutex_exit(hash_lock);
3593 buf_discard_identity(hdr);
3596 buf->b_efunc = NULL;
3597 buf->b_private = NULL;
3600 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3601 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3603 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3604 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3605 mutex_exit(&l2arc_buflist_mtx);
3610 arc_released(arc_buf_t *buf)
3614 mutex_enter(&buf->b_evict_lock);
3615 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3616 mutex_exit(&buf->b_evict_lock);
3621 arc_has_callback(arc_buf_t *buf)
3625 mutex_enter(&buf->b_evict_lock);
3626 callback = (buf->b_efunc != NULL);
3627 mutex_exit(&buf->b_evict_lock);
3633 arc_referenced(arc_buf_t *buf)
3637 mutex_enter(&buf->b_evict_lock);
3638 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3639 mutex_exit(&buf->b_evict_lock);
3640 return (referenced);
3645 arc_write_ready(zio_t *zio)
3647 arc_write_callback_t *callback = zio->io_private;
3648 arc_buf_t *buf = callback->awcb_buf;
3649 arc_buf_hdr_t *hdr = buf->b_hdr;
3651 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3652 callback->awcb_ready(zio, buf, callback->awcb_private);
3655 * If the IO is already in progress, then this is a re-write
3656 * attempt, so we need to thaw and re-compute the cksum.
3657 * It is the responsibility of the callback to handle the
3658 * accounting for any re-write attempt.
3660 if (HDR_IO_IN_PROGRESS(hdr)) {
3661 mutex_enter(&hdr->b_freeze_lock);
3662 if (hdr->b_freeze_cksum != NULL) {
3663 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3664 hdr->b_freeze_cksum = NULL;
3666 mutex_exit(&hdr->b_freeze_lock);
3668 arc_cksum_compute(buf, B_FALSE);
3669 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3673 arc_write_done(zio_t *zio)
3675 arc_write_callback_t *callback = zio->io_private;
3676 arc_buf_t *buf = callback->awcb_buf;
3677 arc_buf_hdr_t *hdr = buf->b_hdr;
3679 ASSERT(hdr->b_acb == NULL);
3681 if (zio->io_error == 0) {
3682 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3683 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3684 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3686 ASSERT(BUF_EMPTY(hdr));
3690 * If the block to be written was all-zero, we may have
3691 * compressed it away. In this case no write was performed
3692 * so there will be no dva/birth/checksum. The buffer must
3693 * therefore remain anonymous (and uncached).
3695 if (!BUF_EMPTY(hdr)) {
3696 arc_buf_hdr_t *exists;
3697 kmutex_t *hash_lock;
3699 ASSERT(zio->io_error == 0);
3701 arc_cksum_verify(buf);
3703 exists = buf_hash_insert(hdr, &hash_lock);
3706 * This can only happen if we overwrite for
3707 * sync-to-convergence, because we remove
3708 * buffers from the hash table when we arc_free().
3710 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3711 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3712 panic("bad overwrite, hdr=%p exists=%p",
3713 (void *)hdr, (void *)exists);
3714 ASSERT(refcount_is_zero(&exists->b_refcnt));
3715 arc_change_state(arc_anon, exists, hash_lock);
3716 mutex_exit(hash_lock);
3717 arc_hdr_destroy(exists);
3718 exists = buf_hash_insert(hdr, &hash_lock);
3719 ASSERT3P(exists, ==, NULL);
3720 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3722 ASSERT(zio->io_prop.zp_nopwrite);
3723 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3724 panic("bad nopwrite, hdr=%p exists=%p",
3725 (void *)hdr, (void *)exists);
3728 ASSERT(hdr->b_datacnt == 1);
3729 ASSERT(hdr->b_state == arc_anon);
3730 ASSERT(BP_GET_DEDUP(zio->io_bp));
3731 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3734 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3735 /* if it's not anon, we are doing a scrub */
3736 if (!exists && hdr->b_state == arc_anon)
3737 arc_access(hdr, hash_lock);
3738 mutex_exit(hash_lock);
3740 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3743 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3744 callback->awcb_done(zio, buf, callback->awcb_private);
3746 kmem_free(callback, sizeof (arc_write_callback_t));
3750 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3751 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3752 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *done,
3753 void *private, int priority, int zio_flags, const zbookmark_t *zb)
3755 arc_buf_hdr_t *hdr = buf->b_hdr;
3756 arc_write_callback_t *callback;
3759 ASSERT(ready != NULL);
3760 ASSERT(done != NULL);
3761 ASSERT(!HDR_IO_ERROR(hdr));
3762 ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3763 ASSERT(hdr->b_acb == NULL);
3765 hdr->b_flags |= ARC_L2CACHE;
3767 hdr->b_flags |= ARC_L2COMPRESS;
3768 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3769 callback->awcb_ready = ready;
3770 callback->awcb_done = done;
3771 callback->awcb_private = private;
3772 callback->awcb_buf = buf;
3774 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3775 arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3781 arc_memory_throttle(uint64_t reserve, uint64_t inflight_data, uint64_t txg)
3784 uint64_t available_memory =
3785 ptoa((uintmax_t)cnt.v_free_count + cnt.v_cache_count);
3786 static uint64_t page_load = 0;
3787 static uint64_t last_txg = 0;
3792 MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3795 if (available_memory >= zfs_write_limit_max)
3798 if (txg > last_txg) {
3803 * If we are in pageout, we know that memory is already tight,
3804 * the arc is already going to be evicting, so we just want to
3805 * continue to let page writes occur as quickly as possible.
3807 if (curproc == pageproc) {
3808 if (page_load > available_memory / 4)
3809 return (SET_ERROR(ERESTART));
3810 /* Note: reserve is inflated, so we deflate */
3811 page_load += reserve / 8;
3813 } else if (page_load > 0 && arc_reclaim_needed()) {
3814 /* memory is low, delay before restarting */
3815 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3816 return (SET_ERROR(EAGAIN));
3820 if (arc_size > arc_c_min) {
3821 uint64_t evictable_memory =
3822 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
3823 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
3824 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
3825 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
3826 available_memory += MIN(evictable_memory, arc_size - arc_c_min);
3829 if (inflight_data > available_memory / 4) {
3830 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3831 return (SET_ERROR(ERESTART));
3838 arc_tempreserve_clear(uint64_t reserve)
3840 atomic_add_64(&arc_tempreserve, -reserve);
3841 ASSERT((int64_t)arc_tempreserve >= 0);
3845 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3852 * Once in a while, fail for no reason. Everything should cope.
3854 if (spa_get_random(10000) == 0) {
3855 dprintf("forcing random failure\n");
3856 return (SET_ERROR(ERESTART));
3859 if (reserve > arc_c/4 && !arc_no_grow)
3860 arc_c = MIN(arc_c_max, reserve * 4);
3861 if (reserve > arc_c)
3862 return (SET_ERROR(ENOMEM));
3865 * Don't count loaned bufs as in flight dirty data to prevent long
3866 * network delays from blocking transactions that are ready to be
3867 * assigned to a txg.
3869 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3872 * Writes will, almost always, require additional memory allocations
3873 * in order to compress/encrypt/etc the data. We therefore need to
3874 * make sure that there is sufficient available memory for this.
3876 if (error = arc_memory_throttle(reserve, anon_size, txg))
3880 * Throttle writes when the amount of dirty data in the cache
3881 * gets too large. We try to keep the cache less than half full
3882 * of dirty blocks so that our sync times don't grow too large.
3883 * Note: if two requests come in concurrently, we might let them
3884 * both succeed, when one of them should fail. Not a huge deal.
3887 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3888 anon_size > arc_c / 4) {
3889 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3890 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3891 arc_tempreserve>>10,
3892 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3893 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3894 reserve>>10, arc_c>>10);
3895 return (SET_ERROR(ERESTART));
3897 atomic_add_64(&arc_tempreserve, reserve);
3901 static kmutex_t arc_lowmem_lock;
3903 static eventhandler_tag arc_event_lowmem = NULL;
3906 arc_lowmem(void *arg __unused, int howto __unused)
3909 /* Serialize access via arc_lowmem_lock. */
3910 mutex_enter(&arc_lowmem_lock);
3911 mutex_enter(&arc_reclaim_thr_lock);
3913 cv_signal(&arc_reclaim_thr_cv);
3916 * It is unsafe to block here in arbitrary threads, because we can come
3917 * here from ARC itself and may hold ARC locks and thus risk a deadlock
3918 * with ARC reclaim thread.
3920 if (curproc == pageproc) {
3922 msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
3924 mutex_exit(&arc_reclaim_thr_lock);
3925 mutex_exit(&arc_lowmem_lock);
3932 int i, prefetch_tunable_set = 0;
3934 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3935 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3936 mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
3938 /* Convert seconds to clock ticks */
3939 arc_min_prefetch_lifespan = 1 * hz;
3941 /* Start out with 1/8 of all memory */
3942 arc_c = kmem_size() / 8;
3947 * On architectures where the physical memory can be larger
3948 * than the addressable space (intel in 32-bit mode), we may
3949 * need to limit the cache to 1/8 of VM size.
3951 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3954 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
3955 arc_c_min = MAX(arc_c / 4, 64<<18);
3956 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
3957 if (arc_c * 8 >= 1<<30)
3958 arc_c_max = (arc_c * 8) - (1<<30);
3960 arc_c_max = arc_c_min;
3961 arc_c_max = MAX(arc_c * 5, arc_c_max);
3965 * Allow the tunables to override our calculations if they are
3966 * reasonable (ie. over 16MB)
3968 if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
3969 arc_c_max = zfs_arc_max;
3970 if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
3971 arc_c_min = zfs_arc_min;
3975 arc_p = (arc_c >> 1);
3977 /* limit meta-data to 1/4 of the arc capacity */
3978 arc_meta_limit = arc_c_max / 4;
3980 /* Allow the tunable to override if it is reasonable */
3981 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
3982 arc_meta_limit = zfs_arc_meta_limit;
3984 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
3985 arc_c_min = arc_meta_limit / 2;
3987 if (zfs_arc_grow_retry > 0)
3988 arc_grow_retry = zfs_arc_grow_retry;
3990 if (zfs_arc_shrink_shift > 0)
3991 arc_shrink_shift = zfs_arc_shrink_shift;
3993 if (zfs_arc_p_min_shift > 0)
3994 arc_p_min_shift = zfs_arc_p_min_shift;
3996 /* if kmem_flags are set, lets try to use less memory */
3997 if (kmem_debugging())
3999 if (arc_c < arc_c_min)
4002 zfs_arc_min = arc_c_min;
4003 zfs_arc_max = arc_c_max;
4005 arc_anon = &ARC_anon;
4007 arc_mru_ghost = &ARC_mru_ghost;
4009 arc_mfu_ghost = &ARC_mfu_ghost;
4010 arc_l2c_only = &ARC_l2c_only;
4013 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4014 mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4015 NULL, MUTEX_DEFAULT, NULL);
4016 mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4017 NULL, MUTEX_DEFAULT, NULL);
4018 mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4019 NULL, MUTEX_DEFAULT, NULL);
4020 mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4021 NULL, MUTEX_DEFAULT, NULL);
4022 mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4023 NULL, MUTEX_DEFAULT, NULL);
4024 mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4025 NULL, MUTEX_DEFAULT, NULL);
4027 list_create(&arc_mru->arcs_lists[i],
4028 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4029 list_create(&arc_mru_ghost->arcs_lists[i],
4030 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4031 list_create(&arc_mfu->arcs_lists[i],
4032 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4033 list_create(&arc_mfu_ghost->arcs_lists[i],
4034 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4035 list_create(&arc_mfu_ghost->arcs_lists[i],
4036 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4037 list_create(&arc_l2c_only->arcs_lists[i],
4038 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4043 arc_thread_exit = 0;
4044 arc_eviction_list = NULL;
4045 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4046 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4048 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4049 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4051 if (arc_ksp != NULL) {
4052 arc_ksp->ks_data = &arc_stats;
4053 kstat_install(arc_ksp);
4056 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4057 TS_RUN, minclsyspri);
4060 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4061 EVENTHANDLER_PRI_FIRST);
4067 if (zfs_write_limit_max == 0)
4068 zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
4070 zfs_write_limit_shift = 0;
4071 mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
4074 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4075 prefetch_tunable_set = 1;
4078 if (prefetch_tunable_set == 0) {
4079 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4081 printf(" add \"vfs.zfs.prefetch_disable=0\" "
4082 "to /boot/loader.conf.\n");
4083 zfs_prefetch_disable = 1;
4086 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4087 prefetch_tunable_set == 0) {
4088 printf("ZFS NOTICE: Prefetch is disabled by default if less "
4089 "than 4GB of RAM is present;\n"
4090 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
4091 "to /boot/loader.conf.\n");
4092 zfs_prefetch_disable = 1;
4095 /* Warn about ZFS memory and address space requirements. */
4096 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4097 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4098 "expect unstable behavior.\n");
4100 if (kmem_size() < 512 * (1 << 20)) {
4101 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4102 "expect unstable behavior.\n");
4103 printf(" Consider tuning vm.kmem_size and "
4104 "vm.kmem_size_max\n");
4105 printf(" in /boot/loader.conf.\n");
4115 mutex_enter(&arc_reclaim_thr_lock);
4116 arc_thread_exit = 1;
4117 cv_signal(&arc_reclaim_thr_cv);
4118 while (arc_thread_exit != 0)
4119 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4120 mutex_exit(&arc_reclaim_thr_lock);
4126 if (arc_ksp != NULL) {
4127 kstat_delete(arc_ksp);
4131 mutex_destroy(&arc_eviction_mtx);
4132 mutex_destroy(&arc_reclaim_thr_lock);
4133 cv_destroy(&arc_reclaim_thr_cv);
4135 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4136 list_destroy(&arc_mru->arcs_lists[i]);
4137 list_destroy(&arc_mru_ghost->arcs_lists[i]);
4138 list_destroy(&arc_mfu->arcs_lists[i]);
4139 list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4140 list_destroy(&arc_l2c_only->arcs_lists[i]);
4142 mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4143 mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4144 mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4145 mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4146 mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4147 mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4150 mutex_destroy(&zfs_write_limit_lock);
4154 ASSERT(arc_loaned_bytes == 0);
4156 mutex_destroy(&arc_lowmem_lock);
4158 if (arc_event_lowmem != NULL)
4159 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4166 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4167 * It uses dedicated storage devices to hold cached data, which are populated
4168 * using large infrequent writes. The main role of this cache is to boost
4169 * the performance of random read workloads. The intended L2ARC devices
4170 * include short-stroked disks, solid state disks, and other media with
4171 * substantially faster read latency than disk.
4173 * +-----------------------+
4175 * +-----------------------+
4178 * l2arc_feed_thread() arc_read()
4182 * +---------------+ |
4184 * +---------------+ |
4189 * +-------+ +-------+
4191 * | cache | | cache |
4192 * +-------+ +-------+
4193 * +=========+ .-----.
4194 * : L2ARC : |-_____-|
4195 * : devices : | Disks |
4196 * +=========+ `-_____-'
4198 * Read requests are satisfied from the following sources, in order:
4201 * 2) vdev cache of L2ARC devices
4203 * 4) vdev cache of disks
4206 * Some L2ARC device types exhibit extremely slow write performance.
4207 * To accommodate for this there are some significant differences between
4208 * the L2ARC and traditional cache design:
4210 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4211 * the ARC behave as usual, freeing buffers and placing headers on ghost
4212 * lists. The ARC does not send buffers to the L2ARC during eviction as
4213 * this would add inflated write latencies for all ARC memory pressure.
4215 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4216 * It does this by periodically scanning buffers from the eviction-end of
4217 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4218 * not already there. It scans until a headroom of buffers is satisfied,
4219 * which itself is a buffer for ARC eviction. If a compressible buffer is
4220 * found during scanning and selected for writing to an L2ARC device, we
4221 * temporarily boost scanning headroom during the next scan cycle to make
4222 * sure we adapt to compression effects (which might significantly reduce
4223 * the data volume we write to L2ARC). The thread that does this is
4224 * l2arc_feed_thread(), illustrated below; example sizes are included to
4225 * provide a better sense of ratio than this diagram:
4228 * +---------------------+----------+
4229 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4230 * +---------------------+----------+ | o L2ARC eligible
4231 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4232 * +---------------------+----------+ |
4233 * 15.9 Gbytes ^ 32 Mbytes |
4235 * l2arc_feed_thread()
4237 * l2arc write hand <--[oooo]--'
4241 * +==============================+
4242 * L2ARC dev |####|#|###|###| |####| ... |
4243 * +==============================+
4246 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4247 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4248 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4249 * safe to say that this is an uncommon case, since buffers at the end of
4250 * the ARC lists have moved there due to inactivity.
4252 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4253 * then the L2ARC simply misses copying some buffers. This serves as a
4254 * pressure valve to prevent heavy read workloads from both stalling the ARC
4255 * with waits and clogging the L2ARC with writes. This also helps prevent
4256 * the potential for the L2ARC to churn if it attempts to cache content too
4257 * quickly, such as during backups of the entire pool.
4259 * 5. After system boot and before the ARC has filled main memory, there are
4260 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4261 * lists can remain mostly static. Instead of searching from tail of these
4262 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4263 * for eligible buffers, greatly increasing its chance of finding them.
4265 * The L2ARC device write speed is also boosted during this time so that
4266 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4267 * there are no L2ARC reads, and no fear of degrading read performance
4268 * through increased writes.
4270 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4271 * the vdev queue can aggregate them into larger and fewer writes. Each
4272 * device is written to in a rotor fashion, sweeping writes through
4273 * available space then repeating.
4275 * 7. The L2ARC does not store dirty content. It never needs to flush
4276 * write buffers back to disk based storage.
4278 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4279 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4281 * The performance of the L2ARC can be tweaked by a number of tunables, which
4282 * may be necessary for different workloads:
4284 * l2arc_write_max max write bytes per interval
4285 * l2arc_write_boost extra write bytes during device warmup
4286 * l2arc_noprefetch skip caching prefetched buffers
4287 * l2arc_headroom number of max device writes to precache
4288 * l2arc_headroom_boost when we find compressed buffers during ARC
4289 * scanning, we multiply headroom by this
4290 * percentage factor for the next scan cycle,
4291 * since more compressed buffers are likely to
4293 * l2arc_feed_secs seconds between L2ARC writing
4295 * Tunables may be removed or added as future performance improvements are
4296 * integrated, and also may become zpool properties.
4298 * There are three key functions that control how the L2ARC warms up:
4300 * l2arc_write_eligible() check if a buffer is eligible to cache
4301 * l2arc_write_size() calculate how much to write
4302 * l2arc_write_interval() calculate sleep delay between writes
4304 * These three functions determine what to write, how much, and how quickly
4309 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4312 * A buffer is *not* eligible for the L2ARC if it:
4313 * 1. belongs to a different spa.
4314 * 2. is already cached on the L2ARC.
4315 * 3. has an I/O in progress (it may be an incomplete read).
4316 * 4. is flagged not eligible (zfs property).
4318 if (ab->b_spa != spa_guid) {
4319 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4322 if (ab->b_l2hdr != NULL) {
4323 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4326 if (HDR_IO_IN_PROGRESS(ab)) {
4327 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4330 if (!HDR_L2CACHE(ab)) {
4331 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4339 l2arc_write_size(void)
4344 * Make sure our globals have meaningful values in case the user
4347 size = l2arc_write_max;
4349 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4350 "be greater than zero, resetting it to the default (%d)",
4352 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4355 if (arc_warm == B_FALSE)
4356 size += l2arc_write_boost;
4363 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4365 clock_t interval, next, now;
4368 * If the ARC lists are busy, increase our write rate; if the
4369 * lists are stale, idle back. This is achieved by checking
4370 * how much we previously wrote - if it was more than half of
4371 * what we wanted, schedule the next write much sooner.
4373 if (l2arc_feed_again && wrote > (wanted / 2))
4374 interval = (hz * l2arc_feed_min_ms) / 1000;
4376 interval = hz * l2arc_feed_secs;
4378 now = ddi_get_lbolt();
4379 next = MAX(now, MIN(now + interval, began + interval));
4385 l2arc_hdr_stat_add(void)
4387 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4388 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4392 l2arc_hdr_stat_remove(void)
4394 ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4395 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4399 * Cycle through L2ARC devices. This is how L2ARC load balances.
4400 * If a device is returned, this also returns holding the spa config lock.
4402 static l2arc_dev_t *
4403 l2arc_dev_get_next(void)
4405 l2arc_dev_t *first, *next = NULL;
4408 * Lock out the removal of spas (spa_namespace_lock), then removal
4409 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4410 * both locks will be dropped and a spa config lock held instead.
4412 mutex_enter(&spa_namespace_lock);
4413 mutex_enter(&l2arc_dev_mtx);
4415 /* if there are no vdevs, there is nothing to do */
4416 if (l2arc_ndev == 0)
4420 next = l2arc_dev_last;
4422 /* loop around the list looking for a non-faulted vdev */
4424 next = list_head(l2arc_dev_list);
4426 next = list_next(l2arc_dev_list, next);
4428 next = list_head(l2arc_dev_list);
4431 /* if we have come back to the start, bail out */
4434 else if (next == first)
4437 } while (vdev_is_dead(next->l2ad_vdev));
4439 /* if we were unable to find any usable vdevs, return NULL */
4440 if (vdev_is_dead(next->l2ad_vdev))
4443 l2arc_dev_last = next;
4446 mutex_exit(&l2arc_dev_mtx);
4449 * Grab the config lock to prevent the 'next' device from being
4450 * removed while we are writing to it.
4453 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4454 mutex_exit(&spa_namespace_lock);
4460 * Free buffers that were tagged for destruction.
4463 l2arc_do_free_on_write()
4466 l2arc_data_free_t *df, *df_prev;
4468 mutex_enter(&l2arc_free_on_write_mtx);
4469 buflist = l2arc_free_on_write;
4471 for (df = list_tail(buflist); df; df = df_prev) {
4472 df_prev = list_prev(buflist, df);
4473 ASSERT(df->l2df_data != NULL);
4474 ASSERT(df->l2df_func != NULL);
4475 df->l2df_func(df->l2df_data, df->l2df_size);
4476 list_remove(buflist, df);
4477 kmem_free(df, sizeof (l2arc_data_free_t));
4480 mutex_exit(&l2arc_free_on_write_mtx);
4484 * A write to a cache device has completed. Update all headers to allow
4485 * reads from these buffers to begin.
4488 l2arc_write_done(zio_t *zio)
4490 l2arc_write_callback_t *cb;
4493 arc_buf_hdr_t *head, *ab, *ab_prev;
4494 l2arc_buf_hdr_t *abl2;
4495 kmutex_t *hash_lock;
4497 cb = zio->io_private;
4499 dev = cb->l2wcb_dev;
4500 ASSERT(dev != NULL);
4501 head = cb->l2wcb_head;
4502 ASSERT(head != NULL);
4503 buflist = dev->l2ad_buflist;
4504 ASSERT(buflist != NULL);
4505 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4506 l2arc_write_callback_t *, cb);
4508 if (zio->io_error != 0)
4509 ARCSTAT_BUMP(arcstat_l2_writes_error);
4511 mutex_enter(&l2arc_buflist_mtx);
4514 * All writes completed, or an error was hit.
4516 for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4517 ab_prev = list_prev(buflist, ab);
4519 hash_lock = HDR_LOCK(ab);
4520 if (!mutex_tryenter(hash_lock)) {
4522 * This buffer misses out. It may be in a stage
4523 * of eviction. Its ARC_L2_WRITING flag will be
4524 * left set, denying reads to this buffer.
4526 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4533 * Release the temporary compressed buffer as soon as possible.
4535 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4536 l2arc_release_cdata_buf(ab);
4538 if (zio->io_error != 0) {
4540 * Error - drop L2ARC entry.
4542 list_remove(buflist, ab);
4543 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4545 trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4547 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4548 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4552 * Allow ARC to begin reads to this L2ARC entry.
4554 ab->b_flags &= ~ARC_L2_WRITING;
4556 mutex_exit(hash_lock);
4559 atomic_inc_64(&l2arc_writes_done);
4560 list_remove(buflist, head);
4561 kmem_cache_free(hdr_cache, head);
4562 mutex_exit(&l2arc_buflist_mtx);
4564 l2arc_do_free_on_write();
4566 kmem_free(cb, sizeof (l2arc_write_callback_t));
4570 * A read to a cache device completed. Validate buffer contents before
4571 * handing over to the regular ARC routines.
4574 l2arc_read_done(zio_t *zio)
4576 l2arc_read_callback_t *cb;
4579 kmutex_t *hash_lock;
4582 ASSERT(zio->io_vd != NULL);
4583 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4585 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4587 cb = zio->io_private;
4589 buf = cb->l2rcb_buf;
4590 ASSERT(buf != NULL);
4592 hash_lock = HDR_LOCK(buf->b_hdr);
4593 mutex_enter(hash_lock);
4595 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4598 * If the buffer was compressed, decompress it first.
4600 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4601 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4602 ASSERT(zio->io_data != NULL);
4605 * Check this survived the L2ARC journey.
4607 equal = arc_cksum_equal(buf);
4608 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4609 mutex_exit(hash_lock);
4610 zio->io_private = buf;
4611 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4612 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
4615 mutex_exit(hash_lock);
4617 * Buffer didn't survive caching. Increment stats and
4618 * reissue to the original storage device.
4620 if (zio->io_error != 0) {
4621 ARCSTAT_BUMP(arcstat_l2_io_error);
4623 zio->io_error = SET_ERROR(EIO);
4626 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4629 * If there's no waiter, issue an async i/o to the primary
4630 * storage now. If there *is* a waiter, the caller must
4631 * issue the i/o in a context where it's OK to block.
4633 if (zio->io_waiter == NULL) {
4634 zio_t *pio = zio_unique_parent(zio);
4636 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4638 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4639 buf->b_data, zio->io_size, arc_read_done, buf,
4640 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4644 kmem_free(cb, sizeof (l2arc_read_callback_t));
4648 * This is the list priority from which the L2ARC will search for pages to
4649 * cache. This is used within loops (0..3) to cycle through lists in the
4650 * desired order. This order can have a significant effect on cache
4653 * Currently the metadata lists are hit first, MFU then MRU, followed by
4654 * the data lists. This function returns a locked list, and also returns
4658 l2arc_list_locked(int list_num, kmutex_t **lock)
4660 list_t *list = NULL;
4663 ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4665 if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4667 list = &arc_mfu->arcs_lists[idx];
4668 *lock = ARCS_LOCK(arc_mfu, idx);
4669 } else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4670 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4671 list = &arc_mru->arcs_lists[idx];
4672 *lock = ARCS_LOCK(arc_mru, idx);
4673 } else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4674 ARC_BUFC_NUMDATALISTS)) {
4675 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4676 list = &arc_mfu->arcs_lists[idx];
4677 *lock = ARCS_LOCK(arc_mfu, idx);
4679 idx = list_num - ARC_BUFC_NUMLISTS;
4680 list = &arc_mru->arcs_lists[idx];
4681 *lock = ARCS_LOCK(arc_mru, idx);
4684 ASSERT(!(MUTEX_HELD(*lock)));
4690 * Evict buffers from the device write hand to the distance specified in
4691 * bytes. This distance may span populated buffers, it may span nothing.
4692 * This is clearing a region on the L2ARC device ready for writing.
4693 * If the 'all' boolean is set, every buffer is evicted.
4696 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4699 l2arc_buf_hdr_t *abl2;
4700 arc_buf_hdr_t *ab, *ab_prev;
4701 kmutex_t *hash_lock;
4704 buflist = dev->l2ad_buflist;
4706 if (buflist == NULL)
4709 if (!all && dev->l2ad_first) {
4711 * This is the first sweep through the device. There is
4717 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4719 * When nearing the end of the device, evict to the end
4720 * before the device write hand jumps to the start.
4722 taddr = dev->l2ad_end;
4724 taddr = dev->l2ad_hand + distance;
4726 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4727 uint64_t, taddr, boolean_t, all);
4730 mutex_enter(&l2arc_buflist_mtx);
4731 for (ab = list_tail(buflist); ab; ab = ab_prev) {
4732 ab_prev = list_prev(buflist, ab);
4734 hash_lock = HDR_LOCK(ab);
4735 if (!mutex_tryenter(hash_lock)) {
4737 * Missed the hash lock. Retry.
4739 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4740 mutex_exit(&l2arc_buflist_mtx);
4741 mutex_enter(hash_lock);
4742 mutex_exit(hash_lock);
4746 if (HDR_L2_WRITE_HEAD(ab)) {
4748 * We hit a write head node. Leave it for
4749 * l2arc_write_done().
4751 list_remove(buflist, ab);
4752 mutex_exit(hash_lock);
4756 if (!all && ab->b_l2hdr != NULL &&
4757 (ab->b_l2hdr->b_daddr > taddr ||
4758 ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4760 * We've evicted to the target address,
4761 * or the end of the device.
4763 mutex_exit(hash_lock);
4767 if (HDR_FREE_IN_PROGRESS(ab)) {
4769 * Already on the path to destruction.
4771 mutex_exit(hash_lock);
4775 if (ab->b_state == arc_l2c_only) {
4776 ASSERT(!HDR_L2_READING(ab));
4778 * This doesn't exist in the ARC. Destroy.
4779 * arc_hdr_destroy() will call list_remove()
4780 * and decrement arcstat_l2_size.
4782 arc_change_state(arc_anon, ab, hash_lock);
4783 arc_hdr_destroy(ab);
4786 * Invalidate issued or about to be issued
4787 * reads, since we may be about to write
4788 * over this location.
4790 if (HDR_L2_READING(ab)) {
4791 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4792 ab->b_flags |= ARC_L2_EVICTED;
4796 * Tell ARC this no longer exists in L2ARC.
4798 if (ab->b_l2hdr != NULL) {
4800 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4802 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4803 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4805 list_remove(buflist, ab);
4808 * This may have been leftover after a
4811 ab->b_flags &= ~ARC_L2_WRITING;
4813 mutex_exit(hash_lock);
4815 mutex_exit(&l2arc_buflist_mtx);
4817 vdev_space_update(dev->l2ad_vdev, -(taddr - dev->l2ad_evict), 0, 0);
4818 dev->l2ad_evict = taddr;
4822 * Find and write ARC buffers to the L2ARC device.
4824 * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4825 * for reading until they have completed writing.
4826 * The headroom_boost is an in-out parameter used to maintain headroom boost
4827 * state between calls to this function.
4829 * Returns the number of bytes actually written (which may be smaller than
4830 * the delta by which the device hand has changed due to alignment).
4833 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4834 boolean_t *headroom_boost)
4836 arc_buf_hdr_t *ab, *ab_prev, *head;
4838 uint64_t write_asize, write_psize, write_sz, headroom,
4841 kmutex_t *list_lock;
4843 l2arc_write_callback_t *cb;
4845 uint64_t guid = spa_load_guid(spa);
4846 const boolean_t do_headroom_boost = *headroom_boost;
4849 ASSERT(dev->l2ad_vdev != NULL);
4851 /* Lower the flag now, we might want to raise it again later. */
4852 *headroom_boost = B_FALSE;
4855 write_sz = write_asize = write_psize = 0;
4857 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4858 head->b_flags |= ARC_L2_WRITE_HEAD;
4860 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
4862 * We will want to try to compress buffers that are at least 2x the
4863 * device sector size.
4865 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4868 * Copy buffers for L2ARC writing.
4870 mutex_enter(&l2arc_buflist_mtx);
4871 for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
4872 uint64_t passed_sz = 0;
4874 list = l2arc_list_locked(try, &list_lock);
4875 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
4878 * L2ARC fast warmup.
4880 * Until the ARC is warm and starts to evict, read from the
4881 * head of the ARC lists rather than the tail.
4883 if (arc_warm == B_FALSE)
4884 ab = list_head(list);
4886 ab = list_tail(list);
4888 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
4890 headroom = target_sz * l2arc_headroom;
4891 if (do_headroom_boost)
4892 headroom = (headroom * l2arc_headroom_boost) / 100;
4894 for (; ab; ab = ab_prev) {
4895 l2arc_buf_hdr_t *l2hdr;
4896 kmutex_t *hash_lock;
4899 if (arc_warm == B_FALSE)
4900 ab_prev = list_next(list, ab);
4902 ab_prev = list_prev(list, ab);
4903 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, ab->b_size);
4905 hash_lock = HDR_LOCK(ab);
4906 if (!mutex_tryenter(hash_lock)) {
4907 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
4909 * Skip this buffer rather than waiting.
4914 passed_sz += ab->b_size;
4915 if (passed_sz > headroom) {
4919 mutex_exit(hash_lock);
4920 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
4924 if (!l2arc_write_eligible(guid, ab)) {
4925 mutex_exit(hash_lock);
4929 if ((write_sz + ab->b_size) > target_sz) {
4931 mutex_exit(hash_lock);
4932 ARCSTAT_BUMP(arcstat_l2_write_full);
4938 * Insert a dummy header on the buflist so
4939 * l2arc_write_done() can find where the
4940 * write buffers begin without searching.
4942 list_insert_head(dev->l2ad_buflist, head);
4945 sizeof (l2arc_write_callback_t), KM_SLEEP);
4946 cb->l2wcb_dev = dev;
4947 cb->l2wcb_head = head;
4948 pio = zio_root(spa, l2arc_write_done, cb,
4950 ARCSTAT_BUMP(arcstat_l2_write_pios);
4954 * Create and add a new L2ARC header.
4956 l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
4958 ab->b_flags |= ARC_L2_WRITING;
4961 * Temporarily stash the data buffer in b_tmp_cdata.
4962 * The subsequent write step will pick it up from
4963 * there. This is because can't access ab->b_buf
4964 * without holding the hash_lock, which we in turn
4965 * can't access without holding the ARC list locks
4966 * (which we want to avoid during compression/writing).
4968 l2hdr->b_compress = ZIO_COMPRESS_OFF;
4969 l2hdr->b_asize = ab->b_size;
4970 l2hdr->b_tmp_cdata = ab->b_buf->b_data;
4972 buf_sz = ab->b_size;
4973 ab->b_l2hdr = l2hdr;
4975 list_insert_head(dev->l2ad_buflist, ab);
4978 * Compute and store the buffer cksum before
4979 * writing. On debug the cksum is verified first.
4981 arc_cksum_verify(ab->b_buf);
4982 arc_cksum_compute(ab->b_buf, B_TRUE);
4984 mutex_exit(hash_lock);
4989 mutex_exit(list_lock);
4995 /* No buffers selected for writing? */
4998 mutex_exit(&l2arc_buflist_mtx);
4999 kmem_cache_free(hdr_cache, head);
5004 * Now start writing the buffers. We're starting at the write head
5005 * and work backwards, retracing the course of the buffer selector
5008 for (ab = list_prev(dev->l2ad_buflist, head); ab;
5009 ab = list_prev(dev->l2ad_buflist, ab)) {
5010 l2arc_buf_hdr_t *l2hdr;
5014 * We shouldn't need to lock the buffer here, since we flagged
5015 * it as ARC_L2_WRITING in the previous step, but we must take
5016 * care to only access its L2 cache parameters. In particular,
5017 * ab->b_buf may be invalid by now due to ARC eviction.
5019 l2hdr = ab->b_l2hdr;
5020 l2hdr->b_daddr = dev->l2ad_hand;
5022 if ((ab->b_flags & ARC_L2COMPRESS) &&
5023 l2hdr->b_asize >= buf_compress_minsz) {
5024 if (l2arc_compress_buf(l2hdr)) {
5026 * If compression succeeded, enable headroom
5027 * boost on the next scan cycle.
5029 *headroom_boost = B_TRUE;
5034 * Pick up the buffer data we had previously stashed away
5035 * (and now potentially also compressed).
5037 buf_data = l2hdr->b_tmp_cdata;
5038 buf_sz = l2hdr->b_asize;
5040 /* Compression may have squashed the buffer to zero length. */
5044 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5045 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5046 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5047 ZIO_FLAG_CANFAIL, B_FALSE);
5049 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5051 (void) zio_nowait(wzio);
5053 write_asize += buf_sz;
5055 * Keep the clock hand suitably device-aligned.
5057 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5058 write_psize += buf_p_sz;
5059 dev->l2ad_hand += buf_p_sz;
5063 mutex_exit(&l2arc_buflist_mtx);
5065 ASSERT3U(write_asize, <=, target_sz);
5066 ARCSTAT_BUMP(arcstat_l2_writes_sent);
5067 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5068 ARCSTAT_INCR(arcstat_l2_size, write_sz);
5069 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5070 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
5073 * Bump device hand to the device start if it is approaching the end.
5074 * l2arc_evict() will already have evicted ahead for this case.
5076 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5077 vdev_space_update(dev->l2ad_vdev,
5078 dev->l2ad_end - dev->l2ad_hand, 0, 0);
5079 dev->l2ad_hand = dev->l2ad_start;
5080 dev->l2ad_evict = dev->l2ad_start;
5081 dev->l2ad_first = B_FALSE;
5084 dev->l2ad_writing = B_TRUE;
5085 (void) zio_wait(pio);
5086 dev->l2ad_writing = B_FALSE;
5088 return (write_asize);
5092 * Compresses an L2ARC buffer.
5093 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5094 * size in l2hdr->b_asize. This routine tries to compress the data and
5095 * depending on the compression result there are three possible outcomes:
5096 * *) The buffer was incompressible. The original l2hdr contents were left
5097 * untouched and are ready for writing to an L2 device.
5098 * *) The buffer was all-zeros, so there is no need to write it to an L2
5099 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5100 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5101 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5102 * data buffer which holds the compressed data to be written, and b_asize
5103 * tells us how much data there is. b_compress is set to the appropriate
5104 * compression algorithm. Once writing is done, invoke
5105 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5107 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5108 * buffer was incompressible).
5111 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5116 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5117 ASSERT(l2hdr->b_tmp_cdata != NULL);
5119 len = l2hdr->b_asize;
5120 cdata = zio_data_buf_alloc(len);
5121 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5122 cdata, l2hdr->b_asize);
5125 /* zero block, indicate that there's nothing to write */
5126 zio_data_buf_free(cdata, len);
5127 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5129 l2hdr->b_tmp_cdata = NULL;
5130 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5132 } else if (csize > 0 && csize < len) {
5134 * Compression succeeded, we'll keep the cdata around for
5135 * writing and release it afterwards.
5137 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5138 l2hdr->b_asize = csize;
5139 l2hdr->b_tmp_cdata = cdata;
5140 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5144 * Compression failed, release the compressed buffer.
5145 * l2hdr will be left unmodified.
5147 zio_data_buf_free(cdata, len);
5148 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5154 * Decompresses a zio read back from an l2arc device. On success, the
5155 * underlying zio's io_data buffer is overwritten by the uncompressed
5156 * version. On decompression error (corrupt compressed stream), the
5157 * zio->io_error value is set to signal an I/O error.
5159 * Please note that the compressed data stream is not checksummed, so
5160 * if the underlying device is experiencing data corruption, we may feed
5161 * corrupt data to the decompressor, so the decompressor needs to be
5162 * able to handle this situation (LZ4 does).
5165 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5167 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5169 if (zio->io_error != 0) {
5171 * An io error has occured, just restore the original io
5172 * size in preparation for a main pool read.
5174 zio->io_orig_size = zio->io_size = hdr->b_size;
5178 if (c == ZIO_COMPRESS_EMPTY) {
5180 * An empty buffer results in a null zio, which means we
5181 * need to fill its io_data after we're done restoring the
5182 * buffer's contents.
5184 ASSERT(hdr->b_buf != NULL);
5185 bzero(hdr->b_buf->b_data, hdr->b_size);
5186 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5188 ASSERT(zio->io_data != NULL);
5190 * We copy the compressed data from the start of the arc buffer
5191 * (the zio_read will have pulled in only what we need, the
5192 * rest is garbage which we will overwrite at decompression)
5193 * and then decompress back to the ARC data buffer. This way we
5194 * can minimize copying by simply decompressing back over the
5195 * original compressed data (rather than decompressing to an
5196 * aux buffer and then copying back the uncompressed buffer,
5197 * which is likely to be much larger).
5202 csize = zio->io_size;
5203 cdata = zio_data_buf_alloc(csize);
5204 bcopy(zio->io_data, cdata, csize);
5205 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5207 zio->io_error = EIO;
5208 zio_data_buf_free(cdata, csize);
5211 /* Restore the expected uncompressed IO size. */
5212 zio->io_orig_size = zio->io_size = hdr->b_size;
5216 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5217 * This buffer serves as a temporary holder of compressed data while
5218 * the buffer entry is being written to an l2arc device. Once that is
5219 * done, we can dispose of it.
5222 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5224 l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5226 if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5228 * If the data was compressed, then we've allocated a
5229 * temporary buffer for it, so now we need to release it.
5231 ASSERT(l2hdr->b_tmp_cdata != NULL);
5232 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5234 l2hdr->b_tmp_cdata = NULL;
5238 * This thread feeds the L2ARC at regular intervals. This is the beating
5239 * heart of the L2ARC.
5242 l2arc_feed_thread(void *dummy __unused)
5247 uint64_t size, wrote;
5248 clock_t begin, next = ddi_get_lbolt();
5249 boolean_t headroom_boost = B_FALSE;
5251 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5253 mutex_enter(&l2arc_feed_thr_lock);
5255 while (l2arc_thread_exit == 0) {
5256 CALLB_CPR_SAFE_BEGIN(&cpr);
5257 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5258 next - ddi_get_lbolt());
5259 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5260 next = ddi_get_lbolt() + hz;
5263 * Quick check for L2ARC devices.
5265 mutex_enter(&l2arc_dev_mtx);
5266 if (l2arc_ndev == 0) {
5267 mutex_exit(&l2arc_dev_mtx);
5270 mutex_exit(&l2arc_dev_mtx);
5271 begin = ddi_get_lbolt();
5274 * This selects the next l2arc device to write to, and in
5275 * doing so the next spa to feed from: dev->l2ad_spa. This
5276 * will return NULL if there are now no l2arc devices or if
5277 * they are all faulted.
5279 * If a device is returned, its spa's config lock is also
5280 * held to prevent device removal. l2arc_dev_get_next()
5281 * will grab and release l2arc_dev_mtx.
5283 if ((dev = l2arc_dev_get_next()) == NULL)
5286 spa = dev->l2ad_spa;
5287 ASSERT(spa != NULL);
5290 * If the pool is read-only then force the feed thread to
5291 * sleep a little longer.
5293 if (!spa_writeable(spa)) {
5294 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5295 spa_config_exit(spa, SCL_L2ARC, dev);
5300 * Avoid contributing to memory pressure.
5302 if (arc_reclaim_needed()) {
5303 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5304 spa_config_exit(spa, SCL_L2ARC, dev);
5308 ARCSTAT_BUMP(arcstat_l2_feeds);
5310 size = l2arc_write_size();
5313 * Evict L2ARC buffers that will be overwritten.
5315 l2arc_evict(dev, size, B_FALSE);
5318 * Write ARC buffers.
5320 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5323 * Calculate interval between writes.
5325 next = l2arc_write_interval(begin, size, wrote);
5326 spa_config_exit(spa, SCL_L2ARC, dev);
5329 l2arc_thread_exit = 0;
5330 cv_broadcast(&l2arc_feed_thr_cv);
5331 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5336 l2arc_vdev_present(vdev_t *vd)
5340 mutex_enter(&l2arc_dev_mtx);
5341 for (dev = list_head(l2arc_dev_list); dev != NULL;
5342 dev = list_next(l2arc_dev_list, dev)) {
5343 if (dev->l2ad_vdev == vd)
5346 mutex_exit(&l2arc_dev_mtx);
5348 return (dev != NULL);
5352 * Add a vdev for use by the L2ARC. By this point the spa has already
5353 * validated the vdev and opened it.
5356 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5358 l2arc_dev_t *adddev;
5360 ASSERT(!l2arc_vdev_present(vd));
5363 * Create a new l2arc device entry.
5365 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5366 adddev->l2ad_spa = spa;
5367 adddev->l2ad_vdev = vd;
5368 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5369 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5370 adddev->l2ad_hand = adddev->l2ad_start;
5371 adddev->l2ad_evict = adddev->l2ad_start;
5372 adddev->l2ad_first = B_TRUE;
5373 adddev->l2ad_writing = B_FALSE;
5376 * This is a list of all ARC buffers that are still valid on the
5379 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5380 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5381 offsetof(arc_buf_hdr_t, b_l2node));
5383 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5386 * Add device to global list
5388 mutex_enter(&l2arc_dev_mtx);
5389 list_insert_head(l2arc_dev_list, adddev);
5390 atomic_inc_64(&l2arc_ndev);
5391 mutex_exit(&l2arc_dev_mtx);
5395 * Remove a vdev from the L2ARC.
5398 l2arc_remove_vdev(vdev_t *vd)
5400 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5403 * Find the device by vdev
5405 mutex_enter(&l2arc_dev_mtx);
5406 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5407 nextdev = list_next(l2arc_dev_list, dev);
5408 if (vd == dev->l2ad_vdev) {
5413 ASSERT(remdev != NULL);
5416 * Remove device from global list
5418 list_remove(l2arc_dev_list, remdev);
5419 l2arc_dev_last = NULL; /* may have been invalidated */
5420 atomic_dec_64(&l2arc_ndev);
5421 mutex_exit(&l2arc_dev_mtx);
5424 * Clear all buflists and ARC references. L2ARC device flush.
5426 l2arc_evict(remdev, 0, B_TRUE);
5427 list_destroy(remdev->l2ad_buflist);
5428 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5429 kmem_free(remdev, sizeof (l2arc_dev_t));
5435 l2arc_thread_exit = 0;
5437 l2arc_writes_sent = 0;
5438 l2arc_writes_done = 0;
5440 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5441 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5442 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5443 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5444 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5446 l2arc_dev_list = &L2ARC_dev_list;
5447 l2arc_free_on_write = &L2ARC_free_on_write;
5448 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5449 offsetof(l2arc_dev_t, l2ad_node));
5450 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5451 offsetof(l2arc_data_free_t, l2df_list_node));
5458 * This is called from dmu_fini(), which is called from spa_fini();
5459 * Because of this, we can assume that all l2arc devices have
5460 * already been removed when the pools themselves were removed.
5463 l2arc_do_free_on_write();
5465 mutex_destroy(&l2arc_feed_thr_lock);
5466 cv_destroy(&l2arc_feed_thr_cv);
5467 mutex_destroy(&l2arc_dev_mtx);
5468 mutex_destroy(&l2arc_buflist_mtx);
5469 mutex_destroy(&l2arc_free_on_write_mtx);
5471 list_destroy(l2arc_dev_list);
5472 list_destroy(l2arc_free_on_write);
5478 if (!(spa_mode_global & FWRITE))
5481 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5482 TS_RUN, minclsyspri);
5488 if (!(spa_mode_global & FWRITE))
5491 mutex_enter(&l2arc_feed_thr_lock);
5492 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5493 l2arc_thread_exit = 1;
5494 while (l2arc_thread_exit != 0)
5495 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5496 mutex_exit(&l2arc_feed_thr_lock);