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 (c) 2012, Joyent, Inc. All rights reserved.
24 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
30 * DVA-based Adjustable Replacement Cache
32 * While much of the theory of operation used here is
33 * based on the self-tuning, low overhead replacement cache
34 * presented by Megiddo and Modha at FAST 2003, there are some
35 * significant differences:
37 * 1. The Megiddo and Modha model assumes any page is evictable.
38 * Pages in its cache cannot be "locked" into memory. This makes
39 * the eviction algorithm simple: evict the last page in the list.
40 * This also make the performance characteristics easy to reason
41 * about. Our cache is not so simple. At any given moment, some
42 * subset of the blocks in the cache are un-evictable because we
43 * have handed out a reference to them. Blocks are only evictable
44 * when there are no external references active. This makes
45 * eviction far more problematic: we choose to evict the evictable
46 * blocks that are the "lowest" in the list.
48 * There are times when it is not possible to evict the requested
49 * space. In these circumstances we are unable to adjust the cache
50 * size. To prevent the cache growing unbounded at these times we
51 * implement a "cache throttle" that slows the flow of new data
52 * into the cache until we can make space available.
54 * 2. The Megiddo and Modha model assumes a fixed cache size.
55 * Pages are evicted when the cache is full and there is a cache
56 * miss. Our model has a variable sized cache. It grows with
57 * high use, but also tries to react to memory pressure from the
58 * operating system: decreasing its size when system memory is
61 * 3. The Megiddo and Modha model assumes a fixed page size. All
62 * elements of the cache are therefore exactly the same size. So
63 * when adjusting the cache size following a cache miss, its simply
64 * a matter of choosing a single page to evict. In our model, we
65 * have variable sized cache blocks (rangeing from 512 bytes to
66 * 128K bytes). We therefore choose a set of blocks to evict to make
67 * space for a cache miss that approximates as closely as possible
68 * the space used by the new block.
70 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71 * by N. Megiddo & D. Modha, FAST 2003
77 * A new reference to a cache buffer can be obtained in two
78 * ways: 1) via a hash table lookup using the DVA as a key,
79 * or 2) via one of the ARC lists. The arc_read() interface
80 * uses method 1, while the internal arc algorithms for
81 * adjusting the cache use method 2. We therefore provide two
82 * types of locks: 1) the hash table lock array, and 2) the
85 * Buffers do not have their own mutexes, rather they rely on the
86 * hash table mutexes for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexes).
89 * buf_hash_find() returns the appropriate mutex (held) when it
90 * locates the requested buffer in the hash table. It returns
91 * NULL for the mutex if the buffer was not in the table.
93 * buf_hash_remove() expects the appropriate hash mutex to be
94 * already held before it is invoked.
96 * Each arc state also has a mutex which is used to protect the
97 * buffer list associated with the state. When attempting to
98 * obtain a hash table lock while holding an arc list lock you
99 * must use: mutex_tryenter() to avoid deadlock. Also note that
100 * the active state mutex must be held before the ghost state mutex.
102 * Arc buffers may have an associated eviction callback function.
103 * This function will be invoked prior to removing the buffer (e.g.
104 * in arc_do_user_evicts()). Note however that the data associated
105 * with the buffer may be evicted prior to the callback. The callback
106 * must be made with *no locks held* (to prevent deadlock). Additionally,
107 * the users of callbacks must ensure that their private data is
108 * protected from simultaneous callbacks from arc_clear_callback()
109 * and arc_do_user_evicts().
111 * Note that the majority of the performance stats are manipulated
112 * with atomic operations.
114 * The L2ARC uses the l2ad_mtx on each vdev for the following:
116 * - L2ARC buflist creation
117 * - L2ARC buflist eviction
118 * - L2ARC write completion, which walks L2ARC buflists
119 * - ARC header destruction, as it removes from L2ARC buflists
120 * - ARC header release, as it removes from L2ARC buflists
125 #include <sys/zio_compress.h>
126 #include <sys/zfs_context.h>
128 #include <sys/refcount.h>
129 #include <sys/vdev.h>
130 #include <sys/vdev_impl.h>
131 #include <sys/dsl_pool.h>
132 #include <sys/multilist.h>
134 #include <sys/dnlc.h>
135 #include <sys/racct.h>
137 #include <sys/callb.h>
138 #include <sys/kstat.h>
139 #include <sys/trim_map.h>
140 #include <zfs_fletcher.h>
143 #include <machine/vmparam.h>
147 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
148 boolean_t arc_watch = B_FALSE;
153 static kmutex_t arc_reclaim_lock;
154 static kcondvar_t arc_reclaim_thread_cv;
155 static boolean_t arc_reclaim_thread_exit;
156 static kcondvar_t arc_reclaim_waiters_cv;
158 static kmutex_t arc_user_evicts_lock;
159 static kcondvar_t arc_user_evicts_cv;
160 static boolean_t arc_user_evicts_thread_exit;
162 uint_t arc_reduce_dnlc_percent = 3;
165 * The number of headers to evict in arc_evict_state_impl() before
166 * dropping the sublist lock and evicting from another sublist. A lower
167 * value means we're more likely to evict the "correct" header (i.e. the
168 * oldest header in the arc state), but comes with higher overhead
169 * (i.e. more invocations of arc_evict_state_impl()).
171 int zfs_arc_evict_batch_limit = 10;
174 * The number of sublists used for each of the arc state lists. If this
175 * is not set to a suitable value by the user, it will be configured to
176 * the number of CPUs on the system in arc_init().
178 int zfs_arc_num_sublists_per_state = 0;
180 /* number of seconds before growing cache again */
181 static int arc_grow_retry = 60;
183 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
184 int zfs_arc_overflow_shift = 8;
186 /* shift of arc_c for calculating both min and max arc_p */
187 static int arc_p_min_shift = 4;
189 /* log2(fraction of arc to reclaim) */
190 static int arc_shrink_shift = 7;
193 * log2(fraction of ARC which must be free to allow growing).
194 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
195 * when reading a new block into the ARC, we will evict an equal-sized block
198 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
199 * we will still not allow it to grow.
201 int arc_no_grow_shift = 5;
205 * minimum lifespan of a prefetch block in clock ticks
206 * (initialized in arc_init())
208 static int arc_min_prefetch_lifespan;
211 * If this percent of memory is free, don't throttle.
213 int arc_lotsfree_percent = 10;
216 extern boolean_t zfs_prefetch_disable;
219 * The arc has filled available memory and has now warmed up.
221 static boolean_t arc_warm;
224 * These tunables are for performance analysis.
226 uint64_t zfs_arc_max;
227 uint64_t zfs_arc_min;
228 uint64_t zfs_arc_meta_limit = 0;
229 uint64_t zfs_arc_meta_min = 0;
230 int zfs_arc_grow_retry = 0;
231 int zfs_arc_shrink_shift = 0;
232 int zfs_arc_p_min_shift = 0;
233 int zfs_disable_dup_eviction = 0;
234 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
235 u_int zfs_arc_free_target = 0;
237 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
238 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
242 arc_free_target_init(void *unused __unused)
245 zfs_arc_free_target = vm_pageout_wakeup_thresh;
247 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
248 arc_free_target_init, NULL);
250 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
251 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
252 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
253 SYSCTL_DECL(_vfs_zfs);
254 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
256 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
258 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
259 &zfs_arc_average_blocksize, 0,
260 "ARC average blocksize");
261 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
262 &arc_shrink_shift, 0,
263 "log2(fraction of arc to reclaim)");
266 * We don't have a tunable for arc_free_target due to the dependency on
267 * pagedaemon initialisation.
269 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
270 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
271 sysctl_vfs_zfs_arc_free_target, "IU",
272 "Desired number of free pages below which ARC triggers reclaim");
275 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
280 val = zfs_arc_free_target;
281 err = sysctl_handle_int(oidp, &val, 0, req);
282 if (err != 0 || req->newptr == NULL)
287 if (val > vm_cnt.v_page_count)
290 zfs_arc_free_target = val;
296 * Must be declared here, before the definition of corresponding kstat
297 * macro which uses the same names will confuse the compiler.
299 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
300 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
301 sysctl_vfs_zfs_arc_meta_limit, "QU",
302 "ARC metadata limit");
306 * Note that buffers can be in one of 6 states:
307 * ARC_anon - anonymous (discussed below)
308 * ARC_mru - recently used, currently cached
309 * ARC_mru_ghost - recentely used, no longer in cache
310 * ARC_mfu - frequently used, currently cached
311 * ARC_mfu_ghost - frequently used, no longer in cache
312 * ARC_l2c_only - exists in L2ARC but not other states
313 * When there are no active references to the buffer, they are
314 * are linked onto a list in one of these arc states. These are
315 * the only buffers that can be evicted or deleted. Within each
316 * state there are multiple lists, one for meta-data and one for
317 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
318 * etc.) is tracked separately so that it can be managed more
319 * explicitly: favored over data, limited explicitly.
321 * Anonymous buffers are buffers that are not associated with
322 * a DVA. These are buffers that hold dirty block copies
323 * before they are written to stable storage. By definition,
324 * they are "ref'd" and are considered part of arc_mru
325 * that cannot be freed. Generally, they will aquire a DVA
326 * as they are written and migrate onto the arc_mru list.
328 * The ARC_l2c_only state is for buffers that are in the second
329 * level ARC but no longer in any of the ARC_m* lists. The second
330 * level ARC itself may also contain buffers that are in any of
331 * the ARC_m* states - meaning that a buffer can exist in two
332 * places. The reason for the ARC_l2c_only state is to keep the
333 * buffer header in the hash table, so that reads that hit the
334 * second level ARC benefit from these fast lookups.
337 typedef struct arc_state {
339 * list of evictable buffers
341 multilist_t arcs_list[ARC_BUFC_NUMTYPES];
343 * total amount of evictable data in this state
345 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];
347 * total amount of data in this state; this includes: evictable,
348 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
350 refcount_t arcs_size;
354 static arc_state_t ARC_anon;
355 static arc_state_t ARC_mru;
356 static arc_state_t ARC_mru_ghost;
357 static arc_state_t ARC_mfu;
358 static arc_state_t ARC_mfu_ghost;
359 static arc_state_t ARC_l2c_only;
361 typedef struct arc_stats {
362 kstat_named_t arcstat_hits;
363 kstat_named_t arcstat_misses;
364 kstat_named_t arcstat_demand_data_hits;
365 kstat_named_t arcstat_demand_data_misses;
366 kstat_named_t arcstat_demand_metadata_hits;
367 kstat_named_t arcstat_demand_metadata_misses;
368 kstat_named_t arcstat_prefetch_data_hits;
369 kstat_named_t arcstat_prefetch_data_misses;
370 kstat_named_t arcstat_prefetch_metadata_hits;
371 kstat_named_t arcstat_prefetch_metadata_misses;
372 kstat_named_t arcstat_mru_hits;
373 kstat_named_t arcstat_mru_ghost_hits;
374 kstat_named_t arcstat_mfu_hits;
375 kstat_named_t arcstat_mfu_ghost_hits;
376 kstat_named_t arcstat_allocated;
377 kstat_named_t arcstat_deleted;
379 * Number of buffers that could not be evicted because the hash lock
380 * was held by another thread. The lock may not necessarily be held
381 * by something using the same buffer, since hash locks are shared
382 * by multiple buffers.
384 kstat_named_t arcstat_mutex_miss;
386 * Number of buffers skipped because they have I/O in progress, are
387 * indrect prefetch buffers that have not lived long enough, or are
388 * not from the spa we're trying to evict from.
390 kstat_named_t arcstat_evict_skip;
392 * Number of times arc_evict_state() was unable to evict enough
393 * buffers to reach it's target amount.
395 kstat_named_t arcstat_evict_not_enough;
396 kstat_named_t arcstat_evict_l2_cached;
397 kstat_named_t arcstat_evict_l2_eligible;
398 kstat_named_t arcstat_evict_l2_ineligible;
399 kstat_named_t arcstat_evict_l2_skip;
400 kstat_named_t arcstat_hash_elements;
401 kstat_named_t arcstat_hash_elements_max;
402 kstat_named_t arcstat_hash_collisions;
403 kstat_named_t arcstat_hash_chains;
404 kstat_named_t arcstat_hash_chain_max;
405 kstat_named_t arcstat_p;
406 kstat_named_t arcstat_c;
407 kstat_named_t arcstat_c_min;
408 kstat_named_t arcstat_c_max;
409 kstat_named_t arcstat_size;
411 * Number of bytes consumed by internal ARC structures necessary
412 * for tracking purposes; these structures are not actually
413 * backed by ARC buffers. This includes arc_buf_hdr_t structures
414 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
415 * caches), and arc_buf_t structures (allocated via arc_buf_t
418 kstat_named_t arcstat_hdr_size;
420 * Number of bytes consumed by ARC buffers of type equal to
421 * ARC_BUFC_DATA. This is generally consumed by buffers backing
422 * on disk user data (e.g. plain file contents).
424 kstat_named_t arcstat_data_size;
426 * Number of bytes consumed by ARC buffers of type equal to
427 * ARC_BUFC_METADATA. This is generally consumed by buffers
428 * backing on disk data that is used for internal ZFS
429 * structures (e.g. ZAP, dnode, indirect blocks, etc).
431 kstat_named_t arcstat_metadata_size;
433 * Number of bytes consumed by various buffers and structures
434 * not actually backed with ARC buffers. This includes bonus
435 * buffers (allocated directly via zio_buf_* functions),
436 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
437 * cache), and dnode_t structures (allocated via dnode_t cache).
439 kstat_named_t arcstat_other_size;
441 * Total number of bytes consumed by ARC buffers residing in the
442 * arc_anon state. This includes *all* buffers in the arc_anon
443 * state; e.g. data, metadata, evictable, and unevictable buffers
444 * are all included in this value.
446 kstat_named_t arcstat_anon_size;
448 * Number of bytes consumed by ARC buffers that meet the
449 * following criteria: backing buffers of type ARC_BUFC_DATA,
450 * residing in the arc_anon state, and are eligible for eviction
451 * (e.g. have no outstanding holds on the buffer).
453 kstat_named_t arcstat_anon_evictable_data;
455 * Number of bytes consumed by ARC buffers that meet the
456 * following criteria: backing buffers of type ARC_BUFC_METADATA,
457 * residing in the arc_anon state, and are eligible for eviction
458 * (e.g. have no outstanding holds on the buffer).
460 kstat_named_t arcstat_anon_evictable_metadata;
462 * Total number of bytes consumed by ARC buffers residing in the
463 * arc_mru state. This includes *all* buffers in the arc_mru
464 * state; e.g. data, metadata, evictable, and unevictable buffers
465 * are all included in this value.
467 kstat_named_t arcstat_mru_size;
469 * Number of bytes consumed by ARC buffers that meet the
470 * following criteria: backing buffers of type ARC_BUFC_DATA,
471 * residing in the arc_mru state, and are eligible for eviction
472 * (e.g. have no outstanding holds on the buffer).
474 kstat_named_t arcstat_mru_evictable_data;
476 * Number of bytes consumed by ARC buffers that meet the
477 * following criteria: backing buffers of type ARC_BUFC_METADATA,
478 * residing in the arc_mru state, and are eligible for eviction
479 * (e.g. have no outstanding holds on the buffer).
481 kstat_named_t arcstat_mru_evictable_metadata;
483 * Total number of bytes that *would have been* consumed by ARC
484 * buffers in the arc_mru_ghost state. The key thing to note
485 * here, is the fact that this size doesn't actually indicate
486 * RAM consumption. The ghost lists only consist of headers and
487 * don't actually have ARC buffers linked off of these headers.
488 * Thus, *if* the headers had associated ARC buffers, these
489 * buffers *would have* consumed this number of bytes.
491 kstat_named_t arcstat_mru_ghost_size;
493 * Number of bytes that *would have been* consumed by ARC
494 * buffers that are eligible for eviction, of type
495 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
497 kstat_named_t arcstat_mru_ghost_evictable_data;
499 * Number of bytes that *would have been* consumed by ARC
500 * buffers that are eligible for eviction, of type
501 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
503 kstat_named_t arcstat_mru_ghost_evictable_metadata;
505 * Total number of bytes consumed by ARC buffers residing in the
506 * arc_mfu state. This includes *all* buffers in the arc_mfu
507 * state; e.g. data, metadata, evictable, and unevictable buffers
508 * are all included in this value.
510 kstat_named_t arcstat_mfu_size;
512 * Number of bytes consumed by ARC buffers that are eligible for
513 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
516 kstat_named_t arcstat_mfu_evictable_data;
518 * Number of bytes consumed by ARC buffers that are eligible for
519 * eviction, of type ARC_BUFC_METADATA, and reside in the
522 kstat_named_t arcstat_mfu_evictable_metadata;
524 * Total number of bytes that *would have been* consumed by ARC
525 * buffers in the arc_mfu_ghost state. See the comment above
526 * arcstat_mru_ghost_size for more details.
528 kstat_named_t arcstat_mfu_ghost_size;
530 * Number of bytes that *would have been* consumed by ARC
531 * buffers that are eligible for eviction, of type
532 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
534 kstat_named_t arcstat_mfu_ghost_evictable_data;
536 * Number of bytes that *would have been* consumed by ARC
537 * buffers that are eligible for eviction, of type
538 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
540 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
541 kstat_named_t arcstat_l2_hits;
542 kstat_named_t arcstat_l2_misses;
543 kstat_named_t arcstat_l2_feeds;
544 kstat_named_t arcstat_l2_rw_clash;
545 kstat_named_t arcstat_l2_read_bytes;
546 kstat_named_t arcstat_l2_write_bytes;
547 kstat_named_t arcstat_l2_writes_sent;
548 kstat_named_t arcstat_l2_writes_done;
549 kstat_named_t arcstat_l2_writes_error;
550 kstat_named_t arcstat_l2_writes_lock_retry;
551 kstat_named_t arcstat_l2_evict_lock_retry;
552 kstat_named_t arcstat_l2_evict_reading;
553 kstat_named_t arcstat_l2_evict_l1cached;
554 kstat_named_t arcstat_l2_free_on_write;
555 kstat_named_t arcstat_l2_cdata_free_on_write;
556 kstat_named_t arcstat_l2_abort_lowmem;
557 kstat_named_t arcstat_l2_cksum_bad;
558 kstat_named_t arcstat_l2_io_error;
559 kstat_named_t arcstat_l2_size;
560 kstat_named_t arcstat_l2_asize;
561 kstat_named_t arcstat_l2_hdr_size;
562 kstat_named_t arcstat_l2_compress_successes;
563 kstat_named_t arcstat_l2_compress_zeros;
564 kstat_named_t arcstat_l2_compress_failures;
565 kstat_named_t arcstat_l2_padding_needed;
566 kstat_named_t arcstat_l2_write_trylock_fail;
567 kstat_named_t arcstat_l2_write_passed_headroom;
568 kstat_named_t arcstat_l2_write_spa_mismatch;
569 kstat_named_t arcstat_l2_write_in_l2;
570 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
571 kstat_named_t arcstat_l2_write_not_cacheable;
572 kstat_named_t arcstat_l2_write_full;
573 kstat_named_t arcstat_l2_write_buffer_iter;
574 kstat_named_t arcstat_l2_write_pios;
575 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
576 kstat_named_t arcstat_l2_write_buffer_list_iter;
577 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
578 kstat_named_t arcstat_memory_throttle_count;
579 kstat_named_t arcstat_duplicate_buffers;
580 kstat_named_t arcstat_duplicate_buffers_size;
581 kstat_named_t arcstat_duplicate_reads;
582 kstat_named_t arcstat_meta_used;
583 kstat_named_t arcstat_meta_limit;
584 kstat_named_t arcstat_meta_max;
585 kstat_named_t arcstat_meta_min;
586 kstat_named_t arcstat_sync_wait_for_async;
587 kstat_named_t arcstat_demand_hit_predictive_prefetch;
590 static arc_stats_t arc_stats = {
591 { "hits", KSTAT_DATA_UINT64 },
592 { "misses", KSTAT_DATA_UINT64 },
593 { "demand_data_hits", KSTAT_DATA_UINT64 },
594 { "demand_data_misses", KSTAT_DATA_UINT64 },
595 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
596 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
597 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
598 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
599 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
600 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
601 { "mru_hits", KSTAT_DATA_UINT64 },
602 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
603 { "mfu_hits", KSTAT_DATA_UINT64 },
604 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
605 { "allocated", KSTAT_DATA_UINT64 },
606 { "deleted", KSTAT_DATA_UINT64 },
607 { "mutex_miss", KSTAT_DATA_UINT64 },
608 { "evict_skip", KSTAT_DATA_UINT64 },
609 { "evict_not_enough", KSTAT_DATA_UINT64 },
610 { "evict_l2_cached", KSTAT_DATA_UINT64 },
611 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
612 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
613 { "evict_l2_skip", KSTAT_DATA_UINT64 },
614 { "hash_elements", KSTAT_DATA_UINT64 },
615 { "hash_elements_max", KSTAT_DATA_UINT64 },
616 { "hash_collisions", KSTAT_DATA_UINT64 },
617 { "hash_chains", KSTAT_DATA_UINT64 },
618 { "hash_chain_max", KSTAT_DATA_UINT64 },
619 { "p", KSTAT_DATA_UINT64 },
620 { "c", KSTAT_DATA_UINT64 },
621 { "c_min", KSTAT_DATA_UINT64 },
622 { "c_max", KSTAT_DATA_UINT64 },
623 { "size", KSTAT_DATA_UINT64 },
624 { "hdr_size", KSTAT_DATA_UINT64 },
625 { "data_size", KSTAT_DATA_UINT64 },
626 { "metadata_size", KSTAT_DATA_UINT64 },
627 { "other_size", KSTAT_DATA_UINT64 },
628 { "anon_size", KSTAT_DATA_UINT64 },
629 { "anon_evictable_data", KSTAT_DATA_UINT64 },
630 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
631 { "mru_size", KSTAT_DATA_UINT64 },
632 { "mru_evictable_data", KSTAT_DATA_UINT64 },
633 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
634 { "mru_ghost_size", KSTAT_DATA_UINT64 },
635 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
636 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
637 { "mfu_size", KSTAT_DATA_UINT64 },
638 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
639 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
640 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
641 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
642 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
643 { "l2_hits", KSTAT_DATA_UINT64 },
644 { "l2_misses", KSTAT_DATA_UINT64 },
645 { "l2_feeds", KSTAT_DATA_UINT64 },
646 { "l2_rw_clash", KSTAT_DATA_UINT64 },
647 { "l2_read_bytes", KSTAT_DATA_UINT64 },
648 { "l2_write_bytes", KSTAT_DATA_UINT64 },
649 { "l2_writes_sent", KSTAT_DATA_UINT64 },
650 { "l2_writes_done", KSTAT_DATA_UINT64 },
651 { "l2_writes_error", KSTAT_DATA_UINT64 },
652 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
653 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
654 { "l2_evict_reading", KSTAT_DATA_UINT64 },
655 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
656 { "l2_free_on_write", KSTAT_DATA_UINT64 },
657 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
658 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
659 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
660 { "l2_io_error", KSTAT_DATA_UINT64 },
661 { "l2_size", KSTAT_DATA_UINT64 },
662 { "l2_asize", KSTAT_DATA_UINT64 },
663 { "l2_hdr_size", KSTAT_DATA_UINT64 },
664 { "l2_compress_successes", KSTAT_DATA_UINT64 },
665 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
666 { "l2_compress_failures", KSTAT_DATA_UINT64 },
667 { "l2_padding_needed", KSTAT_DATA_UINT64 },
668 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
669 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
670 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
671 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
672 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
673 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
674 { "l2_write_full", KSTAT_DATA_UINT64 },
675 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
676 { "l2_write_pios", KSTAT_DATA_UINT64 },
677 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
678 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
679 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
680 { "memory_throttle_count", KSTAT_DATA_UINT64 },
681 { "duplicate_buffers", KSTAT_DATA_UINT64 },
682 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
683 { "duplicate_reads", KSTAT_DATA_UINT64 },
684 { "arc_meta_used", KSTAT_DATA_UINT64 },
685 { "arc_meta_limit", KSTAT_DATA_UINT64 },
686 { "arc_meta_max", KSTAT_DATA_UINT64 },
687 { "arc_meta_min", KSTAT_DATA_UINT64 },
688 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
689 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
692 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
694 #define ARCSTAT_INCR(stat, val) \
695 atomic_add_64(&arc_stats.stat.value.ui64, (val))
697 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
698 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
700 #define ARCSTAT_MAX(stat, val) { \
702 while ((val) > (m = arc_stats.stat.value.ui64) && \
703 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
707 #define ARCSTAT_MAXSTAT(stat) \
708 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
711 * We define a macro to allow ARC hits/misses to be easily broken down by
712 * two separate conditions, giving a total of four different subtypes for
713 * each of hits and misses (so eight statistics total).
715 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
718 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
720 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
724 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
726 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
731 static arc_state_t *arc_anon;
732 static arc_state_t *arc_mru;
733 static arc_state_t *arc_mru_ghost;
734 static arc_state_t *arc_mfu;
735 static arc_state_t *arc_mfu_ghost;
736 static arc_state_t *arc_l2c_only;
739 * There are several ARC variables that are critical to export as kstats --
740 * but we don't want to have to grovel around in the kstat whenever we wish to
741 * manipulate them. For these variables, we therefore define them to be in
742 * terms of the statistic variable. This assures that we are not introducing
743 * the possibility of inconsistency by having shadow copies of the variables,
744 * while still allowing the code to be readable.
746 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
747 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
748 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
749 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
750 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
751 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
752 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
753 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
754 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
756 #define L2ARC_IS_VALID_COMPRESS(_c_) \
757 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
759 static int arc_no_grow; /* Don't try to grow cache size */
760 static uint64_t arc_tempreserve;
761 static uint64_t arc_loaned_bytes;
763 typedef struct arc_callback arc_callback_t;
765 struct arc_callback {
767 arc_done_func_t *acb_done;
769 zio_t *acb_zio_dummy;
770 arc_callback_t *acb_next;
773 typedef struct arc_write_callback arc_write_callback_t;
775 struct arc_write_callback {
777 arc_done_func_t *awcb_ready;
778 arc_done_func_t *awcb_physdone;
779 arc_done_func_t *awcb_done;
784 * ARC buffers are separated into multiple structs as a memory saving measure:
785 * - Common fields struct, always defined, and embedded within it:
786 * - L2-only fields, always allocated but undefined when not in L2ARC
787 * - L1-only fields, only allocated when in L1ARC
789 * Buffer in L1 Buffer only in L2
790 * +------------------------+ +------------------------+
791 * | arc_buf_hdr_t | | arc_buf_hdr_t |
795 * +------------------------+ +------------------------+
796 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
797 * | (undefined if L1-only) | | |
798 * +------------------------+ +------------------------+
799 * | l1arc_buf_hdr_t |
804 * +------------------------+
806 * Because it's possible for the L2ARC to become extremely large, we can wind
807 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
808 * is minimized by only allocating the fields necessary for an L1-cached buffer
809 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
810 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
811 * words in pointers. arc_hdr_realloc() is used to switch a header between
812 * these two allocation states.
814 typedef struct l1arc_buf_hdr {
815 kmutex_t b_freeze_lock;
818 * used for debugging wtih kmem_flags - by allocating and freeing
819 * b_thawed when the buffer is thawed, we get a record of the stack
820 * trace that thawed it.
827 /* for waiting on writes to complete */
830 /* protected by arc state mutex */
831 arc_state_t *b_state;
832 multilist_node_t b_arc_node;
834 /* updated atomically */
835 clock_t b_arc_access;
837 /* self protecting */
840 arc_callback_t *b_acb;
841 /* temporary buffer holder for in-flight compressed or padded data */
845 typedef struct l2arc_dev l2arc_dev_t;
847 typedef struct l2arc_buf_hdr {
848 /* protected by arc_buf_hdr mutex */
849 l2arc_dev_t *b_dev; /* L2ARC device */
850 uint64_t b_daddr; /* disk address, offset byte */
851 /* real alloc'd buffer size depending on b_compress applied */
855 list_node_t b_l2node;
859 /* protected by hash lock */
863 * Even though this checksum is only set/verified when a buffer is in
864 * the L1 cache, it needs to be in the set of common fields because it
865 * must be preserved from the time before a buffer is written out to
866 * L2ARC until after it is read back in.
868 zio_cksum_t *b_freeze_cksum;
870 arc_buf_hdr_t *b_hash_next;
877 /* L2ARC fields. Undefined when not in L2ARC. */
878 l2arc_buf_hdr_t b_l2hdr;
879 /* L1ARC fields. Undefined when in l2arc_only state */
880 l1arc_buf_hdr_t b_l1hdr;
885 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
890 val = arc_meta_limit;
891 err = sysctl_handle_64(oidp, &val, 0, req);
892 if (err != 0 || req->newptr == NULL)
895 if (val <= 0 || val > arc_c_max)
898 arc_meta_limit = val;
903 static arc_buf_t *arc_eviction_list;
904 static arc_buf_hdr_t arc_eviction_hdr;
906 #define GHOST_STATE(state) \
907 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
908 (state) == arc_l2c_only)
910 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
911 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
912 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
913 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
914 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
915 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
917 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
918 #define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
919 #define HDR_L2_READING(hdr) \
920 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
921 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
922 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
923 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
924 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
926 #define HDR_ISTYPE_METADATA(hdr) \
927 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
928 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
930 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
931 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
937 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
938 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
941 * Hash table routines
944 #define HT_LOCK_PAD CACHE_LINE_SIZE
949 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
953 #define BUF_LOCKS 256
954 typedef struct buf_hash_table {
956 arc_buf_hdr_t **ht_table;
957 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
960 static buf_hash_table_t buf_hash_table;
962 #define BUF_HASH_INDEX(spa, dva, birth) \
963 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
964 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
965 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
966 #define HDR_LOCK(hdr) \
967 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
969 uint64_t zfs_crc64_table[256];
975 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
976 #define L2ARC_HEADROOM 2 /* num of writes */
978 * If we discover during ARC scan any buffers to be compressed, we boost
979 * our headroom for the next scanning cycle by this percentage multiple.
981 #define L2ARC_HEADROOM_BOOST 200
982 #define L2ARC_FEED_SECS 1 /* caching interval secs */
983 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
986 * Used to distinguish headers that are being process by
987 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
988 * address. This can happen when the header is added to the l2arc's list
989 * of buffers to write in the first stage of l2arc_write_buffers(), but
990 * has not yet been written out which happens in the second stage of
991 * l2arc_write_buffers().
993 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
995 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
996 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
998 /* L2ARC Performance Tunables */
999 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1000 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1001 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1002 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1003 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1004 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1005 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1006 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1007 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1009 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1010 &l2arc_write_max, 0, "max write size");
1011 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1012 &l2arc_write_boost, 0, "extra write during warmup");
1013 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1014 &l2arc_headroom, 0, "number of dev writes");
1015 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1016 &l2arc_feed_secs, 0, "interval seconds");
1017 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1018 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1020 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1021 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1022 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1023 &l2arc_feed_again, 0, "turbo warmup");
1024 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1025 &l2arc_norw, 0, "no reads during writes");
1027 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1028 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1029 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1030 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1031 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1032 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1034 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1035 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1036 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1037 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1038 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1039 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1041 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1042 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1043 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1044 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1045 "size of metadata in mru ghost state");
1046 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1047 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1048 "size of data in mru ghost state");
1050 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1051 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1052 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1053 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1054 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1055 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1057 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1058 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1059 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1060 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1061 "size of metadata in mfu ghost state");
1062 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1063 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1064 "size of data in mfu ghost state");
1066 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1067 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1073 vdev_t *l2ad_vdev; /* vdev */
1074 spa_t *l2ad_spa; /* spa */
1075 uint64_t l2ad_hand; /* next write location */
1076 uint64_t l2ad_start; /* first addr on device */
1077 uint64_t l2ad_end; /* last addr on device */
1078 boolean_t l2ad_first; /* first sweep through */
1079 boolean_t l2ad_writing; /* currently writing */
1080 kmutex_t l2ad_mtx; /* lock for buffer list */
1081 list_t l2ad_buflist; /* buffer list */
1082 list_node_t l2ad_node; /* device list node */
1083 refcount_t l2ad_alloc; /* allocated bytes */
1086 static list_t L2ARC_dev_list; /* device list */
1087 static list_t *l2arc_dev_list; /* device list pointer */
1088 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1089 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1090 static list_t L2ARC_free_on_write; /* free after write buf list */
1091 static list_t *l2arc_free_on_write; /* free after write list ptr */
1092 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1093 static uint64_t l2arc_ndev; /* number of devices */
1095 typedef struct l2arc_read_callback {
1096 arc_buf_t *l2rcb_buf; /* read buffer */
1097 spa_t *l2rcb_spa; /* spa */
1098 blkptr_t l2rcb_bp; /* original blkptr */
1099 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1100 int l2rcb_flags; /* original flags */
1101 enum zio_compress l2rcb_compress; /* applied compress */
1102 void *l2rcb_data; /* temporary buffer */
1103 } l2arc_read_callback_t;
1105 typedef struct l2arc_write_callback {
1106 l2arc_dev_t *l2wcb_dev; /* device info */
1107 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1108 } l2arc_write_callback_t;
1110 typedef struct l2arc_data_free {
1111 /* protected by l2arc_free_on_write_mtx */
1114 void (*l2df_func)(void *, size_t);
1115 list_node_t l2df_list_node;
1116 } l2arc_data_free_t;
1118 static kmutex_t l2arc_feed_thr_lock;
1119 static kcondvar_t l2arc_feed_thr_cv;
1120 static uint8_t l2arc_thread_exit;
1122 static void arc_get_data_buf(arc_buf_t *);
1123 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1124 static boolean_t arc_is_overflowing();
1125 static void arc_buf_watch(arc_buf_t *);
1127 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1128 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1130 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1131 static void l2arc_read_done(zio_t *);
1133 static boolean_t l2arc_transform_buf(arc_buf_hdr_t *, boolean_t);
1134 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1135 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1138 l2arc_trim(const arc_buf_hdr_t *hdr)
1140 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1142 ASSERT(HDR_HAS_L2HDR(hdr));
1143 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1145 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET)
1147 if (hdr->b_l2hdr.b_asize != 0) {
1148 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1149 hdr->b_l2hdr.b_asize, 0);
1151 ASSERT3U(hdr->b_l2hdr.b_compress, ==, ZIO_COMPRESS_EMPTY);
1156 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1158 uint8_t *vdva = (uint8_t *)dva;
1159 uint64_t crc = -1ULL;
1162 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1164 for (i = 0; i < sizeof (dva_t); i++)
1165 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1167 crc ^= (spa>>8) ^ birth;
1172 #define BUF_EMPTY(buf) \
1173 ((buf)->b_dva.dva_word[0] == 0 && \
1174 (buf)->b_dva.dva_word[1] == 0)
1176 #define BUF_EQUAL(spa, dva, birth, buf) \
1177 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1178 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1179 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1182 buf_discard_identity(arc_buf_hdr_t *hdr)
1184 hdr->b_dva.dva_word[0] = 0;
1185 hdr->b_dva.dva_word[1] = 0;
1189 static arc_buf_hdr_t *
1190 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1192 const dva_t *dva = BP_IDENTITY(bp);
1193 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1194 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1195 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1198 mutex_enter(hash_lock);
1199 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1200 hdr = hdr->b_hash_next) {
1201 if (BUF_EQUAL(spa, dva, birth, hdr)) {
1206 mutex_exit(hash_lock);
1212 * Insert an entry into the hash table. If there is already an element
1213 * equal to elem in the hash table, then the already existing element
1214 * will be returned and the new element will not be inserted.
1215 * Otherwise returns NULL.
1216 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1218 static arc_buf_hdr_t *
1219 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1221 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1222 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1223 arc_buf_hdr_t *fhdr;
1226 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1227 ASSERT(hdr->b_birth != 0);
1228 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1230 if (lockp != NULL) {
1232 mutex_enter(hash_lock);
1234 ASSERT(MUTEX_HELD(hash_lock));
1237 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1238 fhdr = fhdr->b_hash_next, i++) {
1239 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1243 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1244 buf_hash_table.ht_table[idx] = hdr;
1245 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1247 /* collect some hash table performance data */
1249 ARCSTAT_BUMP(arcstat_hash_collisions);
1251 ARCSTAT_BUMP(arcstat_hash_chains);
1253 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1256 ARCSTAT_BUMP(arcstat_hash_elements);
1257 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1263 buf_hash_remove(arc_buf_hdr_t *hdr)
1265 arc_buf_hdr_t *fhdr, **hdrp;
1266 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1268 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1269 ASSERT(HDR_IN_HASH_TABLE(hdr));
1271 hdrp = &buf_hash_table.ht_table[idx];
1272 while ((fhdr = *hdrp) != hdr) {
1273 ASSERT(fhdr != NULL);
1274 hdrp = &fhdr->b_hash_next;
1276 *hdrp = hdr->b_hash_next;
1277 hdr->b_hash_next = NULL;
1278 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1280 /* collect some hash table performance data */
1281 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1283 if (buf_hash_table.ht_table[idx] &&
1284 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1285 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1289 * Global data structures and functions for the buf kmem cache.
1291 static kmem_cache_t *hdr_full_cache;
1292 static kmem_cache_t *hdr_l2only_cache;
1293 static kmem_cache_t *buf_cache;
1300 kmem_free(buf_hash_table.ht_table,
1301 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1302 for (i = 0; i < BUF_LOCKS; i++)
1303 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1304 kmem_cache_destroy(hdr_full_cache);
1305 kmem_cache_destroy(hdr_l2only_cache);
1306 kmem_cache_destroy(buf_cache);
1310 * Constructor callback - called when the cache is empty
1311 * and a new buf is requested.
1315 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1317 arc_buf_hdr_t *hdr = vbuf;
1319 bzero(hdr, HDR_FULL_SIZE);
1320 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1321 refcount_create(&hdr->b_l1hdr.b_refcnt);
1322 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1323 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1324 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1331 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1333 arc_buf_hdr_t *hdr = vbuf;
1335 bzero(hdr, HDR_L2ONLY_SIZE);
1336 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1343 buf_cons(void *vbuf, void *unused, int kmflag)
1345 arc_buf_t *buf = vbuf;
1347 bzero(buf, sizeof (arc_buf_t));
1348 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1349 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1355 * Destructor callback - called when a cached buf is
1356 * no longer required.
1360 hdr_full_dest(void *vbuf, void *unused)
1362 arc_buf_hdr_t *hdr = vbuf;
1364 ASSERT(BUF_EMPTY(hdr));
1365 cv_destroy(&hdr->b_l1hdr.b_cv);
1366 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1367 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1368 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1369 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1374 hdr_l2only_dest(void *vbuf, void *unused)
1376 arc_buf_hdr_t *hdr = vbuf;
1378 ASSERT(BUF_EMPTY(hdr));
1379 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1384 buf_dest(void *vbuf, void *unused)
1386 arc_buf_t *buf = vbuf;
1388 mutex_destroy(&buf->b_evict_lock);
1389 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1393 * Reclaim callback -- invoked when memory is low.
1397 hdr_recl(void *unused)
1399 dprintf("hdr_recl called\n");
1401 * umem calls the reclaim func when we destroy the buf cache,
1402 * which is after we do arc_fini().
1405 cv_signal(&arc_reclaim_thread_cv);
1412 uint64_t hsize = 1ULL << 12;
1416 * The hash table is big enough to fill all of physical memory
1417 * with an average block size of zfs_arc_average_blocksize (default 8K).
1418 * By default, the table will take up
1419 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1421 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1424 buf_hash_table.ht_mask = hsize - 1;
1425 buf_hash_table.ht_table =
1426 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1427 if (buf_hash_table.ht_table == NULL) {
1428 ASSERT(hsize > (1ULL << 8));
1433 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1434 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1435 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1436 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1438 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1439 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1441 for (i = 0; i < 256; i++)
1442 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1443 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1445 for (i = 0; i < BUF_LOCKS; i++) {
1446 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1447 NULL, MUTEX_DEFAULT, NULL);
1452 * Transition between the two allocation states for the arc_buf_hdr struct.
1453 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1454 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1455 * version is used when a cache buffer is only in the L2ARC in order to reduce
1458 static arc_buf_hdr_t *
1459 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1461 ASSERT(HDR_HAS_L2HDR(hdr));
1463 arc_buf_hdr_t *nhdr;
1464 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1466 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1467 (old == hdr_l2only_cache && new == hdr_full_cache));
1469 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1471 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1472 buf_hash_remove(hdr);
1474 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1476 if (new == hdr_full_cache) {
1477 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1479 * arc_access and arc_change_state need to be aware that a
1480 * header has just come out of L2ARC, so we set its state to
1481 * l2c_only even though it's about to change.
1483 nhdr->b_l1hdr.b_state = arc_l2c_only;
1485 /* Verify previous threads set to NULL before freeing */
1486 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1488 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1489 ASSERT0(hdr->b_l1hdr.b_datacnt);
1492 * If we've reached here, We must have been called from
1493 * arc_evict_hdr(), as such we should have already been
1494 * removed from any ghost list we were previously on
1495 * (which protects us from racing with arc_evict_state),
1496 * thus no locking is needed during this check.
1498 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1501 * A buffer must not be moved into the arc_l2c_only
1502 * state if it's not finished being written out to the
1503 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1504 * might try to be accessed, even though it was removed.
1506 VERIFY(!HDR_L2_WRITING(hdr));
1507 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1510 if (hdr->b_l1hdr.b_thawed != NULL) {
1511 kmem_free(hdr->b_l1hdr.b_thawed, 1);
1512 hdr->b_l1hdr.b_thawed = NULL;
1516 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1519 * The header has been reallocated so we need to re-insert it into any
1522 (void) buf_hash_insert(nhdr, NULL);
1524 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1526 mutex_enter(&dev->l2ad_mtx);
1529 * We must place the realloc'ed header back into the list at
1530 * the same spot. Otherwise, if it's placed earlier in the list,
1531 * l2arc_write_buffers() could find it during the function's
1532 * write phase, and try to write it out to the l2arc.
1534 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1535 list_remove(&dev->l2ad_buflist, hdr);
1537 mutex_exit(&dev->l2ad_mtx);
1540 * Since we're using the pointer address as the tag when
1541 * incrementing and decrementing the l2ad_alloc refcount, we
1542 * must remove the old pointer (that we're about to destroy) and
1543 * add the new pointer to the refcount. Otherwise we'd remove
1544 * the wrong pointer address when calling arc_hdr_destroy() later.
1547 (void) refcount_remove_many(&dev->l2ad_alloc,
1548 hdr->b_l2hdr.b_asize, hdr);
1550 (void) refcount_add_many(&dev->l2ad_alloc,
1551 nhdr->b_l2hdr.b_asize, nhdr);
1553 buf_discard_identity(hdr);
1554 hdr->b_freeze_cksum = NULL;
1555 kmem_cache_free(old, hdr);
1561 #define ARC_MINTIME (hz>>4) /* 62 ms */
1564 arc_cksum_verify(arc_buf_t *buf)
1568 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1571 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1572 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1573 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1576 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1577 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1578 panic("buffer modified while frozen!");
1579 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1583 arc_cksum_equal(arc_buf_t *buf)
1588 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1589 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1590 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1591 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1597 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1599 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1602 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1603 if (buf->b_hdr->b_freeze_cksum != NULL) {
1604 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1607 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1608 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1609 NULL, buf->b_hdr->b_freeze_cksum);
1610 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1618 typedef struct procctl {
1626 arc_buf_unwatch(arc_buf_t *buf)
1633 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1634 ctl.prwatch.pr_size = 0;
1635 ctl.prwatch.pr_wflags = 0;
1636 result = write(arc_procfd, &ctl, sizeof (ctl));
1637 ASSERT3U(result, ==, sizeof (ctl));
1644 arc_buf_watch(arc_buf_t *buf)
1651 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1652 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1653 ctl.prwatch.pr_wflags = WA_WRITE;
1654 result = write(arc_procfd, &ctl, sizeof (ctl));
1655 ASSERT3U(result, ==, sizeof (ctl));
1659 #endif /* illumos */
1661 static arc_buf_contents_t
1662 arc_buf_type(arc_buf_hdr_t *hdr)
1664 if (HDR_ISTYPE_METADATA(hdr)) {
1665 return (ARC_BUFC_METADATA);
1667 return (ARC_BUFC_DATA);
1672 arc_bufc_to_flags(arc_buf_contents_t type)
1676 /* metadata field is 0 if buffer contains normal data */
1678 case ARC_BUFC_METADATA:
1679 return (ARC_FLAG_BUFC_METADATA);
1683 panic("undefined ARC buffer type!");
1684 return ((uint32_t)-1);
1688 arc_buf_thaw(arc_buf_t *buf)
1690 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1691 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1692 panic("modifying non-anon buffer!");
1693 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1694 panic("modifying buffer while i/o in progress!");
1695 arc_cksum_verify(buf);
1698 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1699 if (buf->b_hdr->b_freeze_cksum != NULL) {
1700 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1701 buf->b_hdr->b_freeze_cksum = NULL;
1705 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1706 if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1707 kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1708 buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1712 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1715 arc_buf_unwatch(buf);
1720 arc_buf_freeze(arc_buf_t *buf)
1722 kmutex_t *hash_lock;
1724 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1727 hash_lock = HDR_LOCK(buf->b_hdr);
1728 mutex_enter(hash_lock);
1730 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1731 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1732 arc_cksum_compute(buf, B_FALSE);
1733 mutex_exit(hash_lock);
1738 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1740 ASSERT(HDR_HAS_L1HDR(hdr));
1741 ASSERT(MUTEX_HELD(hash_lock));
1742 arc_state_t *state = hdr->b_l1hdr.b_state;
1744 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1745 (state != arc_anon)) {
1746 /* We don't use the L2-only state list. */
1747 if (state != arc_l2c_only) {
1748 arc_buf_contents_t type = arc_buf_type(hdr);
1749 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1750 multilist_t *list = &state->arcs_list[type];
1751 uint64_t *size = &state->arcs_lsize[type];
1753 multilist_remove(list, hdr);
1755 if (GHOST_STATE(state)) {
1756 ASSERT0(hdr->b_l1hdr.b_datacnt);
1757 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1758 delta = hdr->b_size;
1761 ASSERT3U(*size, >=, delta);
1762 atomic_add_64(size, -delta);
1764 /* remove the prefetch flag if we get a reference */
1765 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1770 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1773 arc_state_t *state = hdr->b_l1hdr.b_state;
1775 ASSERT(HDR_HAS_L1HDR(hdr));
1776 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1777 ASSERT(!GHOST_STATE(state));
1780 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1781 * check to prevent usage of the arc_l2c_only list.
1783 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1784 (state != arc_anon)) {
1785 arc_buf_contents_t type = arc_buf_type(hdr);
1786 multilist_t *list = &state->arcs_list[type];
1787 uint64_t *size = &state->arcs_lsize[type];
1789 multilist_insert(list, hdr);
1791 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1792 atomic_add_64(size, hdr->b_size *
1793 hdr->b_l1hdr.b_datacnt);
1799 * Move the supplied buffer to the indicated state. The hash lock
1800 * for the buffer must be held by the caller.
1803 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1804 kmutex_t *hash_lock)
1806 arc_state_t *old_state;
1809 uint64_t from_delta, to_delta;
1810 arc_buf_contents_t buftype = arc_buf_type(hdr);
1813 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1814 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1815 * L1 hdr doesn't always exist when we change state to arc_anon before
1816 * destroying a header, in which case reallocating to add the L1 hdr is
1819 if (HDR_HAS_L1HDR(hdr)) {
1820 old_state = hdr->b_l1hdr.b_state;
1821 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1822 datacnt = hdr->b_l1hdr.b_datacnt;
1824 old_state = arc_l2c_only;
1829 ASSERT(MUTEX_HELD(hash_lock));
1830 ASSERT3P(new_state, !=, old_state);
1831 ASSERT(refcnt == 0 || datacnt > 0);
1832 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1833 ASSERT(old_state != arc_anon || datacnt <= 1);
1835 from_delta = to_delta = datacnt * hdr->b_size;
1838 * If this buffer is evictable, transfer it from the
1839 * old state list to the new state list.
1842 if (old_state != arc_anon && old_state != arc_l2c_only) {
1843 uint64_t *size = &old_state->arcs_lsize[buftype];
1845 ASSERT(HDR_HAS_L1HDR(hdr));
1846 multilist_remove(&old_state->arcs_list[buftype], hdr);
1849 * If prefetching out of the ghost cache,
1850 * we will have a non-zero datacnt.
1852 if (GHOST_STATE(old_state) && datacnt == 0) {
1853 /* ghost elements have a ghost size */
1854 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1855 from_delta = hdr->b_size;
1857 ASSERT3U(*size, >=, from_delta);
1858 atomic_add_64(size, -from_delta);
1860 if (new_state != arc_anon && new_state != arc_l2c_only) {
1861 uint64_t *size = &new_state->arcs_lsize[buftype];
1864 * An L1 header always exists here, since if we're
1865 * moving to some L1-cached state (i.e. not l2c_only or
1866 * anonymous), we realloc the header to add an L1hdr
1869 ASSERT(HDR_HAS_L1HDR(hdr));
1870 multilist_insert(&new_state->arcs_list[buftype], hdr);
1872 /* ghost elements have a ghost size */
1873 if (GHOST_STATE(new_state)) {
1875 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1876 to_delta = hdr->b_size;
1878 atomic_add_64(size, to_delta);
1882 ASSERT(!BUF_EMPTY(hdr));
1883 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1884 buf_hash_remove(hdr);
1886 /* adjust state sizes (ignore arc_l2c_only) */
1888 if (to_delta && new_state != arc_l2c_only) {
1889 ASSERT(HDR_HAS_L1HDR(hdr));
1890 if (GHOST_STATE(new_state)) {
1894 * We moving a header to a ghost state, we first
1895 * remove all arc buffers. Thus, we'll have a
1896 * datacnt of zero, and no arc buffer to use for
1897 * the reference. As a result, we use the arc
1898 * header pointer for the reference.
1900 (void) refcount_add_many(&new_state->arcs_size,
1903 ASSERT3U(datacnt, !=, 0);
1906 * Each individual buffer holds a unique reference,
1907 * thus we must remove each of these references one
1910 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1911 buf = buf->b_next) {
1912 (void) refcount_add_many(&new_state->arcs_size,
1918 if (from_delta && old_state != arc_l2c_only) {
1919 ASSERT(HDR_HAS_L1HDR(hdr));
1920 if (GHOST_STATE(old_state)) {
1922 * When moving a header off of a ghost state,
1923 * there's the possibility for datacnt to be
1924 * non-zero. This is because we first add the
1925 * arc buffer to the header prior to changing
1926 * the header's state. Since we used the header
1927 * for the reference when putting the header on
1928 * the ghost state, we must balance that and use
1929 * the header when removing off the ghost state
1930 * (even though datacnt is non zero).
1933 IMPLY(datacnt == 0, new_state == arc_anon ||
1934 new_state == arc_l2c_only);
1936 (void) refcount_remove_many(&old_state->arcs_size,
1939 ASSERT3P(datacnt, !=, 0);
1942 * Each individual buffer holds a unique reference,
1943 * thus we must remove each of these references one
1946 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1947 buf = buf->b_next) {
1948 (void) refcount_remove_many(
1949 &old_state->arcs_size, hdr->b_size, buf);
1954 if (HDR_HAS_L1HDR(hdr))
1955 hdr->b_l1hdr.b_state = new_state;
1958 * L2 headers should never be on the L2 state list since they don't
1959 * have L1 headers allocated.
1961 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1962 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1966 arc_space_consume(uint64_t space, arc_space_type_t type)
1968 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1971 case ARC_SPACE_DATA:
1972 ARCSTAT_INCR(arcstat_data_size, space);
1974 case ARC_SPACE_META:
1975 ARCSTAT_INCR(arcstat_metadata_size, space);
1977 case ARC_SPACE_OTHER:
1978 ARCSTAT_INCR(arcstat_other_size, space);
1980 case ARC_SPACE_HDRS:
1981 ARCSTAT_INCR(arcstat_hdr_size, space);
1983 case ARC_SPACE_L2HDRS:
1984 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1988 if (type != ARC_SPACE_DATA)
1989 ARCSTAT_INCR(arcstat_meta_used, space);
1991 atomic_add_64(&arc_size, space);
1995 arc_space_return(uint64_t space, arc_space_type_t type)
1997 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2000 case ARC_SPACE_DATA:
2001 ARCSTAT_INCR(arcstat_data_size, -space);
2003 case ARC_SPACE_META:
2004 ARCSTAT_INCR(arcstat_metadata_size, -space);
2006 case ARC_SPACE_OTHER:
2007 ARCSTAT_INCR(arcstat_other_size, -space);
2009 case ARC_SPACE_HDRS:
2010 ARCSTAT_INCR(arcstat_hdr_size, -space);
2012 case ARC_SPACE_L2HDRS:
2013 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2017 if (type != ARC_SPACE_DATA) {
2018 ASSERT(arc_meta_used >= space);
2019 if (arc_meta_max < arc_meta_used)
2020 arc_meta_max = arc_meta_used;
2021 ARCSTAT_INCR(arcstat_meta_used, -space);
2024 ASSERT(arc_size >= space);
2025 atomic_add_64(&arc_size, -space);
2029 arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2034 ASSERT3U(size, >, 0);
2035 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2036 ASSERT(BUF_EMPTY(hdr));
2037 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
2039 hdr->b_spa = spa_load_guid(spa);
2041 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2044 buf->b_efunc = NULL;
2045 buf->b_private = NULL;
2048 hdr->b_flags = arc_bufc_to_flags(type);
2049 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
2051 hdr->b_l1hdr.b_buf = buf;
2052 hdr->b_l1hdr.b_state = arc_anon;
2053 hdr->b_l1hdr.b_arc_access = 0;
2054 hdr->b_l1hdr.b_datacnt = 1;
2055 hdr->b_l1hdr.b_tmp_cdata = NULL;
2057 arc_get_data_buf(buf);
2058 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2059 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2064 static char *arc_onloan_tag = "onloan";
2067 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2068 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2069 * buffers must be returned to the arc before they can be used by the DMU or
2073 arc_loan_buf(spa_t *spa, int size)
2077 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2079 atomic_add_64(&arc_loaned_bytes, size);
2084 * Return a loaned arc buffer to the arc.
2087 arc_return_buf(arc_buf_t *buf, void *tag)
2089 arc_buf_hdr_t *hdr = buf->b_hdr;
2091 ASSERT(buf->b_data != NULL);
2092 ASSERT(HDR_HAS_L1HDR(hdr));
2093 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2094 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2096 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2099 /* Detach an arc_buf from a dbuf (tag) */
2101 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2103 arc_buf_hdr_t *hdr = buf->b_hdr;
2105 ASSERT(buf->b_data != NULL);
2106 ASSERT(HDR_HAS_L1HDR(hdr));
2107 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2108 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2109 buf->b_efunc = NULL;
2110 buf->b_private = NULL;
2112 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2116 arc_buf_clone(arc_buf_t *from)
2119 arc_buf_hdr_t *hdr = from->b_hdr;
2120 uint64_t size = hdr->b_size;
2122 ASSERT(HDR_HAS_L1HDR(hdr));
2123 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2125 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2128 buf->b_efunc = NULL;
2129 buf->b_private = NULL;
2130 buf->b_next = hdr->b_l1hdr.b_buf;
2131 hdr->b_l1hdr.b_buf = buf;
2132 arc_get_data_buf(buf);
2133 bcopy(from->b_data, buf->b_data, size);
2136 * This buffer already exists in the arc so create a duplicate
2137 * copy for the caller. If the buffer is associated with user data
2138 * then track the size and number of duplicates. These stats will be
2139 * updated as duplicate buffers are created and destroyed.
2141 if (HDR_ISTYPE_DATA(hdr)) {
2142 ARCSTAT_BUMP(arcstat_duplicate_buffers);
2143 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2145 hdr->b_l1hdr.b_datacnt += 1;
2150 arc_buf_add_ref(arc_buf_t *buf, void* tag)
2153 kmutex_t *hash_lock;
2156 * Check to see if this buffer is evicted. Callers
2157 * must verify b_data != NULL to know if the add_ref
2160 mutex_enter(&buf->b_evict_lock);
2161 if (buf->b_data == NULL) {
2162 mutex_exit(&buf->b_evict_lock);
2165 hash_lock = HDR_LOCK(buf->b_hdr);
2166 mutex_enter(hash_lock);
2168 ASSERT(HDR_HAS_L1HDR(hdr));
2169 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2170 mutex_exit(&buf->b_evict_lock);
2172 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2173 hdr->b_l1hdr.b_state == arc_mfu);
2175 add_reference(hdr, hash_lock, tag);
2176 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2177 arc_access(hdr, hash_lock);
2178 mutex_exit(hash_lock);
2179 ARCSTAT_BUMP(arcstat_hits);
2180 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2181 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2182 data, metadata, hits);
2186 arc_buf_free_on_write(void *data, size_t size,
2187 void (*free_func)(void *, size_t))
2189 l2arc_data_free_t *df;
2191 df = kmem_alloc(sizeof (*df), KM_SLEEP);
2192 df->l2df_data = data;
2193 df->l2df_size = size;
2194 df->l2df_func = free_func;
2195 mutex_enter(&l2arc_free_on_write_mtx);
2196 list_insert_head(l2arc_free_on_write, df);
2197 mutex_exit(&l2arc_free_on_write_mtx);
2201 * Free the arc data buffer. If it is an l2arc write in progress,
2202 * the buffer is placed on l2arc_free_on_write to be freed later.
2205 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2207 arc_buf_hdr_t *hdr = buf->b_hdr;
2209 if (HDR_L2_WRITING(hdr)) {
2210 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2211 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2213 free_func(buf->b_data, hdr->b_size);
2218 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2220 size_t align, asize, len;
2222 ASSERT(HDR_HAS_L2HDR(hdr));
2223 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2226 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2227 * that doesn't exist, the header is in the arc_l2c_only state,
2228 * and there isn't anything to free (it's already been freed).
2230 if (!HDR_HAS_L1HDR(hdr))
2234 * The header isn't being written to the l2arc device, thus it
2235 * shouldn't have a b_tmp_cdata to free.
2237 if (!HDR_L2_WRITING(hdr)) {
2238 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2243 * The bufer has been chosen for writing to L2ARC, but it's
2244 * not being written just yet. In other words,
2245 * b_tmp_cdata points to exactly the same buffer as b_data,
2246 * l2arc_transform_buf hasn't been called.
2248 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET) {
2249 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==,
2250 hdr->b_l1hdr.b_buf->b_data);
2251 ASSERT3U(hdr->b_l2hdr.b_compress, ==, ZIO_COMPRESS_OFF);
2256 * There's nothing to free since the buffer was all zero's and
2257 * compressed to a zero length buffer.
2259 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_EMPTY) {
2260 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2265 * Nothing to do if the temporary buffer was not required.
2267 if (hdr->b_l1hdr.b_tmp_cdata == NULL)
2270 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2272 align = (size_t)1 << hdr->b_l2hdr.b_dev->l2ad_vdev->vdev_ashift;
2273 asize = P2ROUNDUP(len, align);
2274 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata, asize,
2276 hdr->b_l1hdr.b_tmp_cdata = NULL;
2280 * Free up buf->b_data and if 'remove' is set, then pull the
2281 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2284 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2288 /* free up data associated with the buf */
2289 if (buf->b_data != NULL) {
2290 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2291 uint64_t size = buf->b_hdr->b_size;
2292 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2294 arc_cksum_verify(buf);
2296 arc_buf_unwatch(buf);
2299 if (type == ARC_BUFC_METADATA) {
2300 arc_buf_data_free(buf, zio_buf_free);
2301 arc_space_return(size, ARC_SPACE_META);
2303 ASSERT(type == ARC_BUFC_DATA);
2304 arc_buf_data_free(buf, zio_data_buf_free);
2305 arc_space_return(size, ARC_SPACE_DATA);
2308 /* protected by hash lock, if in the hash table */
2309 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2310 uint64_t *cnt = &state->arcs_lsize[type];
2312 ASSERT(refcount_is_zero(
2313 &buf->b_hdr->b_l1hdr.b_refcnt));
2314 ASSERT(state != arc_anon && state != arc_l2c_only);
2316 ASSERT3U(*cnt, >=, size);
2317 atomic_add_64(cnt, -size);
2320 (void) refcount_remove_many(&state->arcs_size, size, buf);
2324 * If we're destroying a duplicate buffer make sure
2325 * that the appropriate statistics are updated.
2327 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2328 HDR_ISTYPE_DATA(buf->b_hdr)) {
2329 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2330 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2332 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2333 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2336 /* only remove the buf if requested */
2340 /* remove the buf from the hdr list */
2341 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2342 bufp = &(*bufp)->b_next)
2344 *bufp = buf->b_next;
2347 ASSERT(buf->b_efunc == NULL);
2349 /* clean up the buf */
2351 kmem_cache_free(buf_cache, buf);
2355 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2357 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2358 l2arc_dev_t *dev = l2hdr->b_dev;
2360 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2361 ASSERT(HDR_HAS_L2HDR(hdr));
2363 list_remove(&dev->l2ad_buflist, hdr);
2366 * We don't want to leak the b_tmp_cdata buffer that was
2367 * allocated in l2arc_write_buffers()
2369 arc_buf_l2_cdata_free(hdr);
2372 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2373 * this header is being processed by l2arc_write_buffers() (i.e.
2374 * it's in the first stage of l2arc_write_buffers()).
2375 * Re-affirming that truth here, just to serve as a reminder. If
2376 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2377 * may not have its HDR_L2_WRITING flag set. (the write may have
2378 * completed, in which case HDR_L2_WRITING will be false and the
2379 * b_daddr field will point to the address of the buffer on disk).
2381 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2384 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2385 * l2arc_write_buffers(). Since we've just removed this header
2386 * from the l2arc buffer list, this header will never reach the
2387 * second stage of l2arc_write_buffers(), which increments the
2388 * accounting stats for this header. Thus, we must be careful
2389 * not to decrement them for this header either.
2391 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2392 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2393 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2395 vdev_space_update(dev->l2ad_vdev,
2396 -l2hdr->b_asize, 0, 0);
2398 (void) refcount_remove_many(&dev->l2ad_alloc,
2399 l2hdr->b_asize, hdr);
2402 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2406 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2408 if (HDR_HAS_L1HDR(hdr)) {
2409 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2410 hdr->b_l1hdr.b_datacnt > 0);
2411 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2412 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2414 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2415 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2417 if (HDR_HAS_L2HDR(hdr)) {
2418 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2419 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2422 mutex_enter(&dev->l2ad_mtx);
2425 * Even though we checked this conditional above, we
2426 * need to check this again now that we have the
2427 * l2ad_mtx. This is because we could be racing with
2428 * another thread calling l2arc_evict() which might have
2429 * destroyed this header's L2 portion as we were waiting
2430 * to acquire the l2ad_mtx. If that happens, we don't
2431 * want to re-destroy the header's L2 portion.
2433 if (HDR_HAS_L2HDR(hdr)) {
2435 arc_hdr_l2hdr_destroy(hdr);
2439 mutex_exit(&dev->l2ad_mtx);
2442 if (!BUF_EMPTY(hdr))
2443 buf_discard_identity(hdr);
2445 if (hdr->b_freeze_cksum != NULL) {
2446 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2447 hdr->b_freeze_cksum = NULL;
2450 if (HDR_HAS_L1HDR(hdr)) {
2451 while (hdr->b_l1hdr.b_buf) {
2452 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2454 if (buf->b_efunc != NULL) {
2455 mutex_enter(&arc_user_evicts_lock);
2456 mutex_enter(&buf->b_evict_lock);
2457 ASSERT(buf->b_hdr != NULL);
2458 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2459 hdr->b_l1hdr.b_buf = buf->b_next;
2460 buf->b_hdr = &arc_eviction_hdr;
2461 buf->b_next = arc_eviction_list;
2462 arc_eviction_list = buf;
2463 mutex_exit(&buf->b_evict_lock);
2464 cv_signal(&arc_user_evicts_cv);
2465 mutex_exit(&arc_user_evicts_lock);
2467 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2471 if (hdr->b_l1hdr.b_thawed != NULL) {
2472 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2473 hdr->b_l1hdr.b_thawed = NULL;
2478 ASSERT3P(hdr->b_hash_next, ==, NULL);
2479 if (HDR_HAS_L1HDR(hdr)) {
2480 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2481 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2482 kmem_cache_free(hdr_full_cache, hdr);
2484 kmem_cache_free(hdr_l2only_cache, hdr);
2489 arc_buf_free(arc_buf_t *buf, void *tag)
2491 arc_buf_hdr_t *hdr = buf->b_hdr;
2492 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2494 ASSERT(buf->b_efunc == NULL);
2495 ASSERT(buf->b_data != NULL);
2498 kmutex_t *hash_lock = HDR_LOCK(hdr);
2500 mutex_enter(hash_lock);
2502 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2504 (void) remove_reference(hdr, hash_lock, tag);
2505 if (hdr->b_l1hdr.b_datacnt > 1) {
2506 arc_buf_destroy(buf, TRUE);
2508 ASSERT(buf == hdr->b_l1hdr.b_buf);
2509 ASSERT(buf->b_efunc == NULL);
2510 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2512 mutex_exit(hash_lock);
2513 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2516 * We are in the middle of an async write. Don't destroy
2517 * this buffer unless the write completes before we finish
2518 * decrementing the reference count.
2520 mutex_enter(&arc_user_evicts_lock);
2521 (void) remove_reference(hdr, NULL, tag);
2522 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2523 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2524 mutex_exit(&arc_user_evicts_lock);
2526 arc_hdr_destroy(hdr);
2528 if (remove_reference(hdr, NULL, tag) > 0)
2529 arc_buf_destroy(buf, TRUE);
2531 arc_hdr_destroy(hdr);
2536 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2538 arc_buf_hdr_t *hdr = buf->b_hdr;
2539 kmutex_t *hash_lock = HDR_LOCK(hdr);
2540 boolean_t no_callback = (buf->b_efunc == NULL);
2542 if (hdr->b_l1hdr.b_state == arc_anon) {
2543 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2544 arc_buf_free(buf, tag);
2545 return (no_callback);
2548 mutex_enter(hash_lock);
2550 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2551 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2552 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2553 ASSERT(buf->b_data != NULL);
2555 (void) remove_reference(hdr, hash_lock, tag);
2556 if (hdr->b_l1hdr.b_datacnt > 1) {
2558 arc_buf_destroy(buf, TRUE);
2559 } else if (no_callback) {
2560 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2561 ASSERT(buf->b_efunc == NULL);
2562 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2564 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2565 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2566 mutex_exit(hash_lock);
2567 return (no_callback);
2571 arc_buf_size(arc_buf_t *buf)
2573 return (buf->b_hdr->b_size);
2577 * Called from the DMU to determine if the current buffer should be
2578 * evicted. In order to ensure proper locking, the eviction must be initiated
2579 * from the DMU. Return true if the buffer is associated with user data and
2580 * duplicate buffers still exist.
2583 arc_buf_eviction_needed(arc_buf_t *buf)
2586 boolean_t evict_needed = B_FALSE;
2588 if (zfs_disable_dup_eviction)
2591 mutex_enter(&buf->b_evict_lock);
2595 * We are in arc_do_user_evicts(); let that function
2596 * perform the eviction.
2598 ASSERT(buf->b_data == NULL);
2599 mutex_exit(&buf->b_evict_lock);
2601 } else if (buf->b_data == NULL) {
2603 * We have already been added to the arc eviction list;
2604 * recommend eviction.
2606 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2607 mutex_exit(&buf->b_evict_lock);
2611 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2612 evict_needed = B_TRUE;
2614 mutex_exit(&buf->b_evict_lock);
2615 return (evict_needed);
2619 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2620 * state of the header is dependent on it's state prior to entering this
2621 * function. The following transitions are possible:
2623 * - arc_mru -> arc_mru_ghost
2624 * - arc_mfu -> arc_mfu_ghost
2625 * - arc_mru_ghost -> arc_l2c_only
2626 * - arc_mru_ghost -> deleted
2627 * - arc_mfu_ghost -> arc_l2c_only
2628 * - arc_mfu_ghost -> deleted
2631 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2633 arc_state_t *evicted_state, *state;
2634 int64_t bytes_evicted = 0;
2636 ASSERT(MUTEX_HELD(hash_lock));
2637 ASSERT(HDR_HAS_L1HDR(hdr));
2639 state = hdr->b_l1hdr.b_state;
2640 if (GHOST_STATE(state)) {
2641 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2642 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2645 * l2arc_write_buffers() relies on a header's L1 portion
2646 * (i.e. it's b_tmp_cdata field) during it's write phase.
2647 * Thus, we cannot push a header onto the arc_l2c_only
2648 * state (removing it's L1 piece) until the header is
2649 * done being written to the l2arc.
2651 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2652 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2653 return (bytes_evicted);
2656 ARCSTAT_BUMP(arcstat_deleted);
2657 bytes_evicted += hdr->b_size;
2659 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2661 if (HDR_HAS_L2HDR(hdr)) {
2663 * This buffer is cached on the 2nd Level ARC;
2664 * don't destroy the header.
2666 arc_change_state(arc_l2c_only, hdr, hash_lock);
2668 * dropping from L1+L2 cached to L2-only,
2669 * realloc to remove the L1 header.
2671 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2674 arc_change_state(arc_anon, hdr, hash_lock);
2675 arc_hdr_destroy(hdr);
2677 return (bytes_evicted);
2680 ASSERT(state == arc_mru || state == arc_mfu);
2681 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2683 /* prefetch buffers have a minimum lifespan */
2684 if (HDR_IO_IN_PROGRESS(hdr) ||
2685 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2686 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2687 arc_min_prefetch_lifespan)) {
2688 ARCSTAT_BUMP(arcstat_evict_skip);
2689 return (bytes_evicted);
2692 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2693 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2694 while (hdr->b_l1hdr.b_buf) {
2695 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2696 if (!mutex_tryenter(&buf->b_evict_lock)) {
2697 ARCSTAT_BUMP(arcstat_mutex_miss);
2700 if (buf->b_data != NULL)
2701 bytes_evicted += hdr->b_size;
2702 if (buf->b_efunc != NULL) {
2703 mutex_enter(&arc_user_evicts_lock);
2704 arc_buf_destroy(buf, FALSE);
2705 hdr->b_l1hdr.b_buf = buf->b_next;
2706 buf->b_hdr = &arc_eviction_hdr;
2707 buf->b_next = arc_eviction_list;
2708 arc_eviction_list = buf;
2709 cv_signal(&arc_user_evicts_cv);
2710 mutex_exit(&arc_user_evicts_lock);
2711 mutex_exit(&buf->b_evict_lock);
2713 mutex_exit(&buf->b_evict_lock);
2714 arc_buf_destroy(buf, TRUE);
2718 if (HDR_HAS_L2HDR(hdr)) {
2719 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2721 if (l2arc_write_eligible(hdr->b_spa, hdr))
2722 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2724 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2727 if (hdr->b_l1hdr.b_datacnt == 0) {
2728 arc_change_state(evicted_state, hdr, hash_lock);
2729 ASSERT(HDR_IN_HASH_TABLE(hdr));
2730 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2731 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2732 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2735 return (bytes_evicted);
2739 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2740 uint64_t spa, int64_t bytes)
2742 multilist_sublist_t *mls;
2743 uint64_t bytes_evicted = 0;
2745 kmutex_t *hash_lock;
2746 int evict_count = 0;
2748 ASSERT3P(marker, !=, NULL);
2749 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2751 mls = multilist_sublist_lock(ml, idx);
2753 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2754 hdr = multilist_sublist_prev(mls, marker)) {
2755 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2756 (evict_count >= zfs_arc_evict_batch_limit))
2760 * To keep our iteration location, move the marker
2761 * forward. Since we're not holding hdr's hash lock, we
2762 * must be very careful and not remove 'hdr' from the
2763 * sublist. Otherwise, other consumers might mistake the
2764 * 'hdr' as not being on a sublist when they call the
2765 * multilist_link_active() function (they all rely on
2766 * the hash lock protecting concurrent insertions and
2767 * removals). multilist_sublist_move_forward() was
2768 * specifically implemented to ensure this is the case
2769 * (only 'marker' will be removed and re-inserted).
2771 multilist_sublist_move_forward(mls, marker);
2774 * The only case where the b_spa field should ever be
2775 * zero, is the marker headers inserted by
2776 * arc_evict_state(). It's possible for multiple threads
2777 * to be calling arc_evict_state() concurrently (e.g.
2778 * dsl_pool_close() and zio_inject_fault()), so we must
2779 * skip any markers we see from these other threads.
2781 if (hdr->b_spa == 0)
2784 /* we're only interested in evicting buffers of a certain spa */
2785 if (spa != 0 && hdr->b_spa != spa) {
2786 ARCSTAT_BUMP(arcstat_evict_skip);
2790 hash_lock = HDR_LOCK(hdr);
2793 * We aren't calling this function from any code path
2794 * that would already be holding a hash lock, so we're
2795 * asserting on this assumption to be defensive in case
2796 * this ever changes. Without this check, it would be
2797 * possible to incorrectly increment arcstat_mutex_miss
2798 * below (e.g. if the code changed such that we called
2799 * this function with a hash lock held).
2801 ASSERT(!MUTEX_HELD(hash_lock));
2803 if (mutex_tryenter(hash_lock)) {
2804 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2805 mutex_exit(hash_lock);
2807 bytes_evicted += evicted;
2810 * If evicted is zero, arc_evict_hdr() must have
2811 * decided to skip this header, don't increment
2812 * evict_count in this case.
2818 * If arc_size isn't overflowing, signal any
2819 * threads that might happen to be waiting.
2821 * For each header evicted, we wake up a single
2822 * thread. If we used cv_broadcast, we could
2823 * wake up "too many" threads causing arc_size
2824 * to significantly overflow arc_c; since
2825 * arc_get_data_buf() doesn't check for overflow
2826 * when it's woken up (it doesn't because it's
2827 * possible for the ARC to be overflowing while
2828 * full of un-evictable buffers, and the
2829 * function should proceed in this case).
2831 * If threads are left sleeping, due to not
2832 * using cv_broadcast, they will be woken up
2833 * just before arc_reclaim_thread() sleeps.
2835 mutex_enter(&arc_reclaim_lock);
2836 if (!arc_is_overflowing())
2837 cv_signal(&arc_reclaim_waiters_cv);
2838 mutex_exit(&arc_reclaim_lock);
2840 ARCSTAT_BUMP(arcstat_mutex_miss);
2844 multilist_sublist_unlock(mls);
2846 return (bytes_evicted);
2850 * Evict buffers from the given arc state, until we've removed the
2851 * specified number of bytes. Move the removed buffers to the
2852 * appropriate evict state.
2854 * This function makes a "best effort". It skips over any buffers
2855 * it can't get a hash_lock on, and so, may not catch all candidates.
2856 * It may also return without evicting as much space as requested.
2858 * If bytes is specified using the special value ARC_EVICT_ALL, this
2859 * will evict all available (i.e. unlocked and evictable) buffers from
2860 * the given arc state; which is used by arc_flush().
2863 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2864 arc_buf_contents_t type)
2866 uint64_t total_evicted = 0;
2867 multilist_t *ml = &state->arcs_list[type];
2869 arc_buf_hdr_t **markers;
2871 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2873 num_sublists = multilist_get_num_sublists(ml);
2876 * If we've tried to evict from each sublist, made some
2877 * progress, but still have not hit the target number of bytes
2878 * to evict, we want to keep trying. The markers allow us to
2879 * pick up where we left off for each individual sublist, rather
2880 * than starting from the tail each time.
2882 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2883 for (int i = 0; i < num_sublists; i++) {
2884 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2887 * A b_spa of 0 is used to indicate that this header is
2888 * a marker. This fact is used in arc_adjust_type() and
2889 * arc_evict_state_impl().
2891 markers[i]->b_spa = 0;
2893 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2894 multilist_sublist_insert_tail(mls, markers[i]);
2895 multilist_sublist_unlock(mls);
2899 * While we haven't hit our target number of bytes to evict, or
2900 * we're evicting all available buffers.
2902 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2904 * Start eviction using a randomly selected sublist,
2905 * this is to try and evenly balance eviction across all
2906 * sublists. Always starting at the same sublist
2907 * (e.g. index 0) would cause evictions to favor certain
2908 * sublists over others.
2910 int sublist_idx = multilist_get_random_index(ml);
2911 uint64_t scan_evicted = 0;
2913 for (int i = 0; i < num_sublists; i++) {
2914 uint64_t bytes_remaining;
2915 uint64_t bytes_evicted;
2917 if (bytes == ARC_EVICT_ALL)
2918 bytes_remaining = ARC_EVICT_ALL;
2919 else if (total_evicted < bytes)
2920 bytes_remaining = bytes - total_evicted;
2924 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2925 markers[sublist_idx], spa, bytes_remaining);
2927 scan_evicted += bytes_evicted;
2928 total_evicted += bytes_evicted;
2930 /* we've reached the end, wrap to the beginning */
2931 if (++sublist_idx >= num_sublists)
2936 * If we didn't evict anything during this scan, we have
2937 * no reason to believe we'll evict more during another
2938 * scan, so break the loop.
2940 if (scan_evicted == 0) {
2941 /* This isn't possible, let's make that obvious */
2942 ASSERT3S(bytes, !=, 0);
2945 * When bytes is ARC_EVICT_ALL, the only way to
2946 * break the loop is when scan_evicted is zero.
2947 * In that case, we actually have evicted enough,
2948 * so we don't want to increment the kstat.
2950 if (bytes != ARC_EVICT_ALL) {
2951 ASSERT3S(total_evicted, <, bytes);
2952 ARCSTAT_BUMP(arcstat_evict_not_enough);
2959 for (int i = 0; i < num_sublists; i++) {
2960 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2961 multilist_sublist_remove(mls, markers[i]);
2962 multilist_sublist_unlock(mls);
2964 kmem_cache_free(hdr_full_cache, markers[i]);
2966 kmem_free(markers, sizeof (*markers) * num_sublists);
2968 return (total_evicted);
2972 * Flush all "evictable" data of the given type from the arc state
2973 * specified. This will not evict any "active" buffers (i.e. referenced).
2975 * When 'retry' is set to FALSE, the function will make a single pass
2976 * over the state and evict any buffers that it can. Since it doesn't
2977 * continually retry the eviction, it might end up leaving some buffers
2978 * in the ARC due to lock misses.
2980 * When 'retry' is set to TRUE, the function will continually retry the
2981 * eviction until *all* evictable buffers have been removed from the
2982 * state. As a result, if concurrent insertions into the state are
2983 * allowed (e.g. if the ARC isn't shutting down), this function might
2984 * wind up in an infinite loop, continually trying to evict buffers.
2987 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2990 uint64_t evicted = 0;
2992 while (state->arcs_lsize[type] != 0) {
2993 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3003 * Evict the specified number of bytes from the state specified,
3004 * restricting eviction to the spa and type given. This function
3005 * prevents us from trying to evict more from a state's list than
3006 * is "evictable", and to skip evicting altogether when passed a
3007 * negative value for "bytes". In contrast, arc_evict_state() will
3008 * evict everything it can, when passed a negative value for "bytes".
3011 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3012 arc_buf_contents_t type)
3016 if (bytes > 0 && state->arcs_lsize[type] > 0) {
3017 delta = MIN(state->arcs_lsize[type], bytes);
3018 return (arc_evict_state(state, spa, delta, type));
3025 * Evict metadata buffers from the cache, such that arc_meta_used is
3026 * capped by the arc_meta_limit tunable.
3029 arc_adjust_meta(void)
3031 uint64_t total_evicted = 0;
3035 * If we're over the meta limit, we want to evict enough
3036 * metadata to get back under the meta limit. We don't want to
3037 * evict so much that we drop the MRU below arc_p, though. If
3038 * we're over the meta limit more than we're over arc_p, we
3039 * evict some from the MRU here, and some from the MFU below.
3041 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3042 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3043 refcount_count(&arc_mru->arcs_size) - arc_p));
3045 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3048 * Similar to the above, we want to evict enough bytes to get us
3049 * below the meta limit, but not so much as to drop us below the
3050 * space alloted to the MFU (which is defined as arc_c - arc_p).
3052 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3053 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3055 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3057 return (total_evicted);
3061 * Return the type of the oldest buffer in the given arc state
3063 * This function will select a random sublist of type ARC_BUFC_DATA and
3064 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3065 * is compared, and the type which contains the "older" buffer will be
3068 static arc_buf_contents_t
3069 arc_adjust_type(arc_state_t *state)
3071 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3072 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3073 int data_idx = multilist_get_random_index(data_ml);
3074 int meta_idx = multilist_get_random_index(meta_ml);
3075 multilist_sublist_t *data_mls;
3076 multilist_sublist_t *meta_mls;
3077 arc_buf_contents_t type;
3078 arc_buf_hdr_t *data_hdr;
3079 arc_buf_hdr_t *meta_hdr;
3082 * We keep the sublist lock until we're finished, to prevent
3083 * the headers from being destroyed via arc_evict_state().
3085 data_mls = multilist_sublist_lock(data_ml, data_idx);
3086 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3089 * These two loops are to ensure we skip any markers that
3090 * might be at the tail of the lists due to arc_evict_state().
3093 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3094 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3095 if (data_hdr->b_spa != 0)
3099 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3100 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3101 if (meta_hdr->b_spa != 0)
3105 if (data_hdr == NULL && meta_hdr == NULL) {
3106 type = ARC_BUFC_DATA;
3107 } else if (data_hdr == NULL) {
3108 ASSERT3P(meta_hdr, !=, NULL);
3109 type = ARC_BUFC_METADATA;
3110 } else if (meta_hdr == NULL) {
3111 ASSERT3P(data_hdr, !=, NULL);
3112 type = ARC_BUFC_DATA;
3114 ASSERT3P(data_hdr, !=, NULL);
3115 ASSERT3P(meta_hdr, !=, NULL);
3117 /* The headers can't be on the sublist without an L1 header */
3118 ASSERT(HDR_HAS_L1HDR(data_hdr));
3119 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3121 if (data_hdr->b_l1hdr.b_arc_access <
3122 meta_hdr->b_l1hdr.b_arc_access) {
3123 type = ARC_BUFC_DATA;
3125 type = ARC_BUFC_METADATA;
3129 multilist_sublist_unlock(meta_mls);
3130 multilist_sublist_unlock(data_mls);
3136 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3141 uint64_t total_evicted = 0;
3146 * If we're over arc_meta_limit, we want to correct that before
3147 * potentially evicting data buffers below.
3149 total_evicted += arc_adjust_meta();
3154 * If we're over the target cache size, we want to evict enough
3155 * from the list to get back to our target size. We don't want
3156 * to evict too much from the MRU, such that it drops below
3157 * arc_p. So, if we're over our target cache size more than
3158 * the MRU is over arc_p, we'll evict enough to get back to
3159 * arc_p here, and then evict more from the MFU below.
3161 target = MIN((int64_t)(arc_size - arc_c),
3162 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3163 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3166 * If we're below arc_meta_min, always prefer to evict data.
3167 * Otherwise, try to satisfy the requested number of bytes to
3168 * evict from the type which contains older buffers; in an
3169 * effort to keep newer buffers in the cache regardless of their
3170 * type. If we cannot satisfy the number of bytes from this
3171 * type, spill over into the next type.
3173 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3174 arc_meta_used > arc_meta_min) {
3175 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3176 total_evicted += bytes;
3179 * If we couldn't evict our target number of bytes from
3180 * metadata, we try to get the rest from data.
3185 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3187 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3188 total_evicted += bytes;
3191 * If we couldn't evict our target number of bytes from
3192 * data, we try to get the rest from metadata.
3197 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3203 * Now that we've tried to evict enough from the MRU to get its
3204 * size back to arc_p, if we're still above the target cache
3205 * size, we evict the rest from the MFU.
3207 target = arc_size - arc_c;
3209 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3210 arc_meta_used > arc_meta_min) {
3211 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3212 total_evicted += bytes;
3215 * If we couldn't evict our target number of bytes from
3216 * metadata, we try to get the rest from data.
3221 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3223 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3224 total_evicted += bytes;
3227 * If we couldn't evict our target number of bytes from
3228 * data, we try to get the rest from data.
3233 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3237 * Adjust ghost lists
3239 * In addition to the above, the ARC also defines target values
3240 * for the ghost lists. The sum of the mru list and mru ghost
3241 * list should never exceed the target size of the cache, and
3242 * the sum of the mru list, mfu list, mru ghost list, and mfu
3243 * ghost list should never exceed twice the target size of the
3244 * cache. The following logic enforces these limits on the ghost
3245 * caches, and evicts from them as needed.
3247 target = refcount_count(&arc_mru->arcs_size) +
3248 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3250 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3251 total_evicted += bytes;
3256 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3259 * We assume the sum of the mru list and mfu list is less than
3260 * or equal to arc_c (we enforced this above), which means we
3261 * can use the simpler of the two equations below:
3263 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3264 * mru ghost + mfu ghost <= arc_c
3266 target = refcount_count(&arc_mru_ghost->arcs_size) +
3267 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3269 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3270 total_evicted += bytes;
3275 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3277 return (total_evicted);
3281 arc_do_user_evicts(void)
3283 mutex_enter(&arc_user_evicts_lock);
3284 while (arc_eviction_list != NULL) {
3285 arc_buf_t *buf = arc_eviction_list;
3286 arc_eviction_list = buf->b_next;
3287 mutex_enter(&buf->b_evict_lock);
3289 mutex_exit(&buf->b_evict_lock);
3290 mutex_exit(&arc_user_evicts_lock);
3292 if (buf->b_efunc != NULL)
3293 VERIFY0(buf->b_efunc(buf->b_private));
3295 buf->b_efunc = NULL;
3296 buf->b_private = NULL;
3297 kmem_cache_free(buf_cache, buf);
3298 mutex_enter(&arc_user_evicts_lock);
3300 mutex_exit(&arc_user_evicts_lock);
3304 arc_flush(spa_t *spa, boolean_t retry)
3309 * If retry is TRUE, a spa must not be specified since we have
3310 * no good way to determine if all of a spa's buffers have been
3311 * evicted from an arc state.
3313 ASSERT(!retry || spa == 0);
3316 guid = spa_load_guid(spa);
3318 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3319 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3321 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3322 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3324 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3325 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3327 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3328 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3330 arc_do_user_evicts();
3331 ASSERT(spa || arc_eviction_list == NULL);
3335 arc_shrink(int64_t to_free)
3337 if (arc_c > arc_c_min) {
3338 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3339 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3340 if (arc_c > arc_c_min + to_free)
3341 atomic_add_64(&arc_c, -to_free);
3345 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3346 if (arc_c > arc_size)
3347 arc_c = MAX(arc_size, arc_c_min);
3349 arc_p = (arc_c >> 1);
3351 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3354 ASSERT(arc_c >= arc_c_min);
3355 ASSERT((int64_t)arc_p >= 0);
3358 if (arc_size > arc_c) {
3359 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3361 (void) arc_adjust();
3365 static long needfree = 0;
3367 typedef enum free_memory_reason_t {
3372 FMR_PAGES_PP_MAXIMUM,
3376 } free_memory_reason_t;
3378 int64_t last_free_memory;
3379 free_memory_reason_t last_free_reason;
3382 * Additional reserve of pages for pp_reserve.
3384 int64_t arc_pages_pp_reserve = 64;
3387 * Additional reserve of pages for swapfs.
3389 int64_t arc_swapfs_reserve = 64;
3392 * Return the amount of memory that can be consumed before reclaim will be
3393 * needed. Positive if there is sufficient free memory, negative indicates
3394 * the amount of memory that needs to be freed up.
3397 arc_available_memory(void)
3399 int64_t lowest = INT64_MAX;
3401 free_memory_reason_t r = FMR_UNKNOWN;
3405 n = PAGESIZE * (-needfree);
3413 * Cooperate with pagedaemon when it's time for it to scan
3414 * and reclaim some pages.
3416 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3424 * check that we're out of range of the pageout scanner. It starts to
3425 * schedule paging if freemem is less than lotsfree and needfree.
3426 * lotsfree is the high-water mark for pageout, and needfree is the
3427 * number of needed free pages. We add extra pages here to make sure
3428 * the scanner doesn't start up while we're freeing memory.
3430 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3437 * check to make sure that swapfs has enough space so that anon
3438 * reservations can still succeed. anon_resvmem() checks that the
3439 * availrmem is greater than swapfs_minfree, and the number of reserved
3440 * swap pages. We also add a bit of extra here just to prevent
3441 * circumstances from getting really dire.
3443 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3444 desfree - arc_swapfs_reserve);
3447 r = FMR_SWAPFS_MINFREE;
3452 * Check that we have enough availrmem that memory locking (e.g., via
3453 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3454 * stores the number of pages that cannot be locked; when availrmem
3455 * drops below pages_pp_maximum, page locking mechanisms such as
3456 * page_pp_lock() will fail.)
3458 n = PAGESIZE * (availrmem - pages_pp_maximum -
3459 arc_pages_pp_reserve);
3462 r = FMR_PAGES_PP_MAXIMUM;
3465 #endif /* illumos */
3466 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3468 * If we're on an i386 platform, it's possible that we'll exhaust the
3469 * kernel heap space before we ever run out of available physical
3470 * memory. Most checks of the size of the heap_area compare against
3471 * tune.t_minarmem, which is the minimum available real memory that we
3472 * can have in the system. However, this is generally fixed at 25 pages
3473 * which is so low that it's useless. In this comparison, we seek to
3474 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3475 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3478 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3479 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3484 #define zio_arena NULL
3486 #define zio_arena heap_arena
3490 * If zio data pages are being allocated out of a separate heap segment,
3491 * then enforce that the size of available vmem for this arena remains
3492 * above about 1/16th free.
3494 * Note: The 1/16th arena free requirement was put in place
3495 * to aggressively evict memory from the arc in order to avoid
3496 * memory fragmentation issues.
3498 if (zio_arena != NULL) {
3499 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3500 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3508 * Above limits know nothing about real level of KVA fragmentation.
3509 * Start aggressive reclamation if too little sequential KVA left.
3512 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3513 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3522 /* Every 100 calls, free a small amount */
3523 if (spa_get_random(100) == 0)
3525 #endif /* _KERNEL */
3527 last_free_memory = lowest;
3528 last_free_reason = r;
3529 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3535 * Determine if the system is under memory pressure and is asking
3536 * to reclaim memory. A return value of TRUE indicates that the system
3537 * is under memory pressure and that the arc should adjust accordingly.
3540 arc_reclaim_needed(void)
3542 return (arc_available_memory() < 0);
3545 extern kmem_cache_t *zio_buf_cache[];
3546 extern kmem_cache_t *zio_data_buf_cache[];
3547 extern kmem_cache_t *range_seg_cache;
3549 static __noinline void
3550 arc_kmem_reap_now(void)
3553 kmem_cache_t *prev_cache = NULL;
3554 kmem_cache_t *prev_data_cache = NULL;
3556 DTRACE_PROBE(arc__kmem_reap_start);
3558 if (arc_meta_used >= arc_meta_limit) {
3560 * We are exceeding our meta-data cache limit.
3561 * Purge some DNLC entries to release holds on meta-data.
3563 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3567 * Reclaim unused memory from all kmem caches.
3573 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3574 if (zio_buf_cache[i] != prev_cache) {
3575 prev_cache = zio_buf_cache[i];
3576 kmem_cache_reap_now(zio_buf_cache[i]);
3578 if (zio_data_buf_cache[i] != prev_data_cache) {
3579 prev_data_cache = zio_data_buf_cache[i];
3580 kmem_cache_reap_now(zio_data_buf_cache[i]);
3583 kmem_cache_reap_now(buf_cache);
3584 kmem_cache_reap_now(hdr_full_cache);
3585 kmem_cache_reap_now(hdr_l2only_cache);
3586 kmem_cache_reap_now(range_seg_cache);
3589 if (zio_arena != NULL) {
3591 * Ask the vmem arena to reclaim unused memory from its
3594 vmem_qcache_reap(zio_arena);
3597 DTRACE_PROBE(arc__kmem_reap_end);
3601 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3602 * enough data and signal them to proceed. When this happens, the threads in
3603 * arc_get_data_buf() are sleeping while holding the hash lock for their
3604 * particular arc header. Thus, we must be careful to never sleep on a
3605 * hash lock in this thread. This is to prevent the following deadlock:
3607 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3608 * waiting for the reclaim thread to signal it.
3610 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3611 * fails, and goes to sleep forever.
3613 * This possible deadlock is avoided by always acquiring a hash lock
3614 * using mutex_tryenter() from arc_reclaim_thread().
3617 arc_reclaim_thread(void *dummy __unused)
3619 hrtime_t growtime = 0;
3622 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3624 mutex_enter(&arc_reclaim_lock);
3625 while (!arc_reclaim_thread_exit) {
3626 int64_t free_memory = arc_available_memory();
3627 uint64_t evicted = 0;
3629 mutex_exit(&arc_reclaim_lock);
3631 if (free_memory < 0) {
3633 arc_no_grow = B_TRUE;
3637 * Wait at least zfs_grow_retry (default 60) seconds
3638 * before considering growing.
3640 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
3642 arc_kmem_reap_now();
3645 * If we are still low on memory, shrink the ARC
3646 * so that we have arc_shrink_min free space.
3648 free_memory = arc_available_memory();
3651 (arc_c >> arc_shrink_shift) - free_memory;
3654 to_free = MAX(to_free, ptob(needfree));
3656 arc_shrink(to_free);
3658 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3659 arc_no_grow = B_TRUE;
3660 } else if (gethrtime() >= growtime) {
3661 arc_no_grow = B_FALSE;
3664 evicted = arc_adjust();
3666 mutex_enter(&arc_reclaim_lock);
3669 * If evicted is zero, we couldn't evict anything via
3670 * arc_adjust(). This could be due to hash lock
3671 * collisions, but more likely due to the majority of
3672 * arc buffers being unevictable. Therefore, even if
3673 * arc_size is above arc_c, another pass is unlikely to
3674 * be helpful and could potentially cause us to enter an
3677 if (arc_size <= arc_c || evicted == 0) {
3682 * We're either no longer overflowing, or we
3683 * can't evict anything more, so we should wake
3684 * up any threads before we go to sleep.
3686 cv_broadcast(&arc_reclaim_waiters_cv);
3689 * Block until signaled, or after one second (we
3690 * might need to perform arc_kmem_reap_now()
3691 * even if we aren't being signalled)
3693 CALLB_CPR_SAFE_BEGIN(&cpr);
3694 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
3695 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
3696 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3700 arc_reclaim_thread_exit = FALSE;
3701 cv_broadcast(&arc_reclaim_thread_cv);
3702 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3707 arc_user_evicts_thread(void *dummy __unused)
3711 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3713 mutex_enter(&arc_user_evicts_lock);
3714 while (!arc_user_evicts_thread_exit) {
3715 mutex_exit(&arc_user_evicts_lock);
3717 arc_do_user_evicts();
3720 * This is necessary in order for the mdb ::arc dcmd to
3721 * show up to date information. Since the ::arc command
3722 * does not call the kstat's update function, without
3723 * this call, the command may show stale stats for the
3724 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3725 * with this change, the data might be up to 1 second
3726 * out of date; but that should suffice. The arc_state_t
3727 * structures can be queried directly if more accurate
3728 * information is needed.
3730 if (arc_ksp != NULL)
3731 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3733 mutex_enter(&arc_user_evicts_lock);
3736 * Block until signaled, or after one second (we need to
3737 * call the arc's kstat update function regularly).
3739 CALLB_CPR_SAFE_BEGIN(&cpr);
3740 (void) cv_timedwait(&arc_user_evicts_cv,
3741 &arc_user_evicts_lock, hz);
3742 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3745 arc_user_evicts_thread_exit = FALSE;
3746 cv_broadcast(&arc_user_evicts_cv);
3747 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3752 * Adapt arc info given the number of bytes we are trying to add and
3753 * the state that we are comming from. This function is only called
3754 * when we are adding new content to the cache.
3757 arc_adapt(int bytes, arc_state_t *state)
3760 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3761 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3762 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3764 if (state == arc_l2c_only)
3769 * Adapt the target size of the MRU list:
3770 * - if we just hit in the MRU ghost list, then increase
3771 * the target size of the MRU list.
3772 * - if we just hit in the MFU ghost list, then increase
3773 * the target size of the MFU list by decreasing the
3774 * target size of the MRU list.
3776 if (state == arc_mru_ghost) {
3777 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3778 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3780 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3781 } else if (state == arc_mfu_ghost) {
3784 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3785 mult = MIN(mult, 10);
3787 delta = MIN(bytes * mult, arc_p);
3788 arc_p = MAX(arc_p_min, arc_p - delta);
3790 ASSERT((int64_t)arc_p >= 0);
3792 if (arc_reclaim_needed()) {
3793 cv_signal(&arc_reclaim_thread_cv);
3800 if (arc_c >= arc_c_max)
3804 * If we're within (2 * maxblocksize) bytes of the target
3805 * cache size, increment the target cache size
3807 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3808 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3809 atomic_add_64(&arc_c, (int64_t)bytes);
3810 if (arc_c > arc_c_max)
3812 else if (state == arc_anon)
3813 atomic_add_64(&arc_p, (int64_t)bytes);
3817 ASSERT((int64_t)arc_p >= 0);
3821 * Check if arc_size has grown past our upper threshold, determined by
3822 * zfs_arc_overflow_shift.
3825 arc_is_overflowing(void)
3827 /* Always allow at least one block of overflow */
3828 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3829 arc_c >> zfs_arc_overflow_shift);
3831 return (arc_size >= arc_c + overflow);
3835 * The buffer, supplied as the first argument, needs a data block. If we
3836 * are hitting the hard limit for the cache size, we must sleep, waiting
3837 * for the eviction thread to catch up. If we're past the target size
3838 * but below the hard limit, we'll only signal the reclaim thread and
3842 arc_get_data_buf(arc_buf_t *buf)
3844 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3845 uint64_t size = buf->b_hdr->b_size;
3846 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3848 arc_adapt(size, state);
3851 * If arc_size is currently overflowing, and has grown past our
3852 * upper limit, we must be adding data faster than the evict
3853 * thread can evict. Thus, to ensure we don't compound the
3854 * problem by adding more data and forcing arc_size to grow even
3855 * further past it's target size, we halt and wait for the
3856 * eviction thread to catch up.
3858 * It's also possible that the reclaim thread is unable to evict
3859 * enough buffers to get arc_size below the overflow limit (e.g.
3860 * due to buffers being un-evictable, or hash lock collisions).
3861 * In this case, we want to proceed regardless if we're
3862 * overflowing; thus we don't use a while loop here.
3864 if (arc_is_overflowing()) {
3865 mutex_enter(&arc_reclaim_lock);
3868 * Now that we've acquired the lock, we may no longer be
3869 * over the overflow limit, lets check.
3871 * We're ignoring the case of spurious wake ups. If that
3872 * were to happen, it'd let this thread consume an ARC
3873 * buffer before it should have (i.e. before we're under
3874 * the overflow limit and were signalled by the reclaim
3875 * thread). As long as that is a rare occurrence, it
3876 * shouldn't cause any harm.
3878 if (arc_is_overflowing()) {
3879 cv_signal(&arc_reclaim_thread_cv);
3880 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3883 mutex_exit(&arc_reclaim_lock);
3886 if (type == ARC_BUFC_METADATA) {
3887 buf->b_data = zio_buf_alloc(size);
3888 arc_space_consume(size, ARC_SPACE_META);
3890 ASSERT(type == ARC_BUFC_DATA);
3891 buf->b_data = zio_data_buf_alloc(size);
3892 arc_space_consume(size, ARC_SPACE_DATA);
3896 * Update the state size. Note that ghost states have a
3897 * "ghost size" and so don't need to be updated.
3899 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3900 arc_buf_hdr_t *hdr = buf->b_hdr;
3901 arc_state_t *state = hdr->b_l1hdr.b_state;
3903 (void) refcount_add_many(&state->arcs_size, size, buf);
3906 * If this is reached via arc_read, the link is
3907 * protected by the hash lock. If reached via
3908 * arc_buf_alloc, the header should not be accessed by
3909 * any other thread. And, if reached via arc_read_done,
3910 * the hash lock will protect it if it's found in the
3911 * hash table; otherwise no other thread should be
3912 * trying to [add|remove]_reference it.
3914 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3915 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3916 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3920 * If we are growing the cache, and we are adding anonymous
3921 * data, and we have outgrown arc_p, update arc_p
3923 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3924 (refcount_count(&arc_anon->arcs_size) +
3925 refcount_count(&arc_mru->arcs_size) > arc_p))
3926 arc_p = MIN(arc_c, arc_p + size);
3928 ARCSTAT_BUMP(arcstat_allocated);
3932 * This routine is called whenever a buffer is accessed.
3933 * NOTE: the hash lock is dropped in this function.
3936 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3940 ASSERT(MUTEX_HELD(hash_lock));
3941 ASSERT(HDR_HAS_L1HDR(hdr));
3943 if (hdr->b_l1hdr.b_state == arc_anon) {
3945 * This buffer is not in the cache, and does not
3946 * appear in our "ghost" list. Add the new buffer
3950 ASSERT0(hdr->b_l1hdr.b_arc_access);
3951 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3952 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3953 arc_change_state(arc_mru, hdr, hash_lock);
3955 } else if (hdr->b_l1hdr.b_state == arc_mru) {
3956 now = ddi_get_lbolt();
3959 * If this buffer is here because of a prefetch, then either:
3960 * - clear the flag if this is a "referencing" read
3961 * (any subsequent access will bump this into the MFU state).
3963 * - move the buffer to the head of the list if this is
3964 * another prefetch (to make it less likely to be evicted).
3966 if (HDR_PREFETCH(hdr)) {
3967 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3968 /* link protected by hash lock */
3969 ASSERT(multilist_link_active(
3970 &hdr->b_l1hdr.b_arc_node));
3972 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3973 ARCSTAT_BUMP(arcstat_mru_hits);
3975 hdr->b_l1hdr.b_arc_access = now;
3980 * This buffer has been "accessed" only once so far,
3981 * but it is still in the cache. Move it to the MFU
3984 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3986 * More than 125ms have passed since we
3987 * instantiated this buffer. Move it to the
3988 * most frequently used state.
3990 hdr->b_l1hdr.b_arc_access = now;
3991 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3992 arc_change_state(arc_mfu, hdr, hash_lock);
3994 ARCSTAT_BUMP(arcstat_mru_hits);
3995 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3996 arc_state_t *new_state;
3998 * This buffer has been "accessed" recently, but
3999 * was evicted from the cache. Move it to the
4003 if (HDR_PREFETCH(hdr)) {
4004 new_state = arc_mru;
4005 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4006 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
4007 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4009 new_state = arc_mfu;
4010 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4013 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4014 arc_change_state(new_state, hdr, hash_lock);
4016 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4017 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
4019 * This buffer has been accessed more than once and is
4020 * still in the cache. Keep it in the MFU state.
4022 * NOTE: an add_reference() that occurred when we did
4023 * the arc_read() will have kicked this off the list.
4024 * If it was a prefetch, we will explicitly move it to
4025 * the head of the list now.
4027 if ((HDR_PREFETCH(hdr)) != 0) {
4028 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4029 /* link protected by hash_lock */
4030 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4032 ARCSTAT_BUMP(arcstat_mfu_hits);
4033 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4034 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4035 arc_state_t *new_state = arc_mfu;
4037 * This buffer has been accessed more than once but has
4038 * been evicted from the cache. Move it back to the
4042 if (HDR_PREFETCH(hdr)) {
4044 * This is a prefetch access...
4045 * move this block back to the MRU state.
4047 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4048 new_state = arc_mru;
4051 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4052 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4053 arc_change_state(new_state, hdr, hash_lock);
4055 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4056 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4058 * This buffer is on the 2nd Level ARC.
4061 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4062 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4063 arc_change_state(arc_mfu, hdr, hash_lock);
4065 ASSERT(!"invalid arc state");
4069 /* a generic arc_done_func_t which you can use */
4072 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4074 if (zio == NULL || zio->io_error == 0)
4075 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4076 VERIFY(arc_buf_remove_ref(buf, arg));
4079 /* a generic arc_done_func_t */
4081 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4083 arc_buf_t **bufp = arg;
4084 if (zio && zio->io_error) {
4085 VERIFY(arc_buf_remove_ref(buf, arg));
4089 ASSERT(buf->b_data);
4094 arc_read_done(zio_t *zio)
4098 arc_buf_t *abuf; /* buffer we're assigning to callback */
4099 kmutex_t *hash_lock = NULL;
4100 arc_callback_t *callback_list, *acb;
4101 int freeable = FALSE;
4103 buf = zio->io_private;
4107 * The hdr was inserted into hash-table and removed from lists
4108 * prior to starting I/O. We should find this header, since
4109 * it's in the hash table, and it should be legit since it's
4110 * not possible to evict it during the I/O. The only possible
4111 * reason for it not to be found is if we were freed during the
4114 if (HDR_IN_HASH_TABLE(hdr)) {
4115 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4116 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4117 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4118 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4119 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4121 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4124 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4125 hash_lock == NULL) ||
4127 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4128 (found == hdr && HDR_L2_READING(hdr)));
4131 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4132 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4133 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4135 /* byteswap if necessary */
4136 callback_list = hdr->b_l1hdr.b_acb;
4137 ASSERT(callback_list != NULL);
4138 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4139 dmu_object_byteswap_t bswap =
4140 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4141 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4142 byteswap_uint64_array :
4143 dmu_ot_byteswap[bswap].ob_func;
4144 func(buf->b_data, hdr->b_size);
4147 arc_cksum_compute(buf, B_FALSE);
4152 if (hash_lock && zio->io_error == 0 &&
4153 hdr->b_l1hdr.b_state == arc_anon) {
4155 * Only call arc_access on anonymous buffers. This is because
4156 * if we've issued an I/O for an evicted buffer, we've already
4157 * called arc_access (to prevent any simultaneous readers from
4158 * getting confused).
4160 arc_access(hdr, hash_lock);
4163 /* create copies of the data buffer for the callers */
4165 for (acb = callback_list; acb; acb = acb->acb_next) {
4166 if (acb->acb_done) {
4168 ARCSTAT_BUMP(arcstat_duplicate_reads);
4169 abuf = arc_buf_clone(buf);
4171 acb->acb_buf = abuf;
4175 hdr->b_l1hdr.b_acb = NULL;
4176 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4177 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4179 ASSERT(buf->b_efunc == NULL);
4180 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4181 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4184 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4185 callback_list != NULL);
4187 if (zio->io_error != 0) {
4188 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4189 if (hdr->b_l1hdr.b_state != arc_anon)
4190 arc_change_state(arc_anon, hdr, hash_lock);
4191 if (HDR_IN_HASH_TABLE(hdr))
4192 buf_hash_remove(hdr);
4193 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4197 * Broadcast before we drop the hash_lock to avoid the possibility
4198 * that the hdr (and hence the cv) might be freed before we get to
4199 * the cv_broadcast().
4201 cv_broadcast(&hdr->b_l1hdr.b_cv);
4203 if (hash_lock != NULL) {
4204 mutex_exit(hash_lock);
4207 * This block was freed while we waited for the read to
4208 * complete. It has been removed from the hash table and
4209 * moved to the anonymous state (so that it won't show up
4212 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4213 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4216 /* execute each callback and free its structure */
4217 while ((acb = callback_list) != NULL) {
4219 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4221 if (acb->acb_zio_dummy != NULL) {
4222 acb->acb_zio_dummy->io_error = zio->io_error;
4223 zio_nowait(acb->acb_zio_dummy);
4226 callback_list = acb->acb_next;
4227 kmem_free(acb, sizeof (arc_callback_t));
4231 arc_hdr_destroy(hdr);
4235 * "Read" the block at the specified DVA (in bp) via the
4236 * cache. If the block is found in the cache, invoke the provided
4237 * callback immediately and return. Note that the `zio' parameter
4238 * in the callback will be NULL in this case, since no IO was
4239 * required. If the block is not in the cache pass the read request
4240 * on to the spa with a substitute callback function, so that the
4241 * requested block will be added to the cache.
4243 * If a read request arrives for a block that has a read in-progress,
4244 * either wait for the in-progress read to complete (and return the
4245 * results); or, if this is a read with a "done" func, add a record
4246 * to the read to invoke the "done" func when the read completes,
4247 * and return; or just return.
4249 * arc_read_done() will invoke all the requested "done" functions
4250 * for readers of this block.
4253 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4254 void *private, zio_priority_t priority, int zio_flags,
4255 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4257 arc_buf_hdr_t *hdr = NULL;
4258 arc_buf_t *buf = NULL;
4259 kmutex_t *hash_lock = NULL;
4261 uint64_t guid = spa_load_guid(spa);
4263 ASSERT(!BP_IS_EMBEDDED(bp) ||
4264 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4267 if (!BP_IS_EMBEDDED(bp)) {
4269 * Embedded BP's have no DVA and require no I/O to "read".
4270 * Create an anonymous arc buf to back it.
4272 hdr = buf_hash_find(guid, bp, &hash_lock);
4275 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4277 *arc_flags |= ARC_FLAG_CACHED;
4279 if (HDR_IO_IN_PROGRESS(hdr)) {
4281 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4282 priority == ZIO_PRIORITY_SYNC_READ) {
4284 * This sync read must wait for an
4285 * in-progress async read (e.g. a predictive
4286 * prefetch). Async reads are queued
4287 * separately at the vdev_queue layer, so
4288 * this is a form of priority inversion.
4289 * Ideally, we would "inherit" the demand
4290 * i/o's priority by moving the i/o from
4291 * the async queue to the synchronous queue,
4292 * but there is currently no mechanism to do
4293 * so. Track this so that we can evaluate
4294 * the magnitude of this potential performance
4297 * Note that if the prefetch i/o is already
4298 * active (has been issued to the device),
4299 * the prefetch improved performance, because
4300 * we issued it sooner than we would have
4301 * without the prefetch.
4303 DTRACE_PROBE1(arc__sync__wait__for__async,
4304 arc_buf_hdr_t *, hdr);
4305 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4307 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4308 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4311 if (*arc_flags & ARC_FLAG_WAIT) {
4312 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4313 mutex_exit(hash_lock);
4316 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4319 arc_callback_t *acb = NULL;
4321 acb = kmem_zalloc(sizeof (arc_callback_t),
4323 acb->acb_done = done;
4324 acb->acb_private = private;
4326 acb->acb_zio_dummy = zio_null(pio,
4327 spa, NULL, NULL, NULL, zio_flags);
4329 ASSERT(acb->acb_done != NULL);
4330 acb->acb_next = hdr->b_l1hdr.b_acb;
4331 hdr->b_l1hdr.b_acb = acb;
4332 add_reference(hdr, hash_lock, private);
4333 mutex_exit(hash_lock);
4336 mutex_exit(hash_lock);
4340 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4341 hdr->b_l1hdr.b_state == arc_mfu);
4344 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4346 * This is a demand read which does not have to
4347 * wait for i/o because we did a predictive
4348 * prefetch i/o for it, which has completed.
4351 arc__demand__hit__predictive__prefetch,
4352 arc_buf_hdr_t *, hdr);
4354 arcstat_demand_hit_predictive_prefetch);
4355 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4357 add_reference(hdr, hash_lock, private);
4359 * If this block is already in use, create a new
4360 * copy of the data so that we will be guaranteed
4361 * that arc_release() will always succeed.
4363 buf = hdr->b_l1hdr.b_buf;
4365 ASSERT(buf->b_data);
4366 if (HDR_BUF_AVAILABLE(hdr)) {
4367 ASSERT(buf->b_efunc == NULL);
4368 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4370 buf = arc_buf_clone(buf);
4373 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4374 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4375 hdr->b_flags |= ARC_FLAG_PREFETCH;
4377 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4378 arc_access(hdr, hash_lock);
4379 if (*arc_flags & ARC_FLAG_L2CACHE)
4380 hdr->b_flags |= ARC_FLAG_L2CACHE;
4381 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4382 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4383 mutex_exit(hash_lock);
4384 ARCSTAT_BUMP(arcstat_hits);
4385 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4386 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4387 data, metadata, hits);
4390 done(NULL, buf, private);
4392 uint64_t size = BP_GET_LSIZE(bp);
4393 arc_callback_t *acb;
4396 boolean_t devw = B_FALSE;
4397 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4398 int32_t b_asize = 0;
4401 /* this block is not in the cache */
4402 arc_buf_hdr_t *exists = NULL;
4403 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4404 buf = arc_buf_alloc(spa, size, private, type);
4406 if (!BP_IS_EMBEDDED(bp)) {
4407 hdr->b_dva = *BP_IDENTITY(bp);
4408 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4409 exists = buf_hash_insert(hdr, &hash_lock);
4411 if (exists != NULL) {
4412 /* somebody beat us to the hash insert */
4413 mutex_exit(hash_lock);
4414 buf_discard_identity(hdr);
4415 (void) arc_buf_remove_ref(buf, private);
4416 goto top; /* restart the IO request */
4420 * If there is a callback, we pass our reference to
4421 * it; otherwise we remove our reference.
4424 (void) remove_reference(hdr, hash_lock,
4427 if (*arc_flags & ARC_FLAG_PREFETCH)
4428 hdr->b_flags |= ARC_FLAG_PREFETCH;
4429 if (*arc_flags & ARC_FLAG_L2CACHE)
4430 hdr->b_flags |= ARC_FLAG_L2CACHE;
4431 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4432 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4433 if (BP_GET_LEVEL(bp) > 0)
4434 hdr->b_flags |= ARC_FLAG_INDIRECT;
4437 * This block is in the ghost cache. If it was L2-only
4438 * (and thus didn't have an L1 hdr), we realloc the
4439 * header to add an L1 hdr.
4441 if (!HDR_HAS_L1HDR(hdr)) {
4442 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4446 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4447 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4448 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4449 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4452 * If there is a callback, we pass a reference to it.
4455 add_reference(hdr, hash_lock, private);
4456 if (*arc_flags & ARC_FLAG_PREFETCH)
4457 hdr->b_flags |= ARC_FLAG_PREFETCH;
4458 if (*arc_flags & ARC_FLAG_L2CACHE)
4459 hdr->b_flags |= ARC_FLAG_L2CACHE;
4460 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4461 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4462 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4465 buf->b_efunc = NULL;
4466 buf->b_private = NULL;
4468 hdr->b_l1hdr.b_buf = buf;
4469 ASSERT0(hdr->b_l1hdr.b_datacnt);
4470 hdr->b_l1hdr.b_datacnt = 1;
4471 arc_get_data_buf(buf);
4472 arc_access(hdr, hash_lock);
4475 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4476 hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
4477 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4479 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4480 acb->acb_done = done;
4481 acb->acb_private = private;
4483 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4484 hdr->b_l1hdr.b_acb = acb;
4485 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4487 if (HDR_HAS_L2HDR(hdr) &&
4488 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4489 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4490 addr = hdr->b_l2hdr.b_daddr;
4491 b_compress = hdr->b_l2hdr.b_compress;
4492 b_asize = hdr->b_l2hdr.b_asize;
4494 * Lock out device removal.
4496 if (vdev_is_dead(vd) ||
4497 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4501 if (hash_lock != NULL)
4502 mutex_exit(hash_lock);
4505 * At this point, we have a level 1 cache miss. Try again in
4506 * L2ARC if possible.
4508 ASSERT3U(hdr->b_size, ==, size);
4509 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4510 uint64_t, size, zbookmark_phys_t *, zb);
4511 ARCSTAT_BUMP(arcstat_misses);
4512 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4513 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4514 data, metadata, misses);
4519 racct_add_force(curproc, RACCT_READBPS, size);
4520 racct_add_force(curproc, RACCT_READIOPS, 1);
4521 PROC_UNLOCK(curproc);
4524 curthread->td_ru.ru_inblock++;
4527 if (priority == ZIO_PRIORITY_ASYNC_READ)
4528 hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4530 hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4532 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4534 * Read from the L2ARC if the following are true:
4535 * 1. The L2ARC vdev was previously cached.
4536 * 2. This buffer still has L2ARC metadata.
4537 * 3. This buffer isn't currently writing to the L2ARC.
4538 * 4. The L2ARC entry wasn't evicted, which may
4539 * also have invalidated the vdev.
4540 * 5. This isn't prefetch and l2arc_noprefetch is set.
4542 if (HDR_HAS_L2HDR(hdr) &&
4543 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4544 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4545 l2arc_read_callback_t *cb;
4548 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4549 ARCSTAT_BUMP(arcstat_l2_hits);
4551 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4553 cb->l2rcb_buf = buf;
4554 cb->l2rcb_spa = spa;
4557 cb->l2rcb_flags = zio_flags;
4558 cb->l2rcb_compress = b_compress;
4559 if (b_asize > hdr->b_size) {
4560 ASSERT3U(b_compress, ==,
4562 b_data = zio_data_buf_alloc(b_asize);
4563 cb->l2rcb_data = b_data;
4565 b_data = buf->b_data;
4568 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4569 addr + size < vd->vdev_psize -
4570 VDEV_LABEL_END_SIZE);
4573 * l2arc read. The SCL_L2ARC lock will be
4574 * released by l2arc_read_done().
4575 * Issue a null zio if the underlying buffer
4576 * was squashed to zero size by compression.
4578 if (b_compress == ZIO_COMPRESS_EMPTY) {
4579 ASSERT3U(b_asize, ==, 0);
4580 rzio = zio_null(pio, spa, vd,
4581 l2arc_read_done, cb,
4582 zio_flags | ZIO_FLAG_DONT_CACHE |
4584 ZIO_FLAG_DONT_PROPAGATE |
4585 ZIO_FLAG_DONT_RETRY);
4587 rzio = zio_read_phys(pio, vd, addr,
4590 l2arc_read_done, cb, priority,
4591 zio_flags | ZIO_FLAG_DONT_CACHE |
4593 ZIO_FLAG_DONT_PROPAGATE |
4594 ZIO_FLAG_DONT_RETRY, B_FALSE);
4596 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4598 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4600 if (*arc_flags & ARC_FLAG_NOWAIT) {
4605 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4606 if (zio_wait(rzio) == 0)
4609 /* l2arc read error; goto zio_read() */
4611 DTRACE_PROBE1(l2arc__miss,
4612 arc_buf_hdr_t *, hdr);
4613 ARCSTAT_BUMP(arcstat_l2_misses);
4614 if (HDR_L2_WRITING(hdr))
4615 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4616 spa_config_exit(spa, SCL_L2ARC, vd);
4620 spa_config_exit(spa, SCL_L2ARC, vd);
4621 if (l2arc_ndev != 0) {
4622 DTRACE_PROBE1(l2arc__miss,
4623 arc_buf_hdr_t *, hdr);
4624 ARCSTAT_BUMP(arcstat_l2_misses);
4628 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4629 arc_read_done, buf, priority, zio_flags, zb);
4631 if (*arc_flags & ARC_FLAG_WAIT)
4632 return (zio_wait(rzio));
4634 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4641 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4643 ASSERT(buf->b_hdr != NULL);
4644 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4645 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4647 ASSERT(buf->b_efunc == NULL);
4648 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4650 buf->b_efunc = func;
4651 buf->b_private = private;
4655 * Notify the arc that a block was freed, and thus will never be used again.
4658 arc_freed(spa_t *spa, const blkptr_t *bp)
4661 kmutex_t *hash_lock;
4662 uint64_t guid = spa_load_guid(spa);
4664 ASSERT(!BP_IS_EMBEDDED(bp));
4666 hdr = buf_hash_find(guid, bp, &hash_lock);
4669 if (HDR_BUF_AVAILABLE(hdr)) {
4670 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4671 add_reference(hdr, hash_lock, FTAG);
4672 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4673 mutex_exit(hash_lock);
4675 arc_release(buf, FTAG);
4676 (void) arc_buf_remove_ref(buf, FTAG);
4678 mutex_exit(hash_lock);
4684 * Clear the user eviction callback set by arc_set_callback(), first calling
4685 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4686 * clearing the callback may result in the arc_buf being destroyed. However,
4687 * it will not result in the *last* arc_buf being destroyed, hence the data
4688 * will remain cached in the ARC. We make a copy of the arc buffer here so
4689 * that we can process the callback without holding any locks.
4691 * It's possible that the callback is already in the process of being cleared
4692 * by another thread. In this case we can not clear the callback.
4694 * Returns B_TRUE if the callback was successfully called and cleared.
4697 arc_clear_callback(arc_buf_t *buf)
4700 kmutex_t *hash_lock;
4701 arc_evict_func_t *efunc = buf->b_efunc;
4702 void *private = buf->b_private;
4704 mutex_enter(&buf->b_evict_lock);
4708 * We are in arc_do_user_evicts().
4710 ASSERT(buf->b_data == NULL);
4711 mutex_exit(&buf->b_evict_lock);
4713 } else if (buf->b_data == NULL) {
4715 * We are on the eviction list; process this buffer now
4716 * but let arc_do_user_evicts() do the reaping.
4718 buf->b_efunc = NULL;
4719 mutex_exit(&buf->b_evict_lock);
4720 VERIFY0(efunc(private));
4723 hash_lock = HDR_LOCK(hdr);
4724 mutex_enter(hash_lock);
4726 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4728 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4729 hdr->b_l1hdr.b_datacnt);
4730 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4731 hdr->b_l1hdr.b_state == arc_mfu);
4733 buf->b_efunc = NULL;
4734 buf->b_private = NULL;
4736 if (hdr->b_l1hdr.b_datacnt > 1) {
4737 mutex_exit(&buf->b_evict_lock);
4738 arc_buf_destroy(buf, TRUE);
4740 ASSERT(buf == hdr->b_l1hdr.b_buf);
4741 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4742 mutex_exit(&buf->b_evict_lock);
4745 mutex_exit(hash_lock);
4746 VERIFY0(efunc(private));
4751 * Release this buffer from the cache, making it an anonymous buffer. This
4752 * must be done after a read and prior to modifying the buffer contents.
4753 * If the buffer has more than one reference, we must make
4754 * a new hdr for the buffer.
4757 arc_release(arc_buf_t *buf, void *tag)
4759 arc_buf_hdr_t *hdr = buf->b_hdr;
4762 * It would be nice to assert that if it's DMU metadata (level >
4763 * 0 || it's the dnode file), then it must be syncing context.
4764 * But we don't know that information at this level.
4767 mutex_enter(&buf->b_evict_lock);
4769 ASSERT(HDR_HAS_L1HDR(hdr));
4772 * We don't grab the hash lock prior to this check, because if
4773 * the buffer's header is in the arc_anon state, it won't be
4774 * linked into the hash table.
4776 if (hdr->b_l1hdr.b_state == arc_anon) {
4777 mutex_exit(&buf->b_evict_lock);
4778 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4779 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4780 ASSERT(!HDR_HAS_L2HDR(hdr));
4781 ASSERT(BUF_EMPTY(hdr));
4782 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4783 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4784 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4786 ASSERT3P(buf->b_efunc, ==, NULL);
4787 ASSERT3P(buf->b_private, ==, NULL);
4789 hdr->b_l1hdr.b_arc_access = 0;
4795 kmutex_t *hash_lock = HDR_LOCK(hdr);
4796 mutex_enter(hash_lock);
4799 * This assignment is only valid as long as the hash_lock is
4800 * held, we must be careful not to reference state or the
4801 * b_state field after dropping the lock.
4803 arc_state_t *state = hdr->b_l1hdr.b_state;
4804 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4805 ASSERT3P(state, !=, arc_anon);
4807 /* this buffer is not on any list */
4808 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4810 if (HDR_HAS_L2HDR(hdr)) {
4811 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4814 * We have to recheck this conditional again now that
4815 * we're holding the l2ad_mtx to prevent a race with
4816 * another thread which might be concurrently calling
4817 * l2arc_evict(). In that case, l2arc_evict() might have
4818 * destroyed the header's L2 portion as we were waiting
4819 * to acquire the l2ad_mtx.
4821 if (HDR_HAS_L2HDR(hdr)) {
4823 arc_hdr_l2hdr_destroy(hdr);
4826 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4830 * Do we have more than one buf?
4832 if (hdr->b_l1hdr.b_datacnt > 1) {
4833 arc_buf_hdr_t *nhdr;
4835 uint64_t blksz = hdr->b_size;
4836 uint64_t spa = hdr->b_spa;
4837 arc_buf_contents_t type = arc_buf_type(hdr);
4838 uint32_t flags = hdr->b_flags;
4840 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4842 * Pull the data off of this hdr and attach it to
4843 * a new anonymous hdr.
4845 (void) remove_reference(hdr, hash_lock, tag);
4846 bufp = &hdr->b_l1hdr.b_buf;
4847 while (*bufp != buf)
4848 bufp = &(*bufp)->b_next;
4849 *bufp = buf->b_next;
4852 ASSERT3P(state, !=, arc_l2c_only);
4854 (void) refcount_remove_many(
4855 &state->arcs_size, hdr->b_size, buf);
4857 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4858 ASSERT3P(state, !=, arc_l2c_only);
4859 uint64_t *size = &state->arcs_lsize[type];
4860 ASSERT3U(*size, >=, hdr->b_size);
4861 atomic_add_64(size, -hdr->b_size);
4865 * We're releasing a duplicate user data buffer, update
4866 * our statistics accordingly.
4868 if (HDR_ISTYPE_DATA(hdr)) {
4869 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4870 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4873 hdr->b_l1hdr.b_datacnt -= 1;
4874 arc_cksum_verify(buf);
4876 arc_buf_unwatch(buf);
4879 mutex_exit(hash_lock);
4881 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4882 nhdr->b_size = blksz;
4885 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4886 nhdr->b_flags |= arc_bufc_to_flags(type);
4887 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4889 nhdr->b_l1hdr.b_buf = buf;
4890 nhdr->b_l1hdr.b_datacnt = 1;
4891 nhdr->b_l1hdr.b_state = arc_anon;
4892 nhdr->b_l1hdr.b_arc_access = 0;
4893 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4894 nhdr->b_freeze_cksum = NULL;
4896 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4898 mutex_exit(&buf->b_evict_lock);
4899 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4901 mutex_exit(&buf->b_evict_lock);
4902 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4903 /* protected by hash lock, or hdr is on arc_anon */
4904 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4905 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4906 arc_change_state(arc_anon, hdr, hash_lock);
4907 hdr->b_l1hdr.b_arc_access = 0;
4908 mutex_exit(hash_lock);
4910 buf_discard_identity(hdr);
4913 buf->b_efunc = NULL;
4914 buf->b_private = NULL;
4918 arc_released(arc_buf_t *buf)
4922 mutex_enter(&buf->b_evict_lock);
4923 released = (buf->b_data != NULL &&
4924 buf->b_hdr->b_l1hdr.b_state == arc_anon);
4925 mutex_exit(&buf->b_evict_lock);
4931 arc_referenced(arc_buf_t *buf)
4935 mutex_enter(&buf->b_evict_lock);
4936 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4937 mutex_exit(&buf->b_evict_lock);
4938 return (referenced);
4943 arc_write_ready(zio_t *zio)
4945 arc_write_callback_t *callback = zio->io_private;
4946 arc_buf_t *buf = callback->awcb_buf;
4947 arc_buf_hdr_t *hdr = buf->b_hdr;
4949 ASSERT(HDR_HAS_L1HDR(hdr));
4950 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4951 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4952 callback->awcb_ready(zio, buf, callback->awcb_private);
4955 * If the IO is already in progress, then this is a re-write
4956 * attempt, so we need to thaw and re-compute the cksum.
4957 * It is the responsibility of the callback to handle the
4958 * accounting for any re-write attempt.
4960 if (HDR_IO_IN_PROGRESS(hdr)) {
4961 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4962 if (hdr->b_freeze_cksum != NULL) {
4963 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4964 hdr->b_freeze_cksum = NULL;
4966 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4968 arc_cksum_compute(buf, B_FALSE);
4969 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4973 * The SPA calls this callback for each physical write that happens on behalf
4974 * of a logical write. See the comment in dbuf_write_physdone() for details.
4977 arc_write_physdone(zio_t *zio)
4979 arc_write_callback_t *cb = zio->io_private;
4980 if (cb->awcb_physdone != NULL)
4981 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4985 arc_write_done(zio_t *zio)
4987 arc_write_callback_t *callback = zio->io_private;
4988 arc_buf_t *buf = callback->awcb_buf;
4989 arc_buf_hdr_t *hdr = buf->b_hdr;
4991 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4993 if (zio->io_error == 0) {
4994 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4995 buf_discard_identity(hdr);
4997 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4998 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5001 ASSERT(BUF_EMPTY(hdr));
5005 * If the block to be written was all-zero or compressed enough to be
5006 * embedded in the BP, no write was performed so there will be no
5007 * dva/birth/checksum. The buffer must therefore remain anonymous
5010 if (!BUF_EMPTY(hdr)) {
5011 arc_buf_hdr_t *exists;
5012 kmutex_t *hash_lock;
5014 ASSERT(zio->io_error == 0);
5016 arc_cksum_verify(buf);
5018 exists = buf_hash_insert(hdr, &hash_lock);
5019 if (exists != NULL) {
5021 * This can only happen if we overwrite for
5022 * sync-to-convergence, because we remove
5023 * buffers from the hash table when we arc_free().
5025 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5026 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5027 panic("bad overwrite, hdr=%p exists=%p",
5028 (void *)hdr, (void *)exists);
5029 ASSERT(refcount_is_zero(
5030 &exists->b_l1hdr.b_refcnt));
5031 arc_change_state(arc_anon, exists, hash_lock);
5032 mutex_exit(hash_lock);
5033 arc_hdr_destroy(exists);
5034 exists = buf_hash_insert(hdr, &hash_lock);
5035 ASSERT3P(exists, ==, NULL);
5036 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5038 ASSERT(zio->io_prop.zp_nopwrite);
5039 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5040 panic("bad nopwrite, hdr=%p exists=%p",
5041 (void *)hdr, (void *)exists);
5044 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5045 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5046 ASSERT(BP_GET_DEDUP(zio->io_bp));
5047 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5050 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5051 /* if it's not anon, we are doing a scrub */
5052 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5053 arc_access(hdr, hash_lock);
5054 mutex_exit(hash_lock);
5056 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5059 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5060 callback->awcb_done(zio, buf, callback->awcb_private);
5062 kmem_free(callback, sizeof (arc_write_callback_t));
5066 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
5067 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
5068 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
5069 arc_done_func_t *done, void *private, zio_priority_t priority,
5070 int zio_flags, const zbookmark_phys_t *zb)
5072 arc_buf_hdr_t *hdr = buf->b_hdr;
5073 arc_write_callback_t *callback;
5076 ASSERT(ready != NULL);
5077 ASSERT(done != NULL);
5078 ASSERT(!HDR_IO_ERROR(hdr));
5079 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5080 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5081 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5083 hdr->b_flags |= ARC_FLAG_L2CACHE;
5085 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
5086 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5087 callback->awcb_ready = ready;
5088 callback->awcb_physdone = physdone;
5089 callback->awcb_done = done;
5090 callback->awcb_private = private;
5091 callback->awcb_buf = buf;
5093 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
5094 arc_write_ready, arc_write_physdone, arc_write_done, callback,
5095 priority, zio_flags, zb);
5101 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5104 uint64_t available_memory = ptob(freemem);
5105 static uint64_t page_load = 0;
5106 static uint64_t last_txg = 0;
5108 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5110 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5113 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5116 if (txg > last_txg) {
5121 * If we are in pageout, we know that memory is already tight,
5122 * the arc is already going to be evicting, so we just want to
5123 * continue to let page writes occur as quickly as possible.
5125 if (curproc == pageproc) {
5126 if (page_load > MAX(ptob(minfree), available_memory) / 4)
5127 return (SET_ERROR(ERESTART));
5128 /* Note: reserve is inflated, so we deflate */
5129 page_load += reserve / 8;
5131 } else if (page_load > 0 && arc_reclaim_needed()) {
5132 /* memory is low, delay before restarting */
5133 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5134 return (SET_ERROR(EAGAIN));
5142 arc_tempreserve_clear(uint64_t reserve)
5144 atomic_add_64(&arc_tempreserve, -reserve);
5145 ASSERT((int64_t)arc_tempreserve >= 0);
5149 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5154 if (reserve > arc_c/4 && !arc_no_grow) {
5155 arc_c = MIN(arc_c_max, reserve * 4);
5156 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5158 if (reserve > arc_c)
5159 return (SET_ERROR(ENOMEM));
5162 * Don't count loaned bufs as in flight dirty data to prevent long
5163 * network delays from blocking transactions that are ready to be
5164 * assigned to a txg.
5166 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5167 arc_loaned_bytes), 0);
5170 * Writes will, almost always, require additional memory allocations
5171 * in order to compress/encrypt/etc the data. We therefore need to
5172 * make sure that there is sufficient available memory for this.
5174 error = arc_memory_throttle(reserve, txg);
5179 * Throttle writes when the amount of dirty data in the cache
5180 * gets too large. We try to keep the cache less than half full
5181 * of dirty blocks so that our sync times don't grow too large.
5182 * Note: if two requests come in concurrently, we might let them
5183 * both succeed, when one of them should fail. Not a huge deal.
5186 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5187 anon_size > arc_c / 4) {
5188 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5189 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5190 arc_tempreserve>>10,
5191 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5192 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5193 reserve>>10, arc_c>>10);
5194 return (SET_ERROR(ERESTART));
5196 atomic_add_64(&arc_tempreserve, reserve);
5201 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5202 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5204 size->value.ui64 = refcount_count(&state->arcs_size);
5205 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5206 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5210 arc_kstat_update(kstat_t *ksp, int rw)
5212 arc_stats_t *as = ksp->ks_data;
5214 if (rw == KSTAT_WRITE) {
5217 arc_kstat_update_state(arc_anon,
5218 &as->arcstat_anon_size,
5219 &as->arcstat_anon_evictable_data,
5220 &as->arcstat_anon_evictable_metadata);
5221 arc_kstat_update_state(arc_mru,
5222 &as->arcstat_mru_size,
5223 &as->arcstat_mru_evictable_data,
5224 &as->arcstat_mru_evictable_metadata);
5225 arc_kstat_update_state(arc_mru_ghost,
5226 &as->arcstat_mru_ghost_size,
5227 &as->arcstat_mru_ghost_evictable_data,
5228 &as->arcstat_mru_ghost_evictable_metadata);
5229 arc_kstat_update_state(arc_mfu,
5230 &as->arcstat_mfu_size,
5231 &as->arcstat_mfu_evictable_data,
5232 &as->arcstat_mfu_evictable_metadata);
5233 arc_kstat_update_state(arc_mfu_ghost,
5234 &as->arcstat_mfu_ghost_size,
5235 &as->arcstat_mfu_ghost_evictable_data,
5236 &as->arcstat_mfu_ghost_evictable_metadata);
5243 * This function *must* return indices evenly distributed between all
5244 * sublists of the multilist. This is needed due to how the ARC eviction
5245 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5246 * distributed between all sublists and uses this assumption when
5247 * deciding which sublist to evict from and how much to evict from it.
5250 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5252 arc_buf_hdr_t *hdr = obj;
5255 * We rely on b_dva to generate evenly distributed index
5256 * numbers using buf_hash below. So, as an added precaution,
5257 * let's make sure we never add empty buffers to the arc lists.
5259 ASSERT(!BUF_EMPTY(hdr));
5262 * The assumption here, is the hash value for a given
5263 * arc_buf_hdr_t will remain constant throughout it's lifetime
5264 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5265 * Thus, we don't need to store the header's sublist index
5266 * on insertion, as this index can be recalculated on removal.
5268 * Also, the low order bits of the hash value are thought to be
5269 * distributed evenly. Otherwise, in the case that the multilist
5270 * has a power of two number of sublists, each sublists' usage
5271 * would not be evenly distributed.
5273 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5274 multilist_get_num_sublists(ml));
5278 static eventhandler_tag arc_event_lowmem = NULL;
5281 arc_lowmem(void *arg __unused, int howto __unused)
5284 mutex_enter(&arc_reclaim_lock);
5285 /* XXX: Memory deficit should be passed as argument. */
5286 needfree = btoc(arc_c >> arc_shrink_shift);
5287 DTRACE_PROBE(arc__needfree);
5288 cv_signal(&arc_reclaim_thread_cv);
5291 * It is unsafe to block here in arbitrary threads, because we can come
5292 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5293 * with ARC reclaim thread.
5295 if (curproc == pageproc)
5296 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5297 mutex_exit(&arc_reclaim_lock);
5304 int i, prefetch_tunable_set = 0;
5306 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5307 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5308 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5310 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5311 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5313 /* Convert seconds to clock ticks */
5314 arc_min_prefetch_lifespan = 1 * hz;
5316 /* Start out with 1/8 of all memory */
5317 arc_c = kmem_size() / 8;
5322 * On architectures where the physical memory can be larger
5323 * than the addressable space (intel in 32-bit mode), we may
5324 * need to limit the cache to 1/8 of VM size.
5326 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5328 #endif /* illumos */
5329 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5330 arc_c_min = MAX(arc_c / 4, 16 << 20);
5331 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5332 if (arc_c * 8 >= 1 << 30)
5333 arc_c_max = (arc_c * 8) - (1 << 30);
5335 arc_c_max = arc_c_min;
5336 arc_c_max = MAX(arc_c * 5, arc_c_max);
5339 * In userland, there's only the memory pressure that we artificially
5340 * create (see arc_available_memory()). Don't let arc_c get too
5341 * small, because it can cause transactions to be larger than
5342 * arc_c, causing arc_tempreserve_space() to fail.
5345 arc_c_min = arc_c_max / 2;
5350 * Allow the tunables to override our calculations if they are
5351 * reasonable (ie. over 16MB)
5353 if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5354 arc_c_max = zfs_arc_max;
5355 if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5356 arc_c_min = zfs_arc_min;
5360 arc_p = (arc_c >> 1);
5362 /* limit meta-data to 1/4 of the arc capacity */
5363 arc_meta_limit = arc_c_max / 4;
5365 /* Allow the tunable to override if it is reasonable */
5366 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5367 arc_meta_limit = zfs_arc_meta_limit;
5369 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5370 arc_c_min = arc_meta_limit / 2;
5372 if (zfs_arc_meta_min > 0) {
5373 arc_meta_min = zfs_arc_meta_min;
5375 arc_meta_min = arc_c_min / 2;
5378 if (zfs_arc_grow_retry > 0)
5379 arc_grow_retry = zfs_arc_grow_retry;
5381 if (zfs_arc_shrink_shift > 0)
5382 arc_shrink_shift = zfs_arc_shrink_shift;
5385 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5387 if (arc_no_grow_shift >= arc_shrink_shift)
5388 arc_no_grow_shift = arc_shrink_shift - 1;
5390 if (zfs_arc_p_min_shift > 0)
5391 arc_p_min_shift = zfs_arc_p_min_shift;
5393 if (zfs_arc_num_sublists_per_state < 1)
5394 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5396 /* if kmem_flags are set, lets try to use less memory */
5397 if (kmem_debugging())
5399 if (arc_c < arc_c_min)
5402 zfs_arc_min = arc_c_min;
5403 zfs_arc_max = arc_c_max;
5405 arc_anon = &ARC_anon;
5407 arc_mru_ghost = &ARC_mru_ghost;
5409 arc_mfu_ghost = &ARC_mfu_ghost;
5410 arc_l2c_only = &ARC_l2c_only;
5413 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5414 sizeof (arc_buf_hdr_t),
5415 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5416 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5417 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5418 sizeof (arc_buf_hdr_t),
5419 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5420 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5421 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5422 sizeof (arc_buf_hdr_t),
5423 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5424 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5425 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5426 sizeof (arc_buf_hdr_t),
5427 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5428 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5429 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5430 sizeof (arc_buf_hdr_t),
5431 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5432 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5433 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5434 sizeof (arc_buf_hdr_t),
5435 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5436 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5437 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5438 sizeof (arc_buf_hdr_t),
5439 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5440 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5441 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5442 sizeof (arc_buf_hdr_t),
5443 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5444 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5445 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5446 sizeof (arc_buf_hdr_t),
5447 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5448 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5449 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5450 sizeof (arc_buf_hdr_t),
5451 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5452 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5454 refcount_create(&arc_anon->arcs_size);
5455 refcount_create(&arc_mru->arcs_size);
5456 refcount_create(&arc_mru_ghost->arcs_size);
5457 refcount_create(&arc_mfu->arcs_size);
5458 refcount_create(&arc_mfu_ghost->arcs_size);
5459 refcount_create(&arc_l2c_only->arcs_size);
5463 arc_reclaim_thread_exit = FALSE;
5464 arc_user_evicts_thread_exit = FALSE;
5465 arc_eviction_list = NULL;
5466 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5468 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5469 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5471 if (arc_ksp != NULL) {
5472 arc_ksp->ks_data = &arc_stats;
5473 arc_ksp->ks_update = arc_kstat_update;
5474 kstat_install(arc_ksp);
5477 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5478 TS_RUN, minclsyspri);
5481 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5482 EVENTHANDLER_PRI_FIRST);
5485 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5486 TS_RUN, minclsyspri);
5492 * Calculate maximum amount of dirty data per pool.
5494 * If it has been set by /etc/system, take that.
5495 * Otherwise, use a percentage of physical memory defined by
5496 * zfs_dirty_data_max_percent (default 10%) with a cap at
5497 * zfs_dirty_data_max_max (default 4GB).
5499 if (zfs_dirty_data_max == 0) {
5500 zfs_dirty_data_max = ptob(physmem) *
5501 zfs_dirty_data_max_percent / 100;
5502 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5503 zfs_dirty_data_max_max);
5507 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5508 prefetch_tunable_set = 1;
5511 if (prefetch_tunable_set == 0) {
5512 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5514 printf(" add \"vfs.zfs.prefetch_disable=0\" "
5515 "to /boot/loader.conf.\n");
5516 zfs_prefetch_disable = 1;
5519 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5520 prefetch_tunable_set == 0) {
5521 printf("ZFS NOTICE: Prefetch is disabled by default if less "
5522 "than 4GB of RAM is present;\n"
5523 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
5524 "to /boot/loader.conf.\n");
5525 zfs_prefetch_disable = 1;
5528 /* Warn about ZFS memory and address space requirements. */
5529 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5530 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5531 "expect unstable behavior.\n");
5533 if (kmem_size() < 512 * (1 << 20)) {
5534 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5535 "expect unstable behavior.\n");
5536 printf(" Consider tuning vm.kmem_size and "
5537 "vm.kmem_size_max\n");
5538 printf(" in /boot/loader.conf.\n");
5546 mutex_enter(&arc_reclaim_lock);
5547 arc_reclaim_thread_exit = TRUE;
5549 * The reclaim thread will set arc_reclaim_thread_exit back to
5550 * FALSE when it is finished exiting; we're waiting for that.
5552 while (arc_reclaim_thread_exit) {
5553 cv_signal(&arc_reclaim_thread_cv);
5554 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5556 mutex_exit(&arc_reclaim_lock);
5558 mutex_enter(&arc_user_evicts_lock);
5559 arc_user_evicts_thread_exit = TRUE;
5561 * The user evicts thread will set arc_user_evicts_thread_exit
5562 * to FALSE when it is finished exiting; we're waiting for that.
5564 while (arc_user_evicts_thread_exit) {
5565 cv_signal(&arc_user_evicts_cv);
5566 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5568 mutex_exit(&arc_user_evicts_lock);
5570 /* Use TRUE to ensure *all* buffers are evicted */
5571 arc_flush(NULL, TRUE);
5575 if (arc_ksp != NULL) {
5576 kstat_delete(arc_ksp);
5580 mutex_destroy(&arc_reclaim_lock);
5581 cv_destroy(&arc_reclaim_thread_cv);
5582 cv_destroy(&arc_reclaim_waiters_cv);
5584 mutex_destroy(&arc_user_evicts_lock);
5585 cv_destroy(&arc_user_evicts_cv);
5587 refcount_destroy(&arc_anon->arcs_size);
5588 refcount_destroy(&arc_mru->arcs_size);
5589 refcount_destroy(&arc_mru_ghost->arcs_size);
5590 refcount_destroy(&arc_mfu->arcs_size);
5591 refcount_destroy(&arc_mfu_ghost->arcs_size);
5592 refcount_destroy(&arc_l2c_only->arcs_size);
5594 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5595 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5596 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5597 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5598 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
5599 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5600 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5601 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5602 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5603 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
5607 ASSERT0(arc_loaned_bytes);
5610 if (arc_event_lowmem != NULL)
5611 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5618 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5619 * It uses dedicated storage devices to hold cached data, which are populated
5620 * using large infrequent writes. The main role of this cache is to boost
5621 * the performance of random read workloads. The intended L2ARC devices
5622 * include short-stroked disks, solid state disks, and other media with
5623 * substantially faster read latency than disk.
5625 * +-----------------------+
5627 * +-----------------------+
5630 * l2arc_feed_thread() arc_read()
5634 * +---------------+ |
5636 * +---------------+ |
5641 * +-------+ +-------+
5643 * | cache | | cache |
5644 * +-------+ +-------+
5645 * +=========+ .-----.
5646 * : L2ARC : |-_____-|
5647 * : devices : | Disks |
5648 * +=========+ `-_____-'
5650 * Read requests are satisfied from the following sources, in order:
5653 * 2) vdev cache of L2ARC devices
5655 * 4) vdev cache of disks
5658 * Some L2ARC device types exhibit extremely slow write performance.
5659 * To accommodate for this there are some significant differences between
5660 * the L2ARC and traditional cache design:
5662 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5663 * the ARC behave as usual, freeing buffers and placing headers on ghost
5664 * lists. The ARC does not send buffers to the L2ARC during eviction as
5665 * this would add inflated write latencies for all ARC memory pressure.
5667 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5668 * It does this by periodically scanning buffers from the eviction-end of
5669 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5670 * not already there. It scans until a headroom of buffers is satisfied,
5671 * which itself is a buffer for ARC eviction. If a compressible buffer is
5672 * found during scanning and selected for writing to an L2ARC device, we
5673 * temporarily boost scanning headroom during the next scan cycle to make
5674 * sure we adapt to compression effects (which might significantly reduce
5675 * the data volume we write to L2ARC). The thread that does this is
5676 * l2arc_feed_thread(), illustrated below; example sizes are included to
5677 * provide a better sense of ratio than this diagram:
5680 * +---------------------+----------+
5681 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5682 * +---------------------+----------+ | o L2ARC eligible
5683 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5684 * +---------------------+----------+ |
5685 * 15.9 Gbytes ^ 32 Mbytes |
5687 * l2arc_feed_thread()
5689 * l2arc write hand <--[oooo]--'
5693 * +==============================+
5694 * L2ARC dev |####|#|###|###| |####| ... |
5695 * +==============================+
5698 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5699 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5700 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5701 * safe to say that this is an uncommon case, since buffers at the end of
5702 * the ARC lists have moved there due to inactivity.
5704 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5705 * then the L2ARC simply misses copying some buffers. This serves as a
5706 * pressure valve to prevent heavy read workloads from both stalling the ARC
5707 * with waits and clogging the L2ARC with writes. This also helps prevent
5708 * the potential for the L2ARC to churn if it attempts to cache content too
5709 * quickly, such as during backups of the entire pool.
5711 * 5. After system boot and before the ARC has filled main memory, there are
5712 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5713 * lists can remain mostly static. Instead of searching from tail of these
5714 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5715 * for eligible buffers, greatly increasing its chance of finding them.
5717 * The L2ARC device write speed is also boosted during this time so that
5718 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5719 * there are no L2ARC reads, and no fear of degrading read performance
5720 * through increased writes.
5722 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5723 * the vdev queue can aggregate them into larger and fewer writes. Each
5724 * device is written to in a rotor fashion, sweeping writes through
5725 * available space then repeating.
5727 * 7. The L2ARC does not store dirty content. It never needs to flush
5728 * write buffers back to disk based storage.
5730 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5731 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5733 * The performance of the L2ARC can be tweaked by a number of tunables, which
5734 * may be necessary for different workloads:
5736 * l2arc_write_max max write bytes per interval
5737 * l2arc_write_boost extra write bytes during device warmup
5738 * l2arc_noprefetch skip caching prefetched buffers
5739 * l2arc_headroom number of max device writes to precache
5740 * l2arc_headroom_boost when we find compressed buffers during ARC
5741 * scanning, we multiply headroom by this
5742 * percentage factor for the next scan cycle,
5743 * since more compressed buffers are likely to
5745 * l2arc_feed_secs seconds between L2ARC writing
5747 * Tunables may be removed or added as future performance improvements are
5748 * integrated, and also may become zpool properties.
5750 * There are three key functions that control how the L2ARC warms up:
5752 * l2arc_write_eligible() check if a buffer is eligible to cache
5753 * l2arc_write_size() calculate how much to write
5754 * l2arc_write_interval() calculate sleep delay between writes
5756 * These three functions determine what to write, how much, and how quickly
5761 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5764 * A buffer is *not* eligible for the L2ARC if it:
5765 * 1. belongs to a different spa.
5766 * 2. is already cached on the L2ARC.
5767 * 3. has an I/O in progress (it may be an incomplete read).
5768 * 4. is flagged not eligible (zfs property).
5770 if (hdr->b_spa != spa_guid) {
5771 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5774 if (HDR_HAS_L2HDR(hdr)) {
5775 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5778 if (HDR_IO_IN_PROGRESS(hdr)) {
5779 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5782 if (!HDR_L2CACHE(hdr)) {
5783 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5791 l2arc_write_size(void)
5796 * Make sure our globals have meaningful values in case the user
5799 size = l2arc_write_max;
5801 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5802 "be greater than zero, resetting it to the default (%d)",
5804 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5807 if (arc_warm == B_FALSE)
5808 size += l2arc_write_boost;
5815 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5817 clock_t interval, next, now;
5820 * If the ARC lists are busy, increase our write rate; if the
5821 * lists are stale, idle back. This is achieved by checking
5822 * how much we previously wrote - if it was more than half of
5823 * what we wanted, schedule the next write much sooner.
5825 if (l2arc_feed_again && wrote > (wanted / 2))
5826 interval = (hz * l2arc_feed_min_ms) / 1000;
5828 interval = hz * l2arc_feed_secs;
5830 now = ddi_get_lbolt();
5831 next = MAX(now, MIN(now + interval, began + interval));
5837 * Cycle through L2ARC devices. This is how L2ARC load balances.
5838 * If a device is returned, this also returns holding the spa config lock.
5840 static l2arc_dev_t *
5841 l2arc_dev_get_next(void)
5843 l2arc_dev_t *first, *next = NULL;
5846 * Lock out the removal of spas (spa_namespace_lock), then removal
5847 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5848 * both locks will be dropped and a spa config lock held instead.
5850 mutex_enter(&spa_namespace_lock);
5851 mutex_enter(&l2arc_dev_mtx);
5853 /* if there are no vdevs, there is nothing to do */
5854 if (l2arc_ndev == 0)
5858 next = l2arc_dev_last;
5860 /* loop around the list looking for a non-faulted vdev */
5862 next = list_head(l2arc_dev_list);
5864 next = list_next(l2arc_dev_list, next);
5866 next = list_head(l2arc_dev_list);
5869 /* if we have come back to the start, bail out */
5872 else if (next == first)
5875 } while (vdev_is_dead(next->l2ad_vdev));
5877 /* if we were unable to find any usable vdevs, return NULL */
5878 if (vdev_is_dead(next->l2ad_vdev))
5881 l2arc_dev_last = next;
5884 mutex_exit(&l2arc_dev_mtx);
5887 * Grab the config lock to prevent the 'next' device from being
5888 * removed while we are writing to it.
5891 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5892 mutex_exit(&spa_namespace_lock);
5898 * Free buffers that were tagged for destruction.
5901 l2arc_do_free_on_write()
5904 l2arc_data_free_t *df, *df_prev;
5906 mutex_enter(&l2arc_free_on_write_mtx);
5907 buflist = l2arc_free_on_write;
5909 for (df = list_tail(buflist); df; df = df_prev) {
5910 df_prev = list_prev(buflist, df);
5911 ASSERT(df->l2df_data != NULL);
5912 ASSERT(df->l2df_func != NULL);
5913 df->l2df_func(df->l2df_data, df->l2df_size);
5914 list_remove(buflist, df);
5915 kmem_free(df, sizeof (l2arc_data_free_t));
5918 mutex_exit(&l2arc_free_on_write_mtx);
5922 * A write to a cache device has completed. Update all headers to allow
5923 * reads from these buffers to begin.
5926 l2arc_write_done(zio_t *zio)
5928 l2arc_write_callback_t *cb;
5931 arc_buf_hdr_t *head, *hdr, *hdr_prev;
5932 kmutex_t *hash_lock;
5933 int64_t bytes_dropped = 0;
5935 cb = zio->io_private;
5937 dev = cb->l2wcb_dev;
5938 ASSERT(dev != NULL);
5939 head = cb->l2wcb_head;
5940 ASSERT(head != NULL);
5941 buflist = &dev->l2ad_buflist;
5942 ASSERT(buflist != NULL);
5943 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5944 l2arc_write_callback_t *, cb);
5946 if (zio->io_error != 0)
5947 ARCSTAT_BUMP(arcstat_l2_writes_error);
5950 * All writes completed, or an error was hit.
5953 mutex_enter(&dev->l2ad_mtx);
5954 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5955 hdr_prev = list_prev(buflist, hdr);
5957 hash_lock = HDR_LOCK(hdr);
5960 * We cannot use mutex_enter or else we can deadlock
5961 * with l2arc_write_buffers (due to swapping the order
5962 * the hash lock and l2ad_mtx are taken).
5964 if (!mutex_tryenter(hash_lock)) {
5966 * Missed the hash lock. We must retry so we
5967 * don't leave the ARC_FLAG_L2_WRITING bit set.
5969 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5972 * We don't want to rescan the headers we've
5973 * already marked as having been written out, so
5974 * we reinsert the head node so we can pick up
5975 * where we left off.
5977 list_remove(buflist, head);
5978 list_insert_after(buflist, hdr, head);
5980 mutex_exit(&dev->l2ad_mtx);
5983 * We wait for the hash lock to become available
5984 * to try and prevent busy waiting, and increase
5985 * the chance we'll be able to acquire the lock
5986 * the next time around.
5988 mutex_enter(hash_lock);
5989 mutex_exit(hash_lock);
5994 * We could not have been moved into the arc_l2c_only
5995 * state while in-flight due to our ARC_FLAG_L2_WRITING
5996 * bit being set. Let's just ensure that's being enforced.
5998 ASSERT(HDR_HAS_L1HDR(hdr));
6001 * We may have allocated a buffer for L2ARC compression,
6002 * we must release it to avoid leaking this data.
6004 l2arc_release_cdata_buf(hdr);
6006 if (zio->io_error != 0) {
6008 * Error - drop L2ARC entry.
6010 list_remove(buflist, hdr);
6012 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
6014 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
6015 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
6017 bytes_dropped += hdr->b_l2hdr.b_asize;
6018 (void) refcount_remove_many(&dev->l2ad_alloc,
6019 hdr->b_l2hdr.b_asize, hdr);
6023 * Allow ARC to begin reads and ghost list evictions to
6026 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
6028 mutex_exit(hash_lock);
6031 atomic_inc_64(&l2arc_writes_done);
6032 list_remove(buflist, head);
6033 ASSERT(!HDR_HAS_L1HDR(head));
6034 kmem_cache_free(hdr_l2only_cache, head);
6035 mutex_exit(&dev->l2ad_mtx);
6037 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6039 l2arc_do_free_on_write();
6041 kmem_free(cb, sizeof (l2arc_write_callback_t));
6045 * A read to a cache device completed. Validate buffer contents before
6046 * handing over to the regular ARC routines.
6049 l2arc_read_done(zio_t *zio)
6051 l2arc_read_callback_t *cb;
6054 kmutex_t *hash_lock;
6057 ASSERT(zio->io_vd != NULL);
6058 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6060 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6062 cb = zio->io_private;
6064 buf = cb->l2rcb_buf;
6065 ASSERT(buf != NULL);
6067 hash_lock = HDR_LOCK(buf->b_hdr);
6068 mutex_enter(hash_lock);
6070 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6073 * If the data was read into a temporary buffer,
6074 * move it and free the buffer.
6076 if (cb->l2rcb_data != NULL) {
6077 ASSERT3U(hdr->b_size, <, zio->io_size);
6078 ASSERT3U(cb->l2rcb_compress, ==, ZIO_COMPRESS_OFF);
6079 if (zio->io_error == 0)
6080 bcopy(cb->l2rcb_data, buf->b_data, hdr->b_size);
6083 * The following must be done regardless of whether
6084 * there was an error:
6085 * - free the temporary buffer
6086 * - point zio to the real ARC buffer
6087 * - set zio size accordingly
6088 * These are required because zio is either re-used for
6089 * an I/O of the block in the case of the error
6090 * or the zio is passed to arc_read_done() and it
6093 zio_data_buf_free(cb->l2rcb_data, zio->io_size);
6094 zio->io_size = zio->io_orig_size = hdr->b_size;
6095 zio->io_data = zio->io_orig_data = buf->b_data;
6099 * If the buffer was compressed, decompress it first.
6101 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
6102 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6103 ASSERT(zio->io_data != NULL);
6104 ASSERT3U(zio->io_size, ==, hdr->b_size);
6105 ASSERT3U(BP_GET_LSIZE(&cb->l2rcb_bp), ==, hdr->b_size);
6108 * Check this survived the L2ARC journey.
6110 equal = arc_cksum_equal(buf);
6111 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6112 mutex_exit(hash_lock);
6113 zio->io_private = buf;
6114 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6115 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6118 mutex_exit(hash_lock);
6120 * Buffer didn't survive caching. Increment stats and
6121 * reissue to the original storage device.
6123 if (zio->io_error != 0) {
6124 ARCSTAT_BUMP(arcstat_l2_io_error);
6126 zio->io_error = SET_ERROR(EIO);
6129 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6132 * If there's no waiter, issue an async i/o to the primary
6133 * storage now. If there *is* a waiter, the caller must
6134 * issue the i/o in a context where it's OK to block.
6136 if (zio->io_waiter == NULL) {
6137 zio_t *pio = zio_unique_parent(zio);
6139 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6141 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6142 buf->b_data, hdr->b_size, arc_read_done, buf,
6143 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6147 kmem_free(cb, sizeof (l2arc_read_callback_t));
6151 * This is the list priority from which the L2ARC will search for pages to
6152 * cache. This is used within loops (0..3) to cycle through lists in the
6153 * desired order. This order can have a significant effect on cache
6156 * Currently the metadata lists are hit first, MFU then MRU, followed by
6157 * the data lists. This function returns a locked list, and also returns
6160 static multilist_sublist_t *
6161 l2arc_sublist_lock(int list_num)
6163 multilist_t *ml = NULL;
6166 ASSERT(list_num >= 0 && list_num <= 3);
6170 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6173 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6176 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6179 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6184 * Return a randomly-selected sublist. This is acceptable
6185 * because the caller feeds only a little bit of data for each
6186 * call (8MB). Subsequent calls will result in different
6187 * sublists being selected.
6189 idx = multilist_get_random_index(ml);
6190 return (multilist_sublist_lock(ml, idx));
6194 * Evict buffers from the device write hand to the distance specified in
6195 * bytes. This distance may span populated buffers, it may span nothing.
6196 * This is clearing a region on the L2ARC device ready for writing.
6197 * If the 'all' boolean is set, every buffer is evicted.
6200 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6203 arc_buf_hdr_t *hdr, *hdr_prev;
6204 kmutex_t *hash_lock;
6207 buflist = &dev->l2ad_buflist;
6209 if (!all && dev->l2ad_first) {
6211 * This is the first sweep through the device. There is
6217 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6219 * When nearing the end of the device, evict to the end
6220 * before the device write hand jumps to the start.
6222 taddr = dev->l2ad_end;
6224 taddr = dev->l2ad_hand + distance;
6226 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6227 uint64_t, taddr, boolean_t, all);
6230 mutex_enter(&dev->l2ad_mtx);
6231 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6232 hdr_prev = list_prev(buflist, hdr);
6234 hash_lock = HDR_LOCK(hdr);
6237 * We cannot use mutex_enter or else we can deadlock
6238 * with l2arc_write_buffers (due to swapping the order
6239 * the hash lock and l2ad_mtx are taken).
6241 if (!mutex_tryenter(hash_lock)) {
6243 * Missed the hash lock. Retry.
6245 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6246 mutex_exit(&dev->l2ad_mtx);
6247 mutex_enter(hash_lock);
6248 mutex_exit(hash_lock);
6252 if (HDR_L2_WRITE_HEAD(hdr)) {
6254 * We hit a write head node. Leave it for
6255 * l2arc_write_done().
6257 list_remove(buflist, hdr);
6258 mutex_exit(hash_lock);
6262 if (!all && HDR_HAS_L2HDR(hdr) &&
6263 (hdr->b_l2hdr.b_daddr > taddr ||
6264 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6266 * We've evicted to the target address,
6267 * or the end of the device.
6269 mutex_exit(hash_lock);
6273 ASSERT(HDR_HAS_L2HDR(hdr));
6274 if (!HDR_HAS_L1HDR(hdr)) {
6275 ASSERT(!HDR_L2_READING(hdr));
6277 * This doesn't exist in the ARC. Destroy.
6278 * arc_hdr_destroy() will call list_remove()
6279 * and decrement arcstat_l2_size.
6281 arc_change_state(arc_anon, hdr, hash_lock);
6282 arc_hdr_destroy(hdr);
6284 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6285 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6287 * Invalidate issued or about to be issued
6288 * reads, since we may be about to write
6289 * over this location.
6291 if (HDR_L2_READING(hdr)) {
6292 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6293 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6296 /* Ensure this header has finished being written */
6297 ASSERT(!HDR_L2_WRITING(hdr));
6298 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6300 arc_hdr_l2hdr_destroy(hdr);
6302 mutex_exit(hash_lock);
6304 mutex_exit(&dev->l2ad_mtx);
6308 * Find and write ARC buffers to the L2ARC device.
6310 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6311 * for reading until they have completed writing.
6312 * The headroom_boost is an in-out parameter used to maintain headroom boost
6313 * state between calls to this function.
6315 * Returns the number of bytes actually written (which may be smaller than
6316 * the delta by which the device hand has changed due to alignment).
6319 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6320 boolean_t *headroom_boost)
6322 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6323 uint64_t write_asize, write_sz, headroom,
6327 l2arc_write_callback_t *cb;
6329 uint64_t guid = spa_load_guid(spa);
6330 const boolean_t do_headroom_boost = *headroom_boost;
6333 ASSERT(dev->l2ad_vdev != NULL);
6335 /* Lower the flag now, we might want to raise it again later. */
6336 *headroom_boost = B_FALSE;
6339 write_sz = write_asize = 0;
6341 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6342 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6343 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6345 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6347 * We will want to try to compress buffers that are at least 2x the
6348 * device sector size.
6350 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6353 * Copy buffers for L2ARC writing.
6355 for (try = 0; try <= 3; try++) {
6356 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6357 uint64_t passed_sz = 0;
6359 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6362 * L2ARC fast warmup.
6364 * Until the ARC is warm and starts to evict, read from the
6365 * head of the ARC lists rather than the tail.
6367 if (arc_warm == B_FALSE)
6368 hdr = multilist_sublist_head(mls);
6370 hdr = multilist_sublist_tail(mls);
6372 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6374 headroom = target_sz * l2arc_headroom;
6375 if (do_headroom_boost)
6376 headroom = (headroom * l2arc_headroom_boost) / 100;
6378 for (; hdr; hdr = hdr_prev) {
6379 kmutex_t *hash_lock;
6384 if (arc_warm == B_FALSE)
6385 hdr_prev = multilist_sublist_next(mls, hdr);
6387 hdr_prev = multilist_sublist_prev(mls, hdr);
6388 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6390 hash_lock = HDR_LOCK(hdr);
6391 if (!mutex_tryenter(hash_lock)) {
6392 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6394 * Skip this buffer rather than waiting.
6399 passed_sz += hdr->b_size;
6400 if (passed_sz > headroom) {
6404 mutex_exit(hash_lock);
6405 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6409 if (!l2arc_write_eligible(guid, hdr)) {
6410 mutex_exit(hash_lock);
6415 * Assume that the buffer is not going to be compressed
6416 * and could take more space on disk because of a larger
6419 buf_sz = hdr->b_size;
6420 align = (size_t)1 << dev->l2ad_vdev->vdev_ashift;
6421 buf_a_sz = P2ROUNDUP(buf_sz, align);
6423 if ((write_asize + buf_a_sz) > target_sz) {
6425 mutex_exit(hash_lock);
6426 ARCSTAT_BUMP(arcstat_l2_write_full);
6432 * Insert a dummy header on the buflist so
6433 * l2arc_write_done() can find where the
6434 * write buffers begin without searching.
6436 mutex_enter(&dev->l2ad_mtx);
6437 list_insert_head(&dev->l2ad_buflist, head);
6438 mutex_exit(&dev->l2ad_mtx);
6441 sizeof (l2arc_write_callback_t), KM_SLEEP);
6442 cb->l2wcb_dev = dev;
6443 cb->l2wcb_head = head;
6444 pio = zio_root(spa, l2arc_write_done, cb,
6446 ARCSTAT_BUMP(arcstat_l2_write_pios);
6450 * Create and add a new L2ARC header.
6452 hdr->b_l2hdr.b_dev = dev;
6453 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6455 * Temporarily stash the data buffer in b_tmp_cdata.
6456 * The subsequent write step will pick it up from
6457 * there. This is because can't access b_l1hdr.b_buf
6458 * without holding the hash_lock, which we in turn
6459 * can't access without holding the ARC list locks
6460 * (which we want to avoid during compression/writing).
6462 hdr->b_l2hdr.b_compress = ZIO_COMPRESS_OFF;
6463 hdr->b_l2hdr.b_asize = hdr->b_size;
6464 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6467 * Explicitly set the b_daddr field to a known
6468 * value which means "invalid address". This
6469 * enables us to differentiate which stage of
6470 * l2arc_write_buffers() the particular header
6471 * is in (e.g. this loop, or the one below).
6472 * ARC_FLAG_L2_WRITING is not enough to make
6473 * this distinction, and we need to know in
6474 * order to do proper l2arc vdev accounting in
6475 * arc_release() and arc_hdr_destroy().
6477 * Note, we can't use a new flag to distinguish
6478 * the two stages because we don't hold the
6479 * header's hash_lock below, in the second stage
6480 * of this function. Thus, we can't simply
6481 * change the b_flags field to denote that the
6482 * IO has been sent. We can change the b_daddr
6483 * field of the L2 portion, though, since we'll
6484 * be holding the l2ad_mtx; which is why we're
6485 * using it to denote the header's state change.
6487 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6489 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6491 mutex_enter(&dev->l2ad_mtx);
6492 list_insert_head(&dev->l2ad_buflist, hdr);
6493 mutex_exit(&dev->l2ad_mtx);
6496 * Compute and store the buffer cksum before
6497 * writing. On debug the cksum is verified first.
6499 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6500 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6502 mutex_exit(hash_lock);
6505 write_asize += buf_a_sz;
6508 multilist_sublist_unlock(mls);
6514 /* No buffers selected for writing? */
6517 ASSERT(!HDR_HAS_L1HDR(head));
6518 kmem_cache_free(hdr_l2only_cache, head);
6522 mutex_enter(&dev->l2ad_mtx);
6525 * Now start writing the buffers. We're starting at the write head
6526 * and work backwards, retracing the course of the buffer selector
6530 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6531 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6536 * We rely on the L1 portion of the header below, so
6537 * it's invalid for this header to have been evicted out
6538 * of the ghost cache, prior to being written out. The
6539 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6541 ASSERT(HDR_HAS_L1HDR(hdr));
6544 * We shouldn't need to lock the buffer here, since we flagged
6545 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6546 * take care to only access its L2 cache parameters. In
6547 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6550 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6553 * Save a pointer to the original buffer data we had previously
6556 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6558 compress = HDR_L2COMPRESS(hdr) &&
6559 hdr->b_l2hdr.b_asize >= buf_compress_minsz;
6560 if (l2arc_transform_buf(hdr, compress)) {
6562 * If compression succeeded, enable headroom
6563 * boost on the next scan cycle.
6565 *headroom_boost = B_TRUE;
6569 * Get the new buffer size that accounts for compression
6572 buf_sz = hdr->b_l2hdr.b_asize;
6575 * We need to do this regardless if buf_sz is zero or
6576 * not, otherwise, when this l2hdr is evicted we'll
6577 * remove a reference that was never added.
6579 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6581 /* Compression may have squashed the buffer to zero length. */
6584 * If the data was padded or compressed, then it
6585 * it is in a new buffer.
6587 if (hdr->b_l1hdr.b_tmp_cdata != NULL)
6588 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6589 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6590 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6591 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6592 ZIO_FLAG_CANFAIL, B_FALSE);
6594 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6596 (void) zio_nowait(wzio);
6598 write_asize += buf_sz;
6599 dev->l2ad_hand += buf_sz;
6603 mutex_exit(&dev->l2ad_mtx);
6605 ASSERT3U(write_asize, <=, target_sz);
6606 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6607 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6608 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6609 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6610 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6613 * Bump device hand to the device start if it is approaching the end.
6614 * l2arc_evict() will already have evicted ahead for this case.
6616 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6617 dev->l2ad_hand = dev->l2ad_start;
6618 dev->l2ad_first = B_FALSE;
6621 dev->l2ad_writing = B_TRUE;
6622 (void) zio_wait(pio);
6623 dev->l2ad_writing = B_FALSE;
6625 return (write_asize);
6629 * Transforms, possibly compresses and pads, an L2ARC buffer.
6630 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6631 * size in l2hdr->b_asize. This routine tries to compress the data and
6632 * depending on the compression result there are three possible outcomes:
6633 * *) The buffer was incompressible. The buffer size was already ashift aligned.
6634 * The original hdr contents were left untouched except for b_tmp_cdata,
6635 * which is reset to NULL. The caller must keep a pointer to the original
6637 * *) The buffer was incompressible. The buffer size was not ashift aligned.
6638 * b_tmp_cdata was replaced with a temporary data buffer which holds a padded
6639 * (aligned) copy of the data. Once writing is done, invoke
6640 * l2arc_release_cdata_buf on this hdr to free the temporary buffer.
6641 * *) The buffer was all-zeros, so there is no need to write it to an L2
6642 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6643 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6644 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6645 * data buffer which holds the compressed data to be written, and b_asize
6646 * tells us how much data there is. b_compress is set to the appropriate
6647 * compression algorithm. Once writing is done, invoke
6648 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6650 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6651 * buffer was incompressible).
6654 l2arc_transform_buf(arc_buf_hdr_t *hdr, boolean_t compress)
6657 size_t align, asize, csize, len, rounded;
6659 ASSERT(HDR_HAS_L2HDR(hdr));
6660 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6662 ASSERT(HDR_HAS_L1HDR(hdr));
6663 ASSERT3S(l2hdr->b_compress, ==, ZIO_COMPRESS_OFF);
6664 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6666 len = l2hdr->b_asize;
6667 align = (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift;
6668 asize = P2ROUNDUP(len, align);
6669 cdata = zio_data_buf_alloc(asize);
6670 ASSERT3P(cdata, !=, NULL);
6672 csize = zio_compress_data(ZIO_COMPRESS_LZ4,
6673 hdr->b_l1hdr.b_tmp_cdata, cdata, len);
6678 /* zero block, indicate that there's nothing to write */
6679 zio_data_buf_free(cdata, asize);
6680 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
6682 hdr->b_l1hdr.b_tmp_cdata = NULL;
6683 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6687 rounded = P2ROUNDUP(csize, align);
6688 ASSERT3U(rounded, <=, asize);
6689 if (rounded < len) {
6691 * Compression succeeded, we'll keep the cdata around for
6692 * writing and release it afterwards.
6694 if (rounded > csize) {
6695 bzero((char *)cdata + csize, rounded - csize);
6698 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
6699 l2hdr->b_asize = csize;
6700 hdr->b_l1hdr.b_tmp_cdata = cdata;
6701 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6705 * Compression did not save space.
6707 if (P2PHASE(len, align) != 0) {
6709 * Use compression buffer for a copy of data padded to
6710 * the proper size. Compression algorithm remains set
6711 * to ZIO_COMPRESS_OFF.
6713 ASSERT3U(len, <, asize);
6714 bcopy(hdr->b_l1hdr.b_tmp_cdata, cdata, len);
6715 bzero((char *)cdata + len, asize - len);
6716 l2hdr->b_asize = asize;
6717 hdr->b_l1hdr.b_tmp_cdata = cdata;
6718 ARCSTAT_BUMP(arcstat_l2_padding_needed);
6720 ASSERT3U(len, ==, asize);
6722 * The original buffer is good as is,
6723 * release the compressed buffer.
6724 * l2hdr will be left unmodified except for b_tmp_cdata.
6726 zio_data_buf_free(cdata, asize);
6727 hdr->b_l1hdr.b_tmp_cdata = NULL;
6730 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6736 * Decompresses a zio read back from an l2arc device. On success, the
6737 * underlying zio's io_data buffer is overwritten by the uncompressed
6738 * version. On decompression error (corrupt compressed stream), the
6739 * zio->io_error value is set to signal an I/O error.
6741 * Please note that the compressed data stream is not checksummed, so
6742 * if the underlying device is experiencing data corruption, we may feed
6743 * corrupt data to the decompressor, so the decompressor needs to be
6744 * able to handle this situation (LZ4 does).
6747 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6749 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6751 if (zio->io_error != 0) {
6753 * An io error has occured, just restore the original io
6754 * size in preparation for a main pool read.
6756 zio->io_orig_size = zio->io_size = hdr->b_size;
6760 if (c == ZIO_COMPRESS_EMPTY) {
6762 * An empty buffer results in a null zio, which means we
6763 * need to fill its io_data after we're done restoring the
6764 * buffer's contents.
6766 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6767 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6768 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6770 ASSERT(zio->io_data != NULL);
6772 * We copy the compressed data from the start of the arc buffer
6773 * (the zio_read will have pulled in only what we need, the
6774 * rest is garbage which we will overwrite at decompression)
6775 * and then decompress back to the ARC data buffer. This way we
6776 * can minimize copying by simply decompressing back over the
6777 * original compressed data (rather than decompressing to an
6778 * aux buffer and then copying back the uncompressed buffer,
6779 * which is likely to be much larger).
6784 csize = zio->io_size;
6785 cdata = zio_data_buf_alloc(csize);
6786 bcopy(zio->io_data, cdata, csize);
6787 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6789 zio->io_error = EIO;
6790 zio_data_buf_free(cdata, csize);
6793 /* Restore the expected uncompressed IO size. */
6794 zio->io_orig_size = zio->io_size = hdr->b_size;
6798 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6799 * This buffer serves as a temporary holder of compressed or padded data while
6800 * the buffer entry is being written to an l2arc device. Once that is
6801 * done, we can dispose of it.
6804 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6806 size_t align, asize, len;
6807 enum zio_compress comp = hdr->b_l2hdr.b_compress;
6809 ASSERT(HDR_HAS_L2HDR(hdr));
6810 ASSERT(HDR_HAS_L1HDR(hdr));
6811 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6813 if (hdr->b_l1hdr.b_tmp_cdata != NULL) {
6814 ASSERT(comp != ZIO_COMPRESS_EMPTY);
6816 align = (size_t)1 << hdr->b_l2hdr.b_dev->l2ad_vdev->vdev_ashift;
6817 asize = P2ROUNDUP(len, align);
6818 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata, asize);
6819 hdr->b_l1hdr.b_tmp_cdata = NULL;
6821 ASSERT(comp == ZIO_COMPRESS_OFF || comp == ZIO_COMPRESS_EMPTY);
6826 * This thread feeds the L2ARC at regular intervals. This is the beating
6827 * heart of the L2ARC.
6830 l2arc_feed_thread(void *dummy __unused)
6835 uint64_t size, wrote;
6836 clock_t begin, next = ddi_get_lbolt();
6837 boolean_t headroom_boost = B_FALSE;
6839 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6841 mutex_enter(&l2arc_feed_thr_lock);
6843 while (l2arc_thread_exit == 0) {
6844 CALLB_CPR_SAFE_BEGIN(&cpr);
6845 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6846 next - ddi_get_lbolt());
6847 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6848 next = ddi_get_lbolt() + hz;
6851 * Quick check for L2ARC devices.
6853 mutex_enter(&l2arc_dev_mtx);
6854 if (l2arc_ndev == 0) {
6855 mutex_exit(&l2arc_dev_mtx);
6858 mutex_exit(&l2arc_dev_mtx);
6859 begin = ddi_get_lbolt();
6862 * This selects the next l2arc device to write to, and in
6863 * doing so the next spa to feed from: dev->l2ad_spa. This
6864 * will return NULL if there are now no l2arc devices or if
6865 * they are all faulted.
6867 * If a device is returned, its spa's config lock is also
6868 * held to prevent device removal. l2arc_dev_get_next()
6869 * will grab and release l2arc_dev_mtx.
6871 if ((dev = l2arc_dev_get_next()) == NULL)
6874 spa = dev->l2ad_spa;
6875 ASSERT(spa != NULL);
6878 * If the pool is read-only then force the feed thread to
6879 * sleep a little longer.
6881 if (!spa_writeable(spa)) {
6882 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6883 spa_config_exit(spa, SCL_L2ARC, dev);
6888 * Avoid contributing to memory pressure.
6890 if (arc_reclaim_needed()) {
6891 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6892 spa_config_exit(spa, SCL_L2ARC, dev);
6896 ARCSTAT_BUMP(arcstat_l2_feeds);
6898 size = l2arc_write_size();
6901 * Evict L2ARC buffers that will be overwritten.
6903 l2arc_evict(dev, size, B_FALSE);
6906 * Write ARC buffers.
6908 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6911 * Calculate interval between writes.
6913 next = l2arc_write_interval(begin, size, wrote);
6914 spa_config_exit(spa, SCL_L2ARC, dev);
6917 l2arc_thread_exit = 0;
6918 cv_broadcast(&l2arc_feed_thr_cv);
6919 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6924 l2arc_vdev_present(vdev_t *vd)
6928 mutex_enter(&l2arc_dev_mtx);
6929 for (dev = list_head(l2arc_dev_list); dev != NULL;
6930 dev = list_next(l2arc_dev_list, dev)) {
6931 if (dev->l2ad_vdev == vd)
6934 mutex_exit(&l2arc_dev_mtx);
6936 return (dev != NULL);
6940 * Add a vdev for use by the L2ARC. By this point the spa has already
6941 * validated the vdev and opened it.
6944 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6946 l2arc_dev_t *adddev;
6948 ASSERT(!l2arc_vdev_present(vd));
6950 vdev_ashift_optimize(vd);
6953 * Create a new l2arc device entry.
6955 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6956 adddev->l2ad_spa = spa;
6957 adddev->l2ad_vdev = vd;
6958 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6959 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6960 adddev->l2ad_hand = adddev->l2ad_start;
6961 adddev->l2ad_first = B_TRUE;
6962 adddev->l2ad_writing = B_FALSE;
6964 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6966 * This is a list of all ARC buffers that are still valid on the
6969 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6970 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6972 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6973 refcount_create(&adddev->l2ad_alloc);
6976 * Add device to global list
6978 mutex_enter(&l2arc_dev_mtx);
6979 list_insert_head(l2arc_dev_list, adddev);
6980 atomic_inc_64(&l2arc_ndev);
6981 mutex_exit(&l2arc_dev_mtx);
6985 * Remove a vdev from the L2ARC.
6988 l2arc_remove_vdev(vdev_t *vd)
6990 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6993 * Find the device by vdev
6995 mutex_enter(&l2arc_dev_mtx);
6996 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6997 nextdev = list_next(l2arc_dev_list, dev);
6998 if (vd == dev->l2ad_vdev) {
7003 ASSERT(remdev != NULL);
7006 * Remove device from global list
7008 list_remove(l2arc_dev_list, remdev);
7009 l2arc_dev_last = NULL; /* may have been invalidated */
7010 atomic_dec_64(&l2arc_ndev);
7011 mutex_exit(&l2arc_dev_mtx);
7014 * Clear all buflists and ARC references. L2ARC device flush.
7016 l2arc_evict(remdev, 0, B_TRUE);
7017 list_destroy(&remdev->l2ad_buflist);
7018 mutex_destroy(&remdev->l2ad_mtx);
7019 refcount_destroy(&remdev->l2ad_alloc);
7020 kmem_free(remdev, sizeof (l2arc_dev_t));
7026 l2arc_thread_exit = 0;
7028 l2arc_writes_sent = 0;
7029 l2arc_writes_done = 0;
7031 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7032 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7033 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7034 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7036 l2arc_dev_list = &L2ARC_dev_list;
7037 l2arc_free_on_write = &L2ARC_free_on_write;
7038 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7039 offsetof(l2arc_dev_t, l2ad_node));
7040 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7041 offsetof(l2arc_data_free_t, l2df_list_node));
7048 * This is called from dmu_fini(), which is called from spa_fini();
7049 * Because of this, we can assume that all l2arc devices have
7050 * already been removed when the pools themselves were removed.
7053 l2arc_do_free_on_write();
7055 mutex_destroy(&l2arc_feed_thr_lock);
7056 cv_destroy(&l2arc_feed_thr_cv);
7057 mutex_destroy(&l2arc_dev_mtx);
7058 mutex_destroy(&l2arc_free_on_write_mtx);
7060 list_destroy(l2arc_dev_list);
7061 list_destroy(l2arc_free_on_write);
7067 if (!(spa_mode_global & FWRITE))
7070 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7071 TS_RUN, minclsyspri);
7077 if (!(spa_mode_global & FWRITE))
7080 mutex_enter(&l2arc_feed_thr_lock);
7081 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7082 l2arc_thread_exit = 1;
7083 while (l2arc_thread_exit != 0)
7084 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7085 mutex_exit(&l2arc_feed_thr_lock);