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>
136 #include <sys/callb.h>
137 #include <sys/kstat.h>
138 #include <sys/trim_map.h>
139 #include <zfs_fletcher.h>
142 #include <vm/vm_pageout.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_max", &zfs_arc_max);
251 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
252 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
253 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
254 TUNABLE_QUAD("vfs.zfs.arc_average_blocksize", &zfs_arc_average_blocksize);
255 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
256 SYSCTL_DECL(_vfs_zfs);
257 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
259 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
261 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
262 &zfs_arc_average_blocksize, 0,
263 "ARC average blocksize");
264 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
265 &arc_shrink_shift, 0,
266 "log2(fraction of arc to reclaim)");
269 * We don't have a tunable for arc_free_target due to the dependency on
270 * pagedaemon initialisation.
272 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
273 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
274 sysctl_vfs_zfs_arc_free_target, "IU",
275 "Desired number of free pages below which ARC triggers reclaim");
278 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
283 val = zfs_arc_free_target;
284 err = sysctl_handle_int(oidp, &val, 0, req);
285 if (err != 0 || req->newptr == NULL)
290 if (val > cnt.v_page_count)
293 zfs_arc_free_target = val;
299 * Must be declared here, before the definition of corresponding kstat
300 * macro which uses the same names will confuse the compiler.
302 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
303 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
304 sysctl_vfs_zfs_arc_meta_limit, "QU",
305 "ARC metadata limit");
309 * Note that buffers can be in one of 6 states:
310 * ARC_anon - anonymous (discussed below)
311 * ARC_mru - recently used, currently cached
312 * ARC_mru_ghost - recentely used, no longer in cache
313 * ARC_mfu - frequently used, currently cached
314 * ARC_mfu_ghost - frequently used, no longer in cache
315 * ARC_l2c_only - exists in L2ARC but not other states
316 * When there are no active references to the buffer, they are
317 * are linked onto a list in one of these arc states. These are
318 * the only buffers that can be evicted or deleted. Within each
319 * state there are multiple lists, one for meta-data and one for
320 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
321 * etc.) is tracked separately so that it can be managed more
322 * explicitly: favored over data, limited explicitly.
324 * Anonymous buffers are buffers that are not associated with
325 * a DVA. These are buffers that hold dirty block copies
326 * before they are written to stable storage. By definition,
327 * they are "ref'd" and are considered part of arc_mru
328 * that cannot be freed. Generally, they will aquire a DVA
329 * as they are written and migrate onto the arc_mru list.
331 * The ARC_l2c_only state is for buffers that are in the second
332 * level ARC but no longer in any of the ARC_m* lists. The second
333 * level ARC itself may also contain buffers that are in any of
334 * the ARC_m* states - meaning that a buffer can exist in two
335 * places. The reason for the ARC_l2c_only state is to keep the
336 * buffer header in the hash table, so that reads that hit the
337 * second level ARC benefit from these fast lookups.
340 typedef struct arc_state {
342 * list of evictable buffers
344 multilist_t arcs_list[ARC_BUFC_NUMTYPES];
346 * total amount of evictable data in this state
348 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];
350 * total amount of data in this state; this includes: evictable,
351 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
353 refcount_t arcs_size;
357 static arc_state_t ARC_anon;
358 static arc_state_t ARC_mru;
359 static arc_state_t ARC_mru_ghost;
360 static arc_state_t ARC_mfu;
361 static arc_state_t ARC_mfu_ghost;
362 static arc_state_t ARC_l2c_only;
364 typedef struct arc_stats {
365 kstat_named_t arcstat_hits;
366 kstat_named_t arcstat_misses;
367 kstat_named_t arcstat_demand_data_hits;
368 kstat_named_t arcstat_demand_data_misses;
369 kstat_named_t arcstat_demand_metadata_hits;
370 kstat_named_t arcstat_demand_metadata_misses;
371 kstat_named_t arcstat_prefetch_data_hits;
372 kstat_named_t arcstat_prefetch_data_misses;
373 kstat_named_t arcstat_prefetch_metadata_hits;
374 kstat_named_t arcstat_prefetch_metadata_misses;
375 kstat_named_t arcstat_mru_hits;
376 kstat_named_t arcstat_mru_ghost_hits;
377 kstat_named_t arcstat_mfu_hits;
378 kstat_named_t arcstat_mfu_ghost_hits;
379 kstat_named_t arcstat_allocated;
380 kstat_named_t arcstat_deleted;
382 * Number of buffers that could not be evicted because the hash lock
383 * was held by another thread. The lock may not necessarily be held
384 * by something using the same buffer, since hash locks are shared
385 * by multiple buffers.
387 kstat_named_t arcstat_mutex_miss;
389 * Number of buffers skipped because they have I/O in progress, are
390 * indrect prefetch buffers that have not lived long enough, or are
391 * not from the spa we're trying to evict from.
393 kstat_named_t arcstat_evict_skip;
395 * Number of times arc_evict_state() was unable to evict enough
396 * buffers to reach it's target amount.
398 kstat_named_t arcstat_evict_not_enough;
399 kstat_named_t arcstat_evict_l2_cached;
400 kstat_named_t arcstat_evict_l2_eligible;
401 kstat_named_t arcstat_evict_l2_ineligible;
402 kstat_named_t arcstat_evict_l2_skip;
403 kstat_named_t arcstat_hash_elements;
404 kstat_named_t arcstat_hash_elements_max;
405 kstat_named_t arcstat_hash_collisions;
406 kstat_named_t arcstat_hash_chains;
407 kstat_named_t arcstat_hash_chain_max;
408 kstat_named_t arcstat_p;
409 kstat_named_t arcstat_c;
410 kstat_named_t arcstat_c_min;
411 kstat_named_t arcstat_c_max;
412 kstat_named_t arcstat_size;
414 * Number of bytes consumed by internal ARC structures necessary
415 * for tracking purposes; these structures are not actually
416 * backed by ARC buffers. This includes arc_buf_hdr_t structures
417 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
418 * caches), and arc_buf_t structures (allocated via arc_buf_t
421 kstat_named_t arcstat_hdr_size;
423 * Number of bytes consumed by ARC buffers of type equal to
424 * ARC_BUFC_DATA. This is generally consumed by buffers backing
425 * on disk user data (e.g. plain file contents).
427 kstat_named_t arcstat_data_size;
429 * Number of bytes consumed by ARC buffers of type equal to
430 * ARC_BUFC_METADATA. This is generally consumed by buffers
431 * backing on disk data that is used for internal ZFS
432 * structures (e.g. ZAP, dnode, indirect blocks, etc).
434 kstat_named_t arcstat_metadata_size;
436 * Number of bytes consumed by various buffers and structures
437 * not actually backed with ARC buffers. This includes bonus
438 * buffers (allocated directly via zio_buf_* functions),
439 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
440 * cache), and dnode_t structures (allocated via dnode_t cache).
442 kstat_named_t arcstat_other_size;
444 * Total number of bytes consumed by ARC buffers residing in the
445 * arc_anon state. This includes *all* buffers in the arc_anon
446 * state; e.g. data, metadata, evictable, and unevictable buffers
447 * are all included in this value.
449 kstat_named_t arcstat_anon_size;
451 * Number of bytes consumed by ARC buffers that meet the
452 * following criteria: backing buffers of type ARC_BUFC_DATA,
453 * residing in the arc_anon state, and are eligible for eviction
454 * (e.g. have no outstanding holds on the buffer).
456 kstat_named_t arcstat_anon_evictable_data;
458 * Number of bytes consumed by ARC buffers that meet the
459 * following criteria: backing buffers of type ARC_BUFC_METADATA,
460 * residing in the arc_anon state, and are eligible for eviction
461 * (e.g. have no outstanding holds on the buffer).
463 kstat_named_t arcstat_anon_evictable_metadata;
465 * Total number of bytes consumed by ARC buffers residing in the
466 * arc_mru state. This includes *all* buffers in the arc_mru
467 * state; e.g. data, metadata, evictable, and unevictable buffers
468 * are all included in this value.
470 kstat_named_t arcstat_mru_size;
472 * Number of bytes consumed by ARC buffers that meet the
473 * following criteria: backing buffers of type ARC_BUFC_DATA,
474 * residing in the arc_mru state, and are eligible for eviction
475 * (e.g. have no outstanding holds on the buffer).
477 kstat_named_t arcstat_mru_evictable_data;
479 * Number of bytes consumed by ARC buffers that meet the
480 * following criteria: backing buffers of type ARC_BUFC_METADATA,
481 * residing in the arc_mru state, and are eligible for eviction
482 * (e.g. have no outstanding holds on the buffer).
484 kstat_named_t arcstat_mru_evictable_metadata;
486 * Total number of bytes that *would have been* consumed by ARC
487 * buffers in the arc_mru_ghost state. The key thing to note
488 * here, is the fact that this size doesn't actually indicate
489 * RAM consumption. The ghost lists only consist of headers and
490 * don't actually have ARC buffers linked off of these headers.
491 * Thus, *if* the headers had associated ARC buffers, these
492 * buffers *would have* consumed this number of bytes.
494 kstat_named_t arcstat_mru_ghost_size;
496 * Number of bytes that *would have been* consumed by ARC
497 * buffers that are eligible for eviction, of type
498 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
500 kstat_named_t arcstat_mru_ghost_evictable_data;
502 * Number of bytes that *would have been* consumed by ARC
503 * buffers that are eligible for eviction, of type
504 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
506 kstat_named_t arcstat_mru_ghost_evictable_metadata;
508 * Total number of bytes consumed by ARC buffers residing in the
509 * arc_mfu state. This includes *all* buffers in the arc_mfu
510 * state; e.g. data, metadata, evictable, and unevictable buffers
511 * are all included in this value.
513 kstat_named_t arcstat_mfu_size;
515 * Number of bytes consumed by ARC buffers that are eligible for
516 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
519 kstat_named_t arcstat_mfu_evictable_data;
521 * Number of bytes consumed by ARC buffers that are eligible for
522 * eviction, of type ARC_BUFC_METADATA, and reside in the
525 kstat_named_t arcstat_mfu_evictable_metadata;
527 * Total number of bytes that *would have been* consumed by ARC
528 * buffers in the arc_mfu_ghost state. See the comment above
529 * arcstat_mru_ghost_size for more details.
531 kstat_named_t arcstat_mfu_ghost_size;
533 * Number of bytes that *would have been* consumed by ARC
534 * buffers that are eligible for eviction, of type
535 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
537 kstat_named_t arcstat_mfu_ghost_evictable_data;
539 * Number of bytes that *would have been* consumed by ARC
540 * buffers that are eligible for eviction, of type
541 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
543 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
544 kstat_named_t arcstat_l2_hits;
545 kstat_named_t arcstat_l2_misses;
546 kstat_named_t arcstat_l2_feeds;
547 kstat_named_t arcstat_l2_rw_clash;
548 kstat_named_t arcstat_l2_read_bytes;
549 kstat_named_t arcstat_l2_write_bytes;
550 kstat_named_t arcstat_l2_writes_sent;
551 kstat_named_t arcstat_l2_writes_done;
552 kstat_named_t arcstat_l2_writes_error;
553 kstat_named_t arcstat_l2_writes_lock_retry;
554 kstat_named_t arcstat_l2_evict_lock_retry;
555 kstat_named_t arcstat_l2_evict_reading;
556 kstat_named_t arcstat_l2_evict_l1cached;
557 kstat_named_t arcstat_l2_free_on_write;
558 kstat_named_t arcstat_l2_cdata_free_on_write;
559 kstat_named_t arcstat_l2_abort_lowmem;
560 kstat_named_t arcstat_l2_cksum_bad;
561 kstat_named_t arcstat_l2_io_error;
562 kstat_named_t arcstat_l2_size;
563 kstat_named_t arcstat_l2_asize;
564 kstat_named_t arcstat_l2_hdr_size;
565 kstat_named_t arcstat_l2_compress_successes;
566 kstat_named_t arcstat_l2_compress_zeros;
567 kstat_named_t arcstat_l2_compress_failures;
568 kstat_named_t arcstat_l2_write_trylock_fail;
569 kstat_named_t arcstat_l2_write_passed_headroom;
570 kstat_named_t arcstat_l2_write_spa_mismatch;
571 kstat_named_t arcstat_l2_write_in_l2;
572 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
573 kstat_named_t arcstat_l2_write_not_cacheable;
574 kstat_named_t arcstat_l2_write_full;
575 kstat_named_t arcstat_l2_write_buffer_iter;
576 kstat_named_t arcstat_l2_write_pios;
577 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
578 kstat_named_t arcstat_l2_write_buffer_list_iter;
579 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
580 kstat_named_t arcstat_memory_throttle_count;
581 kstat_named_t arcstat_duplicate_buffers;
582 kstat_named_t arcstat_duplicate_buffers_size;
583 kstat_named_t arcstat_duplicate_reads;
584 kstat_named_t arcstat_meta_used;
585 kstat_named_t arcstat_meta_limit;
586 kstat_named_t arcstat_meta_max;
587 kstat_named_t arcstat_meta_min;
588 kstat_named_t arcstat_sync_wait_for_async;
589 kstat_named_t arcstat_demand_hit_predictive_prefetch;
592 static arc_stats_t arc_stats = {
593 { "hits", KSTAT_DATA_UINT64 },
594 { "misses", KSTAT_DATA_UINT64 },
595 { "demand_data_hits", KSTAT_DATA_UINT64 },
596 { "demand_data_misses", KSTAT_DATA_UINT64 },
597 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
598 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
599 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
600 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
601 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
602 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
603 { "mru_hits", KSTAT_DATA_UINT64 },
604 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
605 { "mfu_hits", KSTAT_DATA_UINT64 },
606 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
607 { "allocated", KSTAT_DATA_UINT64 },
608 { "deleted", KSTAT_DATA_UINT64 },
609 { "mutex_miss", KSTAT_DATA_UINT64 },
610 { "evict_skip", KSTAT_DATA_UINT64 },
611 { "evict_not_enough", KSTAT_DATA_UINT64 },
612 { "evict_l2_cached", KSTAT_DATA_UINT64 },
613 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
614 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
615 { "evict_l2_skip", KSTAT_DATA_UINT64 },
616 { "hash_elements", KSTAT_DATA_UINT64 },
617 { "hash_elements_max", KSTAT_DATA_UINT64 },
618 { "hash_collisions", KSTAT_DATA_UINT64 },
619 { "hash_chains", KSTAT_DATA_UINT64 },
620 { "hash_chain_max", KSTAT_DATA_UINT64 },
621 { "p", KSTAT_DATA_UINT64 },
622 { "c", KSTAT_DATA_UINT64 },
623 { "c_min", KSTAT_DATA_UINT64 },
624 { "c_max", KSTAT_DATA_UINT64 },
625 { "size", KSTAT_DATA_UINT64 },
626 { "hdr_size", KSTAT_DATA_UINT64 },
627 { "data_size", KSTAT_DATA_UINT64 },
628 { "metadata_size", KSTAT_DATA_UINT64 },
629 { "other_size", KSTAT_DATA_UINT64 },
630 { "anon_size", KSTAT_DATA_UINT64 },
631 { "anon_evictable_data", KSTAT_DATA_UINT64 },
632 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
633 { "mru_size", KSTAT_DATA_UINT64 },
634 { "mru_evictable_data", KSTAT_DATA_UINT64 },
635 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
636 { "mru_ghost_size", KSTAT_DATA_UINT64 },
637 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
638 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
639 { "mfu_size", KSTAT_DATA_UINT64 },
640 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
641 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
642 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
643 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
644 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
645 { "l2_hits", KSTAT_DATA_UINT64 },
646 { "l2_misses", KSTAT_DATA_UINT64 },
647 { "l2_feeds", KSTAT_DATA_UINT64 },
648 { "l2_rw_clash", KSTAT_DATA_UINT64 },
649 { "l2_read_bytes", KSTAT_DATA_UINT64 },
650 { "l2_write_bytes", KSTAT_DATA_UINT64 },
651 { "l2_writes_sent", KSTAT_DATA_UINT64 },
652 { "l2_writes_done", KSTAT_DATA_UINT64 },
653 { "l2_writes_error", KSTAT_DATA_UINT64 },
654 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
655 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
656 { "l2_evict_reading", KSTAT_DATA_UINT64 },
657 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
658 { "l2_free_on_write", KSTAT_DATA_UINT64 },
659 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
660 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
661 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
662 { "l2_io_error", KSTAT_DATA_UINT64 },
663 { "l2_size", KSTAT_DATA_UINT64 },
664 { "l2_asize", KSTAT_DATA_UINT64 },
665 { "l2_hdr_size", KSTAT_DATA_UINT64 },
666 { "l2_compress_successes", KSTAT_DATA_UINT64 },
667 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
668 { "l2_compress_failures", KSTAT_DATA_UINT64 },
669 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
670 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
671 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
672 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
673 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
674 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
675 { "l2_write_full", KSTAT_DATA_UINT64 },
676 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
677 { "l2_write_pios", KSTAT_DATA_UINT64 },
678 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
679 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
680 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
681 { "memory_throttle_count", KSTAT_DATA_UINT64 },
682 { "duplicate_buffers", KSTAT_DATA_UINT64 },
683 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
684 { "duplicate_reads", KSTAT_DATA_UINT64 },
685 { "arc_meta_used", KSTAT_DATA_UINT64 },
686 { "arc_meta_limit", KSTAT_DATA_UINT64 },
687 { "arc_meta_max", KSTAT_DATA_UINT64 },
688 { "arc_meta_min", KSTAT_DATA_UINT64 },
689 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
690 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
693 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
695 #define ARCSTAT_INCR(stat, val) \
696 atomic_add_64(&arc_stats.stat.value.ui64, (val))
698 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
699 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
701 #define ARCSTAT_MAX(stat, val) { \
703 while ((val) > (m = arc_stats.stat.value.ui64) && \
704 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
708 #define ARCSTAT_MAXSTAT(stat) \
709 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
712 * We define a macro to allow ARC hits/misses to be easily broken down by
713 * two separate conditions, giving a total of four different subtypes for
714 * each of hits and misses (so eight statistics total).
716 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
719 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
721 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
725 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
727 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
732 static arc_state_t *arc_anon;
733 static arc_state_t *arc_mru;
734 static arc_state_t *arc_mru_ghost;
735 static arc_state_t *arc_mfu;
736 static arc_state_t *arc_mfu_ghost;
737 static arc_state_t *arc_l2c_only;
740 * There are several ARC variables that are critical to export as kstats --
741 * but we don't want to have to grovel around in the kstat whenever we wish to
742 * manipulate them. For these variables, we therefore define them to be in
743 * terms of the statistic variable. This assures that we are not introducing
744 * the possibility of inconsistency by having shadow copies of the variables,
745 * while still allowing the code to be readable.
747 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
748 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
749 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
750 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
751 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
752 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
753 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
754 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
755 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
757 #define L2ARC_IS_VALID_COMPRESS(_c_) \
758 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
760 static int arc_no_grow; /* Don't try to grow cache size */
761 static uint64_t arc_tempreserve;
762 static uint64_t arc_loaned_bytes;
764 typedef struct arc_callback arc_callback_t;
766 struct arc_callback {
768 arc_done_func_t *acb_done;
770 zio_t *acb_zio_dummy;
771 arc_callback_t *acb_next;
774 typedef struct arc_write_callback arc_write_callback_t;
776 struct arc_write_callback {
778 arc_done_func_t *awcb_ready;
779 arc_done_func_t *awcb_physdone;
780 arc_done_func_t *awcb_done;
785 * ARC buffers are separated into multiple structs as a memory saving measure:
786 * - Common fields struct, always defined, and embedded within it:
787 * - L2-only fields, always allocated but undefined when not in L2ARC
788 * - L1-only fields, only allocated when in L1ARC
790 * Buffer in L1 Buffer only in L2
791 * +------------------------+ +------------------------+
792 * | arc_buf_hdr_t | | arc_buf_hdr_t |
796 * +------------------------+ +------------------------+
797 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
798 * | (undefined if L1-only) | | |
799 * +------------------------+ +------------------------+
800 * | l1arc_buf_hdr_t |
805 * +------------------------+
807 * Because it's possible for the L2ARC to become extremely large, we can wind
808 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
809 * is minimized by only allocating the fields necessary for an L1-cached buffer
810 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
811 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
812 * words in pointers. arc_hdr_realloc() is used to switch a header between
813 * these two allocation states.
815 typedef struct l1arc_buf_hdr {
816 kmutex_t b_freeze_lock;
819 * used for debugging wtih kmem_flags - by allocating and freeing
820 * b_thawed when the buffer is thawed, we get a record of the stack
821 * trace that thawed it.
828 /* for waiting on writes to complete */
831 /* protected by arc state mutex */
832 arc_state_t *b_state;
833 multilist_node_t b_arc_node;
835 /* updated atomically */
836 clock_t b_arc_access;
838 /* self protecting */
841 arc_callback_t *b_acb;
842 /* temporary buffer holder for in-flight compressed data */
846 typedef struct l2arc_dev l2arc_dev_t;
848 typedef struct l2arc_buf_hdr {
849 /* protected by arc_buf_hdr mutex */
850 l2arc_dev_t *b_dev; /* L2ARC device */
851 uint64_t b_daddr; /* disk address, offset byte */
852 /* 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)
933 /* For storing compression mode in b_flags */
934 #define HDR_COMPRESS_OFFSET 24
935 #define HDR_COMPRESS_NBITS 7
937 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET(hdr->b_flags, \
938 HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS))
939 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET(hdr->b_flags, \
940 HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS, (cmp))
946 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
947 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
950 * Hash table routines
953 #define HT_LOCK_PAD CACHE_LINE_SIZE
958 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
962 #define BUF_LOCKS 256
963 typedef struct buf_hash_table {
965 arc_buf_hdr_t **ht_table;
966 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
969 static buf_hash_table_t buf_hash_table;
971 #define BUF_HASH_INDEX(spa, dva, birth) \
972 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
973 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
974 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
975 #define HDR_LOCK(hdr) \
976 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
978 uint64_t zfs_crc64_table[256];
984 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
985 #define L2ARC_HEADROOM 2 /* num of writes */
987 * If we discover during ARC scan any buffers to be compressed, we boost
988 * our headroom for the next scanning cycle by this percentage multiple.
990 #define L2ARC_HEADROOM_BOOST 200
991 #define L2ARC_FEED_SECS 1 /* caching interval secs */
992 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
995 * Used to distinguish headers that are being process by
996 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
997 * address. This can happen when the header is added to the l2arc's list
998 * of buffers to write in the first stage of l2arc_write_buffers(), but
999 * has not yet been written out which happens in the second stage of
1000 * l2arc_write_buffers().
1002 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
1004 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1005 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1007 /* L2ARC Performance Tunables */
1008 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1009 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1010 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1011 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1012 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1013 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1014 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1015 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1016 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1018 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1019 &l2arc_write_max, 0, "max write size");
1020 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1021 &l2arc_write_boost, 0, "extra write during warmup");
1022 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1023 &l2arc_headroom, 0, "number of dev writes");
1024 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1025 &l2arc_feed_secs, 0, "interval seconds");
1026 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1027 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1029 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1030 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1031 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1032 &l2arc_feed_again, 0, "turbo warmup");
1033 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1034 &l2arc_norw, 0, "no reads during writes");
1036 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1037 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1038 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1039 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1040 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1041 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1043 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1044 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1045 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1046 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1047 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1048 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1050 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1051 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1052 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1053 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1054 "size of metadata in mru ghost state");
1055 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1056 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1057 "size of data in mru ghost state");
1059 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1060 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1061 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1062 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1063 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1064 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1066 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1067 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1068 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1069 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1070 "size of metadata in mfu ghost state");
1071 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1072 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1073 "size of data in mfu ghost state");
1075 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1076 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1082 vdev_t *l2ad_vdev; /* vdev */
1083 spa_t *l2ad_spa; /* spa */
1084 uint64_t l2ad_hand; /* next write location */
1085 uint64_t l2ad_start; /* first addr on device */
1086 uint64_t l2ad_end; /* last addr on device */
1087 boolean_t l2ad_first; /* first sweep through */
1088 boolean_t l2ad_writing; /* currently writing */
1089 kmutex_t l2ad_mtx; /* lock for buffer list */
1090 list_t l2ad_buflist; /* buffer list */
1091 list_node_t l2ad_node; /* device list node */
1092 refcount_t l2ad_alloc; /* allocated bytes */
1095 static list_t L2ARC_dev_list; /* device list */
1096 static list_t *l2arc_dev_list; /* device list pointer */
1097 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1098 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1099 static list_t L2ARC_free_on_write; /* free after write buf list */
1100 static list_t *l2arc_free_on_write; /* free after write list ptr */
1101 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1102 static uint64_t l2arc_ndev; /* number of devices */
1104 typedef struct l2arc_read_callback {
1105 arc_buf_t *l2rcb_buf; /* read buffer */
1106 spa_t *l2rcb_spa; /* spa */
1107 blkptr_t l2rcb_bp; /* original blkptr */
1108 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1109 int l2rcb_flags; /* original flags */
1110 enum zio_compress l2rcb_compress; /* applied compress */
1111 } l2arc_read_callback_t;
1113 typedef struct l2arc_write_callback {
1114 l2arc_dev_t *l2wcb_dev; /* device info */
1115 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1116 } l2arc_write_callback_t;
1118 typedef struct l2arc_data_free {
1119 /* protected by l2arc_free_on_write_mtx */
1122 void (*l2df_func)(void *, size_t);
1123 list_node_t l2df_list_node;
1124 } l2arc_data_free_t;
1126 static kmutex_t l2arc_feed_thr_lock;
1127 static kcondvar_t l2arc_feed_thr_cv;
1128 static uint8_t l2arc_thread_exit;
1130 static void arc_get_data_buf(arc_buf_t *);
1131 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1132 static boolean_t arc_is_overflowing();
1133 static void arc_buf_watch(arc_buf_t *);
1135 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1136 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1138 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1139 static void l2arc_read_done(zio_t *);
1141 static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
1142 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1143 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1146 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1148 uint8_t *vdva = (uint8_t *)dva;
1149 uint64_t crc = -1ULL;
1152 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1154 for (i = 0; i < sizeof (dva_t); i++)
1155 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1157 crc ^= (spa>>8) ^ birth;
1162 #define BUF_EMPTY(buf) \
1163 ((buf)->b_dva.dva_word[0] == 0 && \
1164 (buf)->b_dva.dva_word[1] == 0)
1166 #define BUF_EQUAL(spa, dva, birth, buf) \
1167 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1168 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1169 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1172 buf_discard_identity(arc_buf_hdr_t *hdr)
1174 hdr->b_dva.dva_word[0] = 0;
1175 hdr->b_dva.dva_word[1] = 0;
1179 static arc_buf_hdr_t *
1180 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1182 const dva_t *dva = BP_IDENTITY(bp);
1183 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1184 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1185 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1188 mutex_enter(hash_lock);
1189 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1190 hdr = hdr->b_hash_next) {
1191 if (BUF_EQUAL(spa, dva, birth, hdr)) {
1196 mutex_exit(hash_lock);
1202 * Insert an entry into the hash table. If there is already an element
1203 * equal to elem in the hash table, then the already existing element
1204 * will be returned and the new element will not be inserted.
1205 * Otherwise returns NULL.
1206 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1208 static arc_buf_hdr_t *
1209 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1211 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1212 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1213 arc_buf_hdr_t *fhdr;
1216 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1217 ASSERT(hdr->b_birth != 0);
1218 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1220 if (lockp != NULL) {
1222 mutex_enter(hash_lock);
1224 ASSERT(MUTEX_HELD(hash_lock));
1227 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1228 fhdr = fhdr->b_hash_next, i++) {
1229 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1233 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1234 buf_hash_table.ht_table[idx] = hdr;
1235 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1237 /* collect some hash table performance data */
1239 ARCSTAT_BUMP(arcstat_hash_collisions);
1241 ARCSTAT_BUMP(arcstat_hash_chains);
1243 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1246 ARCSTAT_BUMP(arcstat_hash_elements);
1247 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1253 buf_hash_remove(arc_buf_hdr_t *hdr)
1255 arc_buf_hdr_t *fhdr, **hdrp;
1256 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1258 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1259 ASSERT(HDR_IN_HASH_TABLE(hdr));
1261 hdrp = &buf_hash_table.ht_table[idx];
1262 while ((fhdr = *hdrp) != hdr) {
1263 ASSERT(fhdr != NULL);
1264 hdrp = &fhdr->b_hash_next;
1266 *hdrp = hdr->b_hash_next;
1267 hdr->b_hash_next = NULL;
1268 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1270 /* collect some hash table performance data */
1271 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1273 if (buf_hash_table.ht_table[idx] &&
1274 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1275 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1279 * Global data structures and functions for the buf kmem cache.
1281 static kmem_cache_t *hdr_full_cache;
1282 static kmem_cache_t *hdr_l2only_cache;
1283 static kmem_cache_t *buf_cache;
1290 kmem_free(buf_hash_table.ht_table,
1291 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1292 for (i = 0; i < BUF_LOCKS; i++)
1293 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1294 kmem_cache_destroy(hdr_full_cache);
1295 kmem_cache_destroy(hdr_l2only_cache);
1296 kmem_cache_destroy(buf_cache);
1300 * Constructor callback - called when the cache is empty
1301 * and a new buf is requested.
1305 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1307 arc_buf_hdr_t *hdr = vbuf;
1309 bzero(hdr, HDR_FULL_SIZE);
1310 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1311 refcount_create(&hdr->b_l1hdr.b_refcnt);
1312 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1313 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1314 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1321 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1323 arc_buf_hdr_t *hdr = vbuf;
1325 bzero(hdr, HDR_L2ONLY_SIZE);
1326 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1333 buf_cons(void *vbuf, void *unused, int kmflag)
1335 arc_buf_t *buf = vbuf;
1337 bzero(buf, sizeof (arc_buf_t));
1338 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1339 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1345 * Destructor callback - called when a cached buf is
1346 * no longer required.
1350 hdr_full_dest(void *vbuf, void *unused)
1352 arc_buf_hdr_t *hdr = vbuf;
1354 ASSERT(BUF_EMPTY(hdr));
1355 cv_destroy(&hdr->b_l1hdr.b_cv);
1356 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1357 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1358 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1359 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1364 hdr_l2only_dest(void *vbuf, void *unused)
1366 arc_buf_hdr_t *hdr = vbuf;
1368 ASSERT(BUF_EMPTY(hdr));
1369 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1374 buf_dest(void *vbuf, void *unused)
1376 arc_buf_t *buf = vbuf;
1378 mutex_destroy(&buf->b_evict_lock);
1379 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1383 * Reclaim callback -- invoked when memory is low.
1387 hdr_recl(void *unused)
1389 dprintf("hdr_recl called\n");
1391 * umem calls the reclaim func when we destroy the buf cache,
1392 * which is after we do arc_fini().
1395 cv_signal(&arc_reclaim_thread_cv);
1402 uint64_t hsize = 1ULL << 12;
1406 * The hash table is big enough to fill all of physical memory
1407 * with an average block size of zfs_arc_average_blocksize (default 8K).
1408 * By default, the table will take up
1409 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1411 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1414 buf_hash_table.ht_mask = hsize - 1;
1415 buf_hash_table.ht_table =
1416 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1417 if (buf_hash_table.ht_table == NULL) {
1418 ASSERT(hsize > (1ULL << 8));
1423 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1424 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1425 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1426 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1428 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1429 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1431 for (i = 0; i < 256; i++)
1432 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1433 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1435 for (i = 0; i < BUF_LOCKS; i++) {
1436 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1437 NULL, MUTEX_DEFAULT, NULL);
1442 * Transition between the two allocation states for the arc_buf_hdr struct.
1443 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1444 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1445 * version is used when a cache buffer is only in the L2ARC in order to reduce
1448 static arc_buf_hdr_t *
1449 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1451 ASSERT(HDR_HAS_L2HDR(hdr));
1453 arc_buf_hdr_t *nhdr;
1454 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1456 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1457 (old == hdr_l2only_cache && new == hdr_full_cache));
1459 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1461 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1462 buf_hash_remove(hdr);
1464 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1466 if (new == hdr_full_cache) {
1467 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1469 * arc_access and arc_change_state need to be aware that a
1470 * header has just come out of L2ARC, so we set its state to
1471 * l2c_only even though it's about to change.
1473 nhdr->b_l1hdr.b_state = arc_l2c_only;
1475 /* Verify previous threads set to NULL before freeing */
1476 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1478 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1479 ASSERT0(hdr->b_l1hdr.b_datacnt);
1482 * If we've reached here, We must have been called from
1483 * arc_evict_hdr(), as such we should have already been
1484 * removed from any ghost list we were previously on
1485 * (which protects us from racing with arc_evict_state),
1486 * thus no locking is needed during this check.
1488 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1491 * A buffer must not be moved into the arc_l2c_only
1492 * state if it's not finished being written out to the
1493 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1494 * might try to be accessed, even though it was removed.
1496 VERIFY(!HDR_L2_WRITING(hdr));
1497 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1499 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1502 * The header has been reallocated so we need to re-insert it into any
1505 (void) buf_hash_insert(nhdr, NULL);
1507 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1509 mutex_enter(&dev->l2ad_mtx);
1512 * We must place the realloc'ed header back into the list at
1513 * the same spot. Otherwise, if it's placed earlier in the list,
1514 * l2arc_write_buffers() could find it during the function's
1515 * write phase, and try to write it out to the l2arc.
1517 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1518 list_remove(&dev->l2ad_buflist, hdr);
1520 mutex_exit(&dev->l2ad_mtx);
1523 * Since we're using the pointer address as the tag when
1524 * incrementing and decrementing the l2ad_alloc refcount, we
1525 * must remove the old pointer (that we're about to destroy) and
1526 * add the new pointer to the refcount. Otherwise we'd remove
1527 * the wrong pointer address when calling arc_hdr_destroy() later.
1530 (void) refcount_remove_many(&dev->l2ad_alloc,
1531 hdr->b_l2hdr.b_asize, hdr);
1533 (void) refcount_add_many(&dev->l2ad_alloc,
1534 nhdr->b_l2hdr.b_asize, nhdr);
1536 buf_discard_identity(hdr);
1537 hdr->b_freeze_cksum = NULL;
1538 kmem_cache_free(old, hdr);
1544 #define ARC_MINTIME (hz>>4) /* 62 ms */
1547 arc_cksum_verify(arc_buf_t *buf)
1551 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1554 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1555 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1556 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1559 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1560 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1561 panic("buffer modified while frozen!");
1562 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1566 arc_cksum_equal(arc_buf_t *buf)
1571 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1572 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1573 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1574 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1580 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1582 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1585 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1586 if (buf->b_hdr->b_freeze_cksum != NULL) {
1587 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1590 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1591 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1592 buf->b_hdr->b_freeze_cksum);
1593 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1596 #endif /* illumos */
1601 typedef struct procctl {
1609 arc_buf_unwatch(arc_buf_t *buf)
1616 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1617 ctl.prwatch.pr_size = 0;
1618 ctl.prwatch.pr_wflags = 0;
1619 result = write(arc_procfd, &ctl, sizeof (ctl));
1620 ASSERT3U(result, ==, sizeof (ctl));
1627 arc_buf_watch(arc_buf_t *buf)
1634 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1635 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1636 ctl.prwatch.pr_wflags = WA_WRITE;
1637 result = write(arc_procfd, &ctl, sizeof (ctl));
1638 ASSERT3U(result, ==, sizeof (ctl));
1642 #endif /* illumos */
1644 static arc_buf_contents_t
1645 arc_buf_type(arc_buf_hdr_t *hdr)
1647 if (HDR_ISTYPE_METADATA(hdr)) {
1648 return (ARC_BUFC_METADATA);
1650 return (ARC_BUFC_DATA);
1655 arc_bufc_to_flags(arc_buf_contents_t type)
1659 /* metadata field is 0 if buffer contains normal data */
1661 case ARC_BUFC_METADATA:
1662 return (ARC_FLAG_BUFC_METADATA);
1666 panic("undefined ARC buffer type!");
1667 return ((uint32_t)-1);
1671 arc_buf_thaw(arc_buf_t *buf)
1673 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1674 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1675 panic("modifying non-anon buffer!");
1676 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1677 panic("modifying buffer while i/o in progress!");
1678 arc_cksum_verify(buf);
1681 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1682 if (buf->b_hdr->b_freeze_cksum != NULL) {
1683 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1684 buf->b_hdr->b_freeze_cksum = NULL;
1688 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1689 if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1690 kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1691 buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1695 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1698 arc_buf_unwatch(buf);
1699 #endif /* illumos */
1703 arc_buf_freeze(arc_buf_t *buf)
1705 kmutex_t *hash_lock;
1707 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1710 hash_lock = HDR_LOCK(buf->b_hdr);
1711 mutex_enter(hash_lock);
1713 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1714 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1715 arc_cksum_compute(buf, B_FALSE);
1716 mutex_exit(hash_lock);
1721 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1723 ASSERT(HDR_HAS_L1HDR(hdr));
1724 ASSERT(MUTEX_HELD(hash_lock));
1725 arc_state_t *state = hdr->b_l1hdr.b_state;
1727 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1728 (state != arc_anon)) {
1729 /* We don't use the L2-only state list. */
1730 if (state != arc_l2c_only) {
1731 arc_buf_contents_t type = arc_buf_type(hdr);
1732 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1733 multilist_t *list = &state->arcs_list[type];
1734 uint64_t *size = &state->arcs_lsize[type];
1736 multilist_remove(list, hdr);
1738 if (GHOST_STATE(state)) {
1739 ASSERT0(hdr->b_l1hdr.b_datacnt);
1740 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1741 delta = hdr->b_size;
1744 ASSERT3U(*size, >=, delta);
1745 atomic_add_64(size, -delta);
1747 /* remove the prefetch flag if we get a reference */
1748 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1753 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1756 arc_state_t *state = hdr->b_l1hdr.b_state;
1758 ASSERT(HDR_HAS_L1HDR(hdr));
1759 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1760 ASSERT(!GHOST_STATE(state));
1763 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1764 * check to prevent usage of the arc_l2c_only list.
1766 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1767 (state != arc_anon)) {
1768 arc_buf_contents_t type = arc_buf_type(hdr);
1769 multilist_t *list = &state->arcs_list[type];
1770 uint64_t *size = &state->arcs_lsize[type];
1772 multilist_insert(list, hdr);
1774 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1775 atomic_add_64(size, hdr->b_size *
1776 hdr->b_l1hdr.b_datacnt);
1782 * Move the supplied buffer to the indicated state. The hash lock
1783 * for the buffer must be held by the caller.
1786 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1787 kmutex_t *hash_lock)
1789 arc_state_t *old_state;
1792 uint64_t from_delta, to_delta;
1793 arc_buf_contents_t buftype = arc_buf_type(hdr);
1796 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1797 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1798 * L1 hdr doesn't always exist when we change state to arc_anon before
1799 * destroying a header, in which case reallocating to add the L1 hdr is
1802 if (HDR_HAS_L1HDR(hdr)) {
1803 old_state = hdr->b_l1hdr.b_state;
1804 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1805 datacnt = hdr->b_l1hdr.b_datacnt;
1807 old_state = arc_l2c_only;
1812 ASSERT(MUTEX_HELD(hash_lock));
1813 ASSERT3P(new_state, !=, old_state);
1814 ASSERT(refcnt == 0 || datacnt > 0);
1815 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1816 ASSERT(old_state != arc_anon || datacnt <= 1);
1818 from_delta = to_delta = datacnt * hdr->b_size;
1821 * If this buffer is evictable, transfer it from the
1822 * old state list to the new state list.
1825 if (old_state != arc_anon && old_state != arc_l2c_only) {
1826 uint64_t *size = &old_state->arcs_lsize[buftype];
1828 ASSERT(HDR_HAS_L1HDR(hdr));
1829 multilist_remove(&old_state->arcs_list[buftype], hdr);
1832 * If prefetching out of the ghost cache,
1833 * we will have a non-zero datacnt.
1835 if (GHOST_STATE(old_state) && datacnt == 0) {
1836 /* ghost elements have a ghost size */
1837 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1838 from_delta = hdr->b_size;
1840 ASSERT3U(*size, >=, from_delta);
1841 atomic_add_64(size, -from_delta);
1843 if (new_state != arc_anon && new_state != arc_l2c_only) {
1844 uint64_t *size = &new_state->arcs_lsize[buftype];
1847 * An L1 header always exists here, since if we're
1848 * moving to some L1-cached state (i.e. not l2c_only or
1849 * anonymous), we realloc the header to add an L1hdr
1852 ASSERT(HDR_HAS_L1HDR(hdr));
1853 multilist_insert(&new_state->arcs_list[buftype], hdr);
1855 /* ghost elements have a ghost size */
1856 if (GHOST_STATE(new_state)) {
1858 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1859 to_delta = hdr->b_size;
1861 atomic_add_64(size, to_delta);
1865 ASSERT(!BUF_EMPTY(hdr));
1866 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1867 buf_hash_remove(hdr);
1869 /* adjust state sizes (ignore arc_l2c_only) */
1871 if (to_delta && new_state != arc_l2c_only) {
1872 ASSERT(HDR_HAS_L1HDR(hdr));
1873 if (GHOST_STATE(new_state)) {
1877 * We moving a header to a ghost state, we first
1878 * remove all arc buffers. Thus, we'll have a
1879 * datacnt of zero, and no arc buffer to use for
1880 * the reference. As a result, we use the arc
1881 * header pointer for the reference.
1883 (void) refcount_add_many(&new_state->arcs_size,
1886 ASSERT3U(datacnt, !=, 0);
1889 * Each individual buffer holds a unique reference,
1890 * thus we must remove each of these references one
1893 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1894 buf = buf->b_next) {
1895 (void) refcount_add_many(&new_state->arcs_size,
1901 if (from_delta && old_state != arc_l2c_only) {
1902 ASSERT(HDR_HAS_L1HDR(hdr));
1903 if (GHOST_STATE(old_state)) {
1905 * When moving a header off of a ghost state,
1906 * there's the possibility for datacnt to be
1907 * non-zero. This is because we first add the
1908 * arc buffer to the header prior to changing
1909 * the header's state. Since we used the header
1910 * for the reference when putting the header on
1911 * the ghost state, we must balance that and use
1912 * the header when removing off the ghost state
1913 * (even though datacnt is non zero).
1916 IMPLY(datacnt == 0, new_state == arc_anon ||
1917 new_state == arc_l2c_only);
1919 (void) refcount_remove_many(&old_state->arcs_size,
1922 ASSERT3P(datacnt, !=, 0);
1925 * Each individual buffer holds a unique reference,
1926 * thus we must remove each of these references one
1929 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1930 buf = buf->b_next) {
1931 (void) refcount_remove_many(
1932 &old_state->arcs_size, hdr->b_size, buf);
1937 if (HDR_HAS_L1HDR(hdr))
1938 hdr->b_l1hdr.b_state = new_state;
1941 * L2 headers should never be on the L2 state list since they don't
1942 * have L1 headers allocated.
1944 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1945 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1949 arc_space_consume(uint64_t space, arc_space_type_t type)
1951 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1954 case ARC_SPACE_DATA:
1955 ARCSTAT_INCR(arcstat_data_size, space);
1957 case ARC_SPACE_META:
1958 ARCSTAT_INCR(arcstat_metadata_size, space);
1960 case ARC_SPACE_OTHER:
1961 ARCSTAT_INCR(arcstat_other_size, space);
1963 case ARC_SPACE_HDRS:
1964 ARCSTAT_INCR(arcstat_hdr_size, space);
1966 case ARC_SPACE_L2HDRS:
1967 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1971 if (type != ARC_SPACE_DATA)
1972 ARCSTAT_INCR(arcstat_meta_used, space);
1974 atomic_add_64(&arc_size, space);
1978 arc_space_return(uint64_t space, arc_space_type_t type)
1980 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1983 case ARC_SPACE_DATA:
1984 ARCSTAT_INCR(arcstat_data_size, -space);
1986 case ARC_SPACE_META:
1987 ARCSTAT_INCR(arcstat_metadata_size, -space);
1989 case ARC_SPACE_OTHER:
1990 ARCSTAT_INCR(arcstat_other_size, -space);
1992 case ARC_SPACE_HDRS:
1993 ARCSTAT_INCR(arcstat_hdr_size, -space);
1995 case ARC_SPACE_L2HDRS:
1996 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2000 if (type != ARC_SPACE_DATA) {
2001 ASSERT(arc_meta_used >= space);
2002 if (arc_meta_max < arc_meta_used)
2003 arc_meta_max = arc_meta_used;
2004 ARCSTAT_INCR(arcstat_meta_used, -space);
2007 ASSERT(arc_size >= space);
2008 atomic_add_64(&arc_size, -space);
2012 arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2017 ASSERT3U(size, >, 0);
2018 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2019 ASSERT(BUF_EMPTY(hdr));
2020 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
2022 hdr->b_spa = spa_load_guid(spa);
2024 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2027 buf->b_efunc = NULL;
2028 buf->b_private = NULL;
2031 hdr->b_flags = arc_bufc_to_flags(type);
2032 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
2034 hdr->b_l1hdr.b_buf = buf;
2035 hdr->b_l1hdr.b_state = arc_anon;
2036 hdr->b_l1hdr.b_arc_access = 0;
2037 hdr->b_l1hdr.b_datacnt = 1;
2038 hdr->b_l1hdr.b_tmp_cdata = NULL;
2040 arc_get_data_buf(buf);
2041 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2042 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2047 static char *arc_onloan_tag = "onloan";
2050 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2051 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2052 * buffers must be returned to the arc before they can be used by the DMU or
2056 arc_loan_buf(spa_t *spa, int size)
2060 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2062 atomic_add_64(&arc_loaned_bytes, size);
2067 * Return a loaned arc buffer to the arc.
2070 arc_return_buf(arc_buf_t *buf, void *tag)
2072 arc_buf_hdr_t *hdr = buf->b_hdr;
2074 ASSERT(buf->b_data != NULL);
2075 ASSERT(HDR_HAS_L1HDR(hdr));
2076 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2077 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2079 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2082 /* Detach an arc_buf from a dbuf (tag) */
2084 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2086 arc_buf_hdr_t *hdr = buf->b_hdr;
2088 ASSERT(buf->b_data != NULL);
2089 ASSERT(HDR_HAS_L1HDR(hdr));
2090 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2091 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2092 buf->b_efunc = NULL;
2093 buf->b_private = NULL;
2095 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2099 arc_buf_clone(arc_buf_t *from)
2102 arc_buf_hdr_t *hdr = from->b_hdr;
2103 uint64_t size = hdr->b_size;
2105 ASSERT(HDR_HAS_L1HDR(hdr));
2106 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2108 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2111 buf->b_efunc = NULL;
2112 buf->b_private = NULL;
2113 buf->b_next = hdr->b_l1hdr.b_buf;
2114 hdr->b_l1hdr.b_buf = buf;
2115 arc_get_data_buf(buf);
2116 bcopy(from->b_data, buf->b_data, size);
2119 * This buffer already exists in the arc so create a duplicate
2120 * copy for the caller. If the buffer is associated with user data
2121 * then track the size and number of duplicates. These stats will be
2122 * updated as duplicate buffers are created and destroyed.
2124 if (HDR_ISTYPE_DATA(hdr)) {
2125 ARCSTAT_BUMP(arcstat_duplicate_buffers);
2126 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2128 hdr->b_l1hdr.b_datacnt += 1;
2133 arc_buf_add_ref(arc_buf_t *buf, void* tag)
2136 kmutex_t *hash_lock;
2139 * Check to see if this buffer is evicted. Callers
2140 * must verify b_data != NULL to know if the add_ref
2143 mutex_enter(&buf->b_evict_lock);
2144 if (buf->b_data == NULL) {
2145 mutex_exit(&buf->b_evict_lock);
2148 hash_lock = HDR_LOCK(buf->b_hdr);
2149 mutex_enter(hash_lock);
2151 ASSERT(HDR_HAS_L1HDR(hdr));
2152 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2153 mutex_exit(&buf->b_evict_lock);
2155 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2156 hdr->b_l1hdr.b_state == arc_mfu);
2158 add_reference(hdr, hash_lock, tag);
2159 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2160 arc_access(hdr, hash_lock);
2161 mutex_exit(hash_lock);
2162 ARCSTAT_BUMP(arcstat_hits);
2163 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2164 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2165 data, metadata, hits);
2169 arc_buf_free_on_write(void *data, size_t size,
2170 void (*free_func)(void *, size_t))
2172 l2arc_data_free_t *df;
2174 df = kmem_alloc(sizeof (*df), KM_SLEEP);
2175 df->l2df_data = data;
2176 df->l2df_size = size;
2177 df->l2df_func = free_func;
2178 mutex_enter(&l2arc_free_on_write_mtx);
2179 list_insert_head(l2arc_free_on_write, df);
2180 mutex_exit(&l2arc_free_on_write_mtx);
2184 * Free the arc data buffer. If it is an l2arc write in progress,
2185 * the buffer is placed on l2arc_free_on_write to be freed later.
2188 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2190 arc_buf_hdr_t *hdr = buf->b_hdr;
2192 if (HDR_L2_WRITING(hdr)) {
2193 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2194 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2196 free_func(buf->b_data, hdr->b_size);
2201 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2203 ASSERT(HDR_HAS_L2HDR(hdr));
2204 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2207 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2208 * that doesn't exist, the header is in the arc_l2c_only state,
2209 * and there isn't anything to free (it's already been freed).
2211 if (!HDR_HAS_L1HDR(hdr))
2215 * The header isn't being written to the l2arc device, thus it
2216 * shouldn't have a b_tmp_cdata to free.
2218 if (!HDR_L2_WRITING(hdr)) {
2219 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2224 * The header does not have compression enabled. This can be due
2225 * to the buffer not being compressible, or because we're
2226 * freeing the buffer before the second phase of
2227 * l2arc_write_buffer() has started (which does the compression
2228 * step). In either case, b_tmp_cdata does not point to a
2229 * separately compressed buffer, so there's nothing to free (it
2230 * points to the same buffer as the arc_buf_t's b_data field).
2232 if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) {
2233 hdr->b_l1hdr.b_tmp_cdata = NULL;
2238 * There's nothing to free since the buffer was all zero's and
2239 * compressed to a zero length buffer.
2241 if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_EMPTY) {
2242 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2246 ASSERT(L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)));
2248 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
2249 hdr->b_size, zio_data_buf_free);
2251 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2252 hdr->b_l1hdr.b_tmp_cdata = NULL;
2256 * Free up buf->b_data and if 'remove' is set, then pull the
2257 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2260 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2264 /* free up data associated with the buf */
2265 if (buf->b_data != NULL) {
2266 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2267 uint64_t size = buf->b_hdr->b_size;
2268 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2270 arc_cksum_verify(buf);
2272 arc_buf_unwatch(buf);
2273 #endif /* illumos */
2275 if (type == ARC_BUFC_METADATA) {
2276 arc_buf_data_free(buf, zio_buf_free);
2277 arc_space_return(size, ARC_SPACE_META);
2279 ASSERT(type == ARC_BUFC_DATA);
2280 arc_buf_data_free(buf, zio_data_buf_free);
2281 arc_space_return(size, ARC_SPACE_DATA);
2284 /* protected by hash lock, if in the hash table */
2285 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2286 uint64_t *cnt = &state->arcs_lsize[type];
2288 ASSERT(refcount_is_zero(
2289 &buf->b_hdr->b_l1hdr.b_refcnt));
2290 ASSERT(state != arc_anon && state != arc_l2c_only);
2292 ASSERT3U(*cnt, >=, size);
2293 atomic_add_64(cnt, -size);
2296 (void) refcount_remove_many(&state->arcs_size, size, buf);
2300 * If we're destroying a duplicate buffer make sure
2301 * that the appropriate statistics are updated.
2303 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2304 HDR_ISTYPE_DATA(buf->b_hdr)) {
2305 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2306 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2308 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2309 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2312 /* only remove the buf if requested */
2316 /* remove the buf from the hdr list */
2317 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2318 bufp = &(*bufp)->b_next)
2320 *bufp = buf->b_next;
2323 ASSERT(buf->b_efunc == NULL);
2325 /* clean up the buf */
2327 kmem_cache_free(buf_cache, buf);
2331 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2333 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2334 l2arc_dev_t *dev = l2hdr->b_dev;
2336 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2337 ASSERT(HDR_HAS_L2HDR(hdr));
2339 list_remove(&dev->l2ad_buflist, hdr);
2342 * We don't want to leak the b_tmp_cdata buffer that was
2343 * allocated in l2arc_write_buffers()
2345 arc_buf_l2_cdata_free(hdr);
2348 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2349 * this header is being processed by l2arc_write_buffers() (i.e.
2350 * it's in the first stage of l2arc_write_buffers()).
2351 * Re-affirming that truth here, just to serve as a reminder. If
2352 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2353 * may not have its HDR_L2_WRITING flag set. (the write may have
2354 * completed, in which case HDR_L2_WRITING will be false and the
2355 * b_daddr field will point to the address of the buffer on disk).
2357 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2360 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2361 * l2arc_write_buffers(). Since we've just removed this header
2362 * from the l2arc buffer list, this header will never reach the
2363 * second stage of l2arc_write_buffers(), which increments the
2364 * accounting stats for this header. Thus, we must be careful
2365 * not to decrement them for this header either.
2367 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2368 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2369 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2371 vdev_space_update(dev->l2ad_vdev,
2372 -l2hdr->b_asize, 0, 0);
2374 (void) refcount_remove_many(&dev->l2ad_alloc,
2375 l2hdr->b_asize, hdr);
2378 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2382 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2384 if (HDR_HAS_L1HDR(hdr)) {
2385 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2386 hdr->b_l1hdr.b_datacnt > 0);
2387 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2388 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2390 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2391 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2393 if (HDR_HAS_L2HDR(hdr)) {
2394 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2395 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2398 mutex_enter(&dev->l2ad_mtx);
2401 * Even though we checked this conditional above, we
2402 * need to check this again now that we have the
2403 * l2ad_mtx. This is because we could be racing with
2404 * another thread calling l2arc_evict() which might have
2405 * destroyed this header's L2 portion as we were waiting
2406 * to acquire the l2ad_mtx. If that happens, we don't
2407 * want to re-destroy the header's L2 portion.
2409 if (HDR_HAS_L2HDR(hdr)) {
2410 if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
2411 trim_map_free(dev->l2ad_vdev,
2412 hdr->b_l2hdr.b_daddr,
2413 hdr->b_l2hdr.b_asize, 0);
2414 arc_hdr_l2hdr_destroy(hdr);
2418 mutex_exit(&dev->l2ad_mtx);
2421 if (!BUF_EMPTY(hdr))
2422 buf_discard_identity(hdr);
2424 if (hdr->b_freeze_cksum != NULL) {
2425 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2426 hdr->b_freeze_cksum = NULL;
2429 if (HDR_HAS_L1HDR(hdr)) {
2430 while (hdr->b_l1hdr.b_buf) {
2431 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2433 if (buf->b_efunc != NULL) {
2434 mutex_enter(&arc_user_evicts_lock);
2435 mutex_enter(&buf->b_evict_lock);
2436 ASSERT(buf->b_hdr != NULL);
2437 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2438 hdr->b_l1hdr.b_buf = buf->b_next;
2439 buf->b_hdr = &arc_eviction_hdr;
2440 buf->b_next = arc_eviction_list;
2441 arc_eviction_list = buf;
2442 mutex_exit(&buf->b_evict_lock);
2443 cv_signal(&arc_user_evicts_cv);
2444 mutex_exit(&arc_user_evicts_lock);
2446 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2450 if (hdr->b_l1hdr.b_thawed != NULL) {
2451 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2452 hdr->b_l1hdr.b_thawed = NULL;
2457 ASSERT3P(hdr->b_hash_next, ==, NULL);
2458 if (HDR_HAS_L1HDR(hdr)) {
2459 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2460 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2461 kmem_cache_free(hdr_full_cache, hdr);
2463 kmem_cache_free(hdr_l2only_cache, hdr);
2468 arc_buf_free(arc_buf_t *buf, void *tag)
2470 arc_buf_hdr_t *hdr = buf->b_hdr;
2471 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2473 ASSERT(buf->b_efunc == NULL);
2474 ASSERT(buf->b_data != NULL);
2477 kmutex_t *hash_lock = HDR_LOCK(hdr);
2479 mutex_enter(hash_lock);
2481 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2483 (void) remove_reference(hdr, hash_lock, tag);
2484 if (hdr->b_l1hdr.b_datacnt > 1) {
2485 arc_buf_destroy(buf, TRUE);
2487 ASSERT(buf == hdr->b_l1hdr.b_buf);
2488 ASSERT(buf->b_efunc == NULL);
2489 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2491 mutex_exit(hash_lock);
2492 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2495 * We are in the middle of an async write. Don't destroy
2496 * this buffer unless the write completes before we finish
2497 * decrementing the reference count.
2499 mutex_enter(&arc_user_evicts_lock);
2500 (void) remove_reference(hdr, NULL, tag);
2501 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2502 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2503 mutex_exit(&arc_user_evicts_lock);
2505 arc_hdr_destroy(hdr);
2507 if (remove_reference(hdr, NULL, tag) > 0)
2508 arc_buf_destroy(buf, TRUE);
2510 arc_hdr_destroy(hdr);
2515 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2517 arc_buf_hdr_t *hdr = buf->b_hdr;
2518 kmutex_t *hash_lock = HDR_LOCK(hdr);
2519 boolean_t no_callback = (buf->b_efunc == NULL);
2521 if (hdr->b_l1hdr.b_state == arc_anon) {
2522 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2523 arc_buf_free(buf, tag);
2524 return (no_callback);
2527 mutex_enter(hash_lock);
2529 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2530 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2531 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2532 ASSERT(buf->b_data != NULL);
2534 (void) remove_reference(hdr, hash_lock, tag);
2535 if (hdr->b_l1hdr.b_datacnt > 1) {
2537 arc_buf_destroy(buf, TRUE);
2538 } else if (no_callback) {
2539 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2540 ASSERT(buf->b_efunc == NULL);
2541 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2543 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2544 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2545 mutex_exit(hash_lock);
2546 return (no_callback);
2550 arc_buf_size(arc_buf_t *buf)
2552 return (buf->b_hdr->b_size);
2556 * Called from the DMU to determine if the current buffer should be
2557 * evicted. In order to ensure proper locking, the eviction must be initiated
2558 * from the DMU. Return true if the buffer is associated with user data and
2559 * duplicate buffers still exist.
2562 arc_buf_eviction_needed(arc_buf_t *buf)
2565 boolean_t evict_needed = B_FALSE;
2567 if (zfs_disable_dup_eviction)
2570 mutex_enter(&buf->b_evict_lock);
2574 * We are in arc_do_user_evicts(); let that function
2575 * perform the eviction.
2577 ASSERT(buf->b_data == NULL);
2578 mutex_exit(&buf->b_evict_lock);
2580 } else if (buf->b_data == NULL) {
2582 * We have already been added to the arc eviction list;
2583 * recommend eviction.
2585 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2586 mutex_exit(&buf->b_evict_lock);
2590 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2591 evict_needed = B_TRUE;
2593 mutex_exit(&buf->b_evict_lock);
2594 return (evict_needed);
2598 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2599 * state of the header is dependent on it's state prior to entering this
2600 * function. The following transitions are possible:
2602 * - arc_mru -> arc_mru_ghost
2603 * - arc_mfu -> arc_mfu_ghost
2604 * - arc_mru_ghost -> arc_l2c_only
2605 * - arc_mru_ghost -> deleted
2606 * - arc_mfu_ghost -> arc_l2c_only
2607 * - arc_mfu_ghost -> deleted
2610 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2612 arc_state_t *evicted_state, *state;
2613 int64_t bytes_evicted = 0;
2615 ASSERT(MUTEX_HELD(hash_lock));
2616 ASSERT(HDR_HAS_L1HDR(hdr));
2618 state = hdr->b_l1hdr.b_state;
2619 if (GHOST_STATE(state)) {
2620 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2621 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2624 * l2arc_write_buffers() relies on a header's L1 portion
2625 * (i.e. it's b_tmp_cdata field) during it's write phase.
2626 * Thus, we cannot push a header onto the arc_l2c_only
2627 * state (removing it's L1 piece) until the header is
2628 * done being written to the l2arc.
2630 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2631 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2632 return (bytes_evicted);
2635 ARCSTAT_BUMP(arcstat_deleted);
2636 bytes_evicted += hdr->b_size;
2638 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2640 if (HDR_HAS_L2HDR(hdr)) {
2642 * This buffer is cached on the 2nd Level ARC;
2643 * don't destroy the header.
2645 arc_change_state(arc_l2c_only, hdr, hash_lock);
2647 * dropping from L1+L2 cached to L2-only,
2648 * realloc to remove the L1 header.
2650 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2653 arc_change_state(arc_anon, hdr, hash_lock);
2654 arc_hdr_destroy(hdr);
2656 return (bytes_evicted);
2659 ASSERT(state == arc_mru || state == arc_mfu);
2660 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2662 /* prefetch buffers have a minimum lifespan */
2663 if (HDR_IO_IN_PROGRESS(hdr) ||
2664 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2665 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2666 arc_min_prefetch_lifespan)) {
2667 ARCSTAT_BUMP(arcstat_evict_skip);
2668 return (bytes_evicted);
2671 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2672 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2673 while (hdr->b_l1hdr.b_buf) {
2674 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2675 if (!mutex_tryenter(&buf->b_evict_lock)) {
2676 ARCSTAT_BUMP(arcstat_mutex_miss);
2679 if (buf->b_data != NULL)
2680 bytes_evicted += hdr->b_size;
2681 if (buf->b_efunc != NULL) {
2682 mutex_enter(&arc_user_evicts_lock);
2683 arc_buf_destroy(buf, FALSE);
2684 hdr->b_l1hdr.b_buf = buf->b_next;
2685 buf->b_hdr = &arc_eviction_hdr;
2686 buf->b_next = arc_eviction_list;
2687 arc_eviction_list = buf;
2688 cv_signal(&arc_user_evicts_cv);
2689 mutex_exit(&arc_user_evicts_lock);
2690 mutex_exit(&buf->b_evict_lock);
2692 mutex_exit(&buf->b_evict_lock);
2693 arc_buf_destroy(buf, TRUE);
2697 if (HDR_HAS_L2HDR(hdr)) {
2698 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2700 if (l2arc_write_eligible(hdr->b_spa, hdr))
2701 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2703 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2706 if (hdr->b_l1hdr.b_datacnt == 0) {
2707 arc_change_state(evicted_state, hdr, hash_lock);
2708 ASSERT(HDR_IN_HASH_TABLE(hdr));
2709 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2710 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2711 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2714 return (bytes_evicted);
2718 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2719 uint64_t spa, int64_t bytes)
2721 multilist_sublist_t *mls;
2722 uint64_t bytes_evicted = 0;
2724 kmutex_t *hash_lock;
2725 int evict_count = 0;
2727 ASSERT3P(marker, !=, NULL);
2728 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2730 mls = multilist_sublist_lock(ml, idx);
2732 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2733 hdr = multilist_sublist_prev(mls, marker)) {
2734 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2735 (evict_count >= zfs_arc_evict_batch_limit))
2739 * To keep our iteration location, move the marker
2740 * forward. Since we're not holding hdr's hash lock, we
2741 * must be very careful and not remove 'hdr' from the
2742 * sublist. Otherwise, other consumers might mistake the
2743 * 'hdr' as not being on a sublist when they call the
2744 * multilist_link_active() function (they all rely on
2745 * the hash lock protecting concurrent insertions and
2746 * removals). multilist_sublist_move_forward() was
2747 * specifically implemented to ensure this is the case
2748 * (only 'marker' will be removed and re-inserted).
2750 multilist_sublist_move_forward(mls, marker);
2753 * The only case where the b_spa field should ever be
2754 * zero, is the marker headers inserted by
2755 * arc_evict_state(). It's possible for multiple threads
2756 * to be calling arc_evict_state() concurrently (e.g.
2757 * dsl_pool_close() and zio_inject_fault()), so we must
2758 * skip any markers we see from these other threads.
2760 if (hdr->b_spa == 0)
2763 /* we're only interested in evicting buffers of a certain spa */
2764 if (spa != 0 && hdr->b_spa != spa) {
2765 ARCSTAT_BUMP(arcstat_evict_skip);
2769 hash_lock = HDR_LOCK(hdr);
2772 * We aren't calling this function from any code path
2773 * that would already be holding a hash lock, so we're
2774 * asserting on this assumption to be defensive in case
2775 * this ever changes. Without this check, it would be
2776 * possible to incorrectly increment arcstat_mutex_miss
2777 * below (e.g. if the code changed such that we called
2778 * this function with a hash lock held).
2780 ASSERT(!MUTEX_HELD(hash_lock));
2782 if (mutex_tryenter(hash_lock)) {
2783 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2784 mutex_exit(hash_lock);
2786 bytes_evicted += evicted;
2789 * If evicted is zero, arc_evict_hdr() must have
2790 * decided to skip this header, don't increment
2791 * evict_count in this case.
2797 * If arc_size isn't overflowing, signal any
2798 * threads that might happen to be waiting.
2800 * For each header evicted, we wake up a single
2801 * thread. If we used cv_broadcast, we could
2802 * wake up "too many" threads causing arc_size
2803 * to significantly overflow arc_c; since
2804 * arc_get_data_buf() doesn't check for overflow
2805 * when it's woken up (it doesn't because it's
2806 * possible for the ARC to be overflowing while
2807 * full of un-evictable buffers, and the
2808 * function should proceed in this case).
2810 * If threads are left sleeping, due to not
2811 * using cv_broadcast, they will be woken up
2812 * just before arc_reclaim_thread() sleeps.
2814 mutex_enter(&arc_reclaim_lock);
2815 if (!arc_is_overflowing())
2816 cv_signal(&arc_reclaim_waiters_cv);
2817 mutex_exit(&arc_reclaim_lock);
2819 ARCSTAT_BUMP(arcstat_mutex_miss);
2823 multilist_sublist_unlock(mls);
2825 return (bytes_evicted);
2829 * Evict buffers from the given arc state, until we've removed the
2830 * specified number of bytes. Move the removed buffers to the
2831 * appropriate evict state.
2833 * This function makes a "best effort". It skips over any buffers
2834 * it can't get a hash_lock on, and so, may not catch all candidates.
2835 * It may also return without evicting as much space as requested.
2837 * If bytes is specified using the special value ARC_EVICT_ALL, this
2838 * will evict all available (i.e. unlocked and evictable) buffers from
2839 * the given arc state; which is used by arc_flush().
2842 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2843 arc_buf_contents_t type)
2845 uint64_t total_evicted = 0;
2846 multilist_t *ml = &state->arcs_list[type];
2848 arc_buf_hdr_t **markers;
2850 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2852 num_sublists = multilist_get_num_sublists(ml);
2855 * If we've tried to evict from each sublist, made some
2856 * progress, but still have not hit the target number of bytes
2857 * to evict, we want to keep trying. The markers allow us to
2858 * pick up where we left off for each individual sublist, rather
2859 * than starting from the tail each time.
2861 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2862 for (int i = 0; i < num_sublists; i++) {
2863 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2866 * A b_spa of 0 is used to indicate that this header is
2867 * a marker. This fact is used in arc_adjust_type() and
2868 * arc_evict_state_impl().
2870 markers[i]->b_spa = 0;
2872 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2873 multilist_sublist_insert_tail(mls, markers[i]);
2874 multilist_sublist_unlock(mls);
2878 * While we haven't hit our target number of bytes to evict, or
2879 * we're evicting all available buffers.
2881 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2883 * Start eviction using a randomly selected sublist,
2884 * this is to try and evenly balance eviction across all
2885 * sublists. Always starting at the same sublist
2886 * (e.g. index 0) would cause evictions to favor certain
2887 * sublists over others.
2889 int sublist_idx = multilist_get_random_index(ml);
2890 uint64_t scan_evicted = 0;
2892 for (int i = 0; i < num_sublists; i++) {
2893 uint64_t bytes_remaining;
2894 uint64_t bytes_evicted;
2896 if (bytes == ARC_EVICT_ALL)
2897 bytes_remaining = ARC_EVICT_ALL;
2898 else if (total_evicted < bytes)
2899 bytes_remaining = bytes - total_evicted;
2903 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2904 markers[sublist_idx], spa, bytes_remaining);
2906 scan_evicted += bytes_evicted;
2907 total_evicted += bytes_evicted;
2909 /* we've reached the end, wrap to the beginning */
2910 if (++sublist_idx >= num_sublists)
2915 * If we didn't evict anything during this scan, we have
2916 * no reason to believe we'll evict more during another
2917 * scan, so break the loop.
2919 if (scan_evicted == 0) {
2920 /* This isn't possible, let's make that obvious */
2921 ASSERT3S(bytes, !=, 0);
2924 * When bytes is ARC_EVICT_ALL, the only way to
2925 * break the loop is when scan_evicted is zero.
2926 * In that case, we actually have evicted enough,
2927 * so we don't want to increment the kstat.
2929 if (bytes != ARC_EVICT_ALL) {
2930 ASSERT3S(total_evicted, <, bytes);
2931 ARCSTAT_BUMP(arcstat_evict_not_enough);
2938 for (int i = 0; i < num_sublists; i++) {
2939 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2940 multilist_sublist_remove(mls, markers[i]);
2941 multilist_sublist_unlock(mls);
2943 kmem_cache_free(hdr_full_cache, markers[i]);
2945 kmem_free(markers, sizeof (*markers) * num_sublists);
2947 return (total_evicted);
2951 * Flush all "evictable" data of the given type from the arc state
2952 * specified. This will not evict any "active" buffers (i.e. referenced).
2954 * When 'retry' is set to FALSE, the function will make a single pass
2955 * over the state and evict any buffers that it can. Since it doesn't
2956 * continually retry the eviction, it might end up leaving some buffers
2957 * in the ARC due to lock misses.
2959 * When 'retry' is set to TRUE, the function will continually retry the
2960 * eviction until *all* evictable buffers have been removed from the
2961 * state. As a result, if concurrent insertions into the state are
2962 * allowed (e.g. if the ARC isn't shutting down), this function might
2963 * wind up in an infinite loop, continually trying to evict buffers.
2966 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2969 uint64_t evicted = 0;
2971 while (state->arcs_lsize[type] != 0) {
2972 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2982 * Evict the specified number of bytes from the state specified,
2983 * restricting eviction to the spa and type given. This function
2984 * prevents us from trying to evict more from a state's list than
2985 * is "evictable", and to skip evicting altogether when passed a
2986 * negative value for "bytes". In contrast, arc_evict_state() will
2987 * evict everything it can, when passed a negative value for "bytes".
2990 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2991 arc_buf_contents_t type)
2995 if (bytes > 0 && state->arcs_lsize[type] > 0) {
2996 delta = MIN(state->arcs_lsize[type], bytes);
2997 return (arc_evict_state(state, spa, delta, type));
3004 * Evict metadata buffers from the cache, such that arc_meta_used is
3005 * capped by the arc_meta_limit tunable.
3008 arc_adjust_meta(void)
3010 uint64_t total_evicted = 0;
3014 * If we're over the meta limit, we want to evict enough
3015 * metadata to get back under the meta limit. We don't want to
3016 * evict so much that we drop the MRU below arc_p, though. If
3017 * we're over the meta limit more than we're over arc_p, we
3018 * evict some from the MRU here, and some from the MFU below.
3020 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3021 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3022 refcount_count(&arc_mru->arcs_size) - arc_p));
3024 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3027 * Similar to the above, we want to evict enough bytes to get us
3028 * below the meta limit, but not so much as to drop us below the
3029 * space alloted to the MFU (which is defined as arc_c - arc_p).
3031 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3032 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3034 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3036 return (total_evicted);
3040 * Return the type of the oldest buffer in the given arc state
3042 * This function will select a random sublist of type ARC_BUFC_DATA and
3043 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3044 * is compared, and the type which contains the "older" buffer will be
3047 static arc_buf_contents_t
3048 arc_adjust_type(arc_state_t *state)
3050 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3051 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3052 int data_idx = multilist_get_random_index(data_ml);
3053 int meta_idx = multilist_get_random_index(meta_ml);
3054 multilist_sublist_t *data_mls;
3055 multilist_sublist_t *meta_mls;
3056 arc_buf_contents_t type;
3057 arc_buf_hdr_t *data_hdr;
3058 arc_buf_hdr_t *meta_hdr;
3061 * We keep the sublist lock until we're finished, to prevent
3062 * the headers from being destroyed via arc_evict_state().
3064 data_mls = multilist_sublist_lock(data_ml, data_idx);
3065 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3068 * These two loops are to ensure we skip any markers that
3069 * might be at the tail of the lists due to arc_evict_state().
3072 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3073 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3074 if (data_hdr->b_spa != 0)
3078 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3079 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3080 if (meta_hdr->b_spa != 0)
3084 if (data_hdr == NULL && meta_hdr == NULL) {
3085 type = ARC_BUFC_DATA;
3086 } else if (data_hdr == NULL) {
3087 ASSERT3P(meta_hdr, !=, NULL);
3088 type = ARC_BUFC_METADATA;
3089 } else if (meta_hdr == NULL) {
3090 ASSERT3P(data_hdr, !=, NULL);
3091 type = ARC_BUFC_DATA;
3093 ASSERT3P(data_hdr, !=, NULL);
3094 ASSERT3P(meta_hdr, !=, NULL);
3096 /* The headers can't be on the sublist without an L1 header */
3097 ASSERT(HDR_HAS_L1HDR(data_hdr));
3098 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3100 if (data_hdr->b_l1hdr.b_arc_access <
3101 meta_hdr->b_l1hdr.b_arc_access) {
3102 type = ARC_BUFC_DATA;
3104 type = ARC_BUFC_METADATA;
3108 multilist_sublist_unlock(meta_mls);
3109 multilist_sublist_unlock(data_mls);
3115 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3120 uint64_t total_evicted = 0;
3125 * If we're over arc_meta_limit, we want to correct that before
3126 * potentially evicting data buffers below.
3128 total_evicted += arc_adjust_meta();
3133 * If we're over the target cache size, we want to evict enough
3134 * from the list to get back to our target size. We don't want
3135 * to evict too much from the MRU, such that it drops below
3136 * arc_p. So, if we're over our target cache size more than
3137 * the MRU is over arc_p, we'll evict enough to get back to
3138 * arc_p here, and then evict more from the MFU below.
3140 target = MIN((int64_t)(arc_size - arc_c),
3141 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3142 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3145 * If we're below arc_meta_min, always prefer to evict data.
3146 * Otherwise, try to satisfy the requested number of bytes to
3147 * evict from the type which contains older buffers; in an
3148 * effort to keep newer buffers in the cache regardless of their
3149 * type. If we cannot satisfy the number of bytes from this
3150 * type, spill over into the next type.
3152 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3153 arc_meta_used > arc_meta_min) {
3154 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3155 total_evicted += bytes;
3158 * If we couldn't evict our target number of bytes from
3159 * metadata, we try to get the rest from data.
3164 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3166 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3167 total_evicted += bytes;
3170 * If we couldn't evict our target number of bytes from
3171 * data, we try to get the rest from metadata.
3176 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3182 * Now that we've tried to evict enough from the MRU to get its
3183 * size back to arc_p, if we're still above the target cache
3184 * size, we evict the rest from the MFU.
3186 target = arc_size - arc_c;
3188 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3189 arc_meta_used > arc_meta_min) {
3190 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3191 total_evicted += bytes;
3194 * If we couldn't evict our target number of bytes from
3195 * metadata, we try to get the rest from data.
3200 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3202 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3203 total_evicted += bytes;
3206 * If we couldn't evict our target number of bytes from
3207 * data, we try to get the rest from data.
3212 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3216 * Adjust ghost lists
3218 * In addition to the above, the ARC also defines target values
3219 * for the ghost lists. The sum of the mru list and mru ghost
3220 * list should never exceed the target size of the cache, and
3221 * the sum of the mru list, mfu list, mru ghost list, and mfu
3222 * ghost list should never exceed twice the target size of the
3223 * cache. The following logic enforces these limits on the ghost
3224 * caches, and evicts from them as needed.
3226 target = refcount_count(&arc_mru->arcs_size) +
3227 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3229 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3230 total_evicted += bytes;
3235 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3238 * We assume the sum of the mru list and mfu list is less than
3239 * or equal to arc_c (we enforced this above), which means we
3240 * can use the simpler of the two equations below:
3242 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3243 * mru ghost + mfu ghost <= arc_c
3245 target = refcount_count(&arc_mru_ghost->arcs_size) +
3246 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3248 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3249 total_evicted += bytes;
3254 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3256 return (total_evicted);
3260 arc_do_user_evicts(void)
3262 mutex_enter(&arc_user_evicts_lock);
3263 while (arc_eviction_list != NULL) {
3264 arc_buf_t *buf = arc_eviction_list;
3265 arc_eviction_list = buf->b_next;
3266 mutex_enter(&buf->b_evict_lock);
3268 mutex_exit(&buf->b_evict_lock);
3269 mutex_exit(&arc_user_evicts_lock);
3271 if (buf->b_efunc != NULL)
3272 VERIFY0(buf->b_efunc(buf->b_private));
3274 buf->b_efunc = NULL;
3275 buf->b_private = NULL;
3276 kmem_cache_free(buf_cache, buf);
3277 mutex_enter(&arc_user_evicts_lock);
3279 mutex_exit(&arc_user_evicts_lock);
3283 arc_flush(spa_t *spa, boolean_t retry)
3288 * If retry is TRUE, a spa must not be specified since we have
3289 * no good way to determine if all of a spa's buffers have been
3290 * evicted from an arc state.
3292 ASSERT(!retry || spa == 0);
3295 guid = spa_load_guid(spa);
3297 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3298 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3300 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3301 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3303 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3304 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3306 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3307 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3309 arc_do_user_evicts();
3310 ASSERT(spa || arc_eviction_list == NULL);
3314 arc_shrink(int64_t to_free)
3316 if (arc_c > arc_c_min) {
3317 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3318 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3319 if (arc_c > arc_c_min + to_free)
3320 atomic_add_64(&arc_c, -to_free);
3324 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3325 if (arc_c > arc_size)
3326 arc_c = MAX(arc_size, arc_c_min);
3328 arc_p = (arc_c >> 1);
3330 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3333 ASSERT(arc_c >= arc_c_min);
3334 ASSERT((int64_t)arc_p >= 0);
3337 if (arc_size > arc_c) {
3338 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3340 (void) arc_adjust();
3344 static long needfree = 0;
3346 typedef enum free_memory_reason_t {
3351 FMR_PAGES_PP_MAXIMUM,
3355 } free_memory_reason_t;
3357 int64_t last_free_memory;
3358 free_memory_reason_t last_free_reason;
3361 * Additional reserve of pages for pp_reserve.
3363 int64_t arc_pages_pp_reserve = 64;
3366 * Additional reserve of pages for swapfs.
3368 int64_t arc_swapfs_reserve = 64;
3371 * Return the amount of memory that can be consumed before reclaim will be
3372 * needed. Positive if there is sufficient free memory, negative indicates
3373 * the amount of memory that needs to be freed up.
3376 arc_available_memory(void)
3378 int64_t lowest = INT64_MAX;
3380 free_memory_reason_t r = FMR_UNKNOWN;
3384 n = PAGESIZE * (-needfree);
3392 * Cooperate with pagedaemon when it's time for it to scan
3393 * and reclaim some pages.
3395 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3403 * check that we're out of range of the pageout scanner. It starts to
3404 * schedule paging if freemem is less than lotsfree and needfree.
3405 * lotsfree is the high-water mark for pageout, and needfree is the
3406 * number of needed free pages. We add extra pages here to make sure
3407 * the scanner doesn't start up while we're freeing memory.
3409 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3416 * check to make sure that swapfs has enough space so that anon
3417 * reservations can still succeed. anon_resvmem() checks that the
3418 * availrmem is greater than swapfs_minfree, and the number of reserved
3419 * swap pages. We also add a bit of extra here just to prevent
3420 * circumstances from getting really dire.
3422 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3423 desfree - arc_swapfs_reserve);
3426 r = FMR_SWAPFS_MINFREE;
3431 * Check that we have enough availrmem that memory locking (e.g., via
3432 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3433 * stores the number of pages that cannot be locked; when availrmem
3434 * drops below pages_pp_maximum, page locking mechanisms such as
3435 * page_pp_lock() will fail.)
3437 n = PAGESIZE * (availrmem - pages_pp_maximum -
3438 arc_pages_pp_reserve);
3441 r = FMR_PAGES_PP_MAXIMUM;
3445 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3447 * If we're on an i386 platform, it's possible that we'll exhaust the
3448 * kernel heap space before we ever run out of available physical
3449 * memory. Most checks of the size of the heap_area compare against
3450 * tune.t_minarmem, which is the minimum available real memory that we
3451 * can have in the system. However, this is generally fixed at 25 pages
3452 * which is so low that it's useless. In this comparison, we seek to
3453 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3454 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3457 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3458 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3463 #define zio_arena NULL
3465 #define zio_arena heap_arena
3469 * If zio data pages are being allocated out of a separate heap segment,
3470 * then enforce that the size of available vmem for this arena remains
3471 * above about 1/16th free.
3473 * Note: The 1/16th arena free requirement was put in place
3474 * to aggressively evict memory from the arc in order to avoid
3475 * memory fragmentation issues.
3477 if (zio_arena != NULL) {
3478 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3479 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3487 * Above limits know nothing about real level of KVA fragmentation.
3488 * Start aggressive reclamation if too little sequential KVA left.
3491 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3492 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3501 /* Every 100 calls, free a small amount */
3502 if (spa_get_random(100) == 0)
3504 #endif /* _KERNEL */
3506 last_free_memory = lowest;
3507 last_free_reason = r;
3508 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3514 * Determine if the system is under memory pressure and is asking
3515 * to reclaim memory. A return value of TRUE indicates that the system
3516 * is under memory pressure and that the arc should adjust accordingly.
3519 arc_reclaim_needed(void)
3521 return (arc_available_memory() < 0);
3524 extern kmem_cache_t *zio_buf_cache[];
3525 extern kmem_cache_t *zio_data_buf_cache[];
3526 extern kmem_cache_t *range_seg_cache;
3528 static __noinline void
3529 arc_kmem_reap_now(void)
3532 kmem_cache_t *prev_cache = NULL;
3533 kmem_cache_t *prev_data_cache = NULL;
3535 DTRACE_PROBE(arc__kmem_reap_start);
3537 if (arc_meta_used >= arc_meta_limit) {
3539 * We are exceeding our meta-data cache limit.
3540 * Purge some DNLC entries to release holds on meta-data.
3542 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3546 * Reclaim unused memory from all kmem caches.
3552 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3553 if (zio_buf_cache[i] != prev_cache) {
3554 prev_cache = zio_buf_cache[i];
3555 kmem_cache_reap_now(zio_buf_cache[i]);
3557 if (zio_data_buf_cache[i] != prev_data_cache) {
3558 prev_data_cache = zio_data_buf_cache[i];
3559 kmem_cache_reap_now(zio_data_buf_cache[i]);
3562 kmem_cache_reap_now(buf_cache);
3563 kmem_cache_reap_now(hdr_full_cache);
3564 kmem_cache_reap_now(hdr_l2only_cache);
3565 kmem_cache_reap_now(range_seg_cache);
3568 if (zio_arena != NULL) {
3570 * Ask the vmem arena to reclaim unused memory from its
3573 vmem_qcache_reap(zio_arena);
3576 DTRACE_PROBE(arc__kmem_reap_end);
3580 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3581 * enough data and signal them to proceed. When this happens, the threads in
3582 * arc_get_data_buf() are sleeping while holding the hash lock for their
3583 * particular arc header. Thus, we must be careful to never sleep on a
3584 * hash lock in this thread. This is to prevent the following deadlock:
3586 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3587 * waiting for the reclaim thread to signal it.
3589 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3590 * fails, and goes to sleep forever.
3592 * This possible deadlock is avoided by always acquiring a hash lock
3593 * using mutex_tryenter() from arc_reclaim_thread().
3596 arc_reclaim_thread(void *dummy __unused)
3598 clock_t growtime = 0;
3601 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3603 mutex_enter(&arc_reclaim_lock);
3604 while (!arc_reclaim_thread_exit) {
3605 int64_t free_memory = arc_available_memory();
3606 uint64_t evicted = 0;
3608 mutex_exit(&arc_reclaim_lock);
3610 if (free_memory < 0) {
3612 arc_no_grow = B_TRUE;
3616 * Wait at least zfs_grow_retry (default 60) seconds
3617 * before considering growing.
3619 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3621 arc_kmem_reap_now();
3624 * If we are still low on memory, shrink the ARC
3625 * so that we have arc_shrink_min free space.
3627 free_memory = arc_available_memory();
3630 (arc_c >> arc_shrink_shift) - free_memory;
3633 to_free = MAX(to_free, ptob(needfree));
3635 arc_shrink(to_free);
3637 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3638 arc_no_grow = B_TRUE;
3639 } else if (ddi_get_lbolt() >= growtime) {
3640 arc_no_grow = B_FALSE;
3643 evicted = arc_adjust();
3645 mutex_enter(&arc_reclaim_lock);
3648 * If evicted is zero, we couldn't evict anything via
3649 * arc_adjust(). This could be due to hash lock
3650 * collisions, but more likely due to the majority of
3651 * arc buffers being unevictable. Therefore, even if
3652 * arc_size is above arc_c, another pass is unlikely to
3653 * be helpful and could potentially cause us to enter an
3656 if (arc_size <= arc_c || evicted == 0) {
3661 * We're either no longer overflowing, or we
3662 * can't evict anything more, so we should wake
3663 * up any threads before we go to sleep.
3665 cv_broadcast(&arc_reclaim_waiters_cv);
3668 * Block until signaled, or after one second (we
3669 * might need to perform arc_kmem_reap_now()
3670 * even if we aren't being signalled)
3672 CALLB_CPR_SAFE_BEGIN(&cpr);
3673 (void) cv_timedwait(&arc_reclaim_thread_cv,
3674 &arc_reclaim_lock, hz);
3675 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3679 arc_reclaim_thread_exit = FALSE;
3680 cv_broadcast(&arc_reclaim_thread_cv);
3681 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3686 arc_user_evicts_thread(void *dummy __unused)
3690 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3692 mutex_enter(&arc_user_evicts_lock);
3693 while (!arc_user_evicts_thread_exit) {
3694 mutex_exit(&arc_user_evicts_lock);
3696 arc_do_user_evicts();
3699 * This is necessary in order for the mdb ::arc dcmd to
3700 * show up to date information. Since the ::arc command
3701 * does not call the kstat's update function, without
3702 * this call, the command may show stale stats for the
3703 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3704 * with this change, the data might be up to 1 second
3705 * out of date; but that should suffice. The arc_state_t
3706 * structures can be queried directly if more accurate
3707 * information is needed.
3709 if (arc_ksp != NULL)
3710 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3712 mutex_enter(&arc_user_evicts_lock);
3715 * Block until signaled, or after one second (we need to
3716 * call the arc's kstat update function regularly).
3718 CALLB_CPR_SAFE_BEGIN(&cpr);
3719 (void) cv_timedwait(&arc_user_evicts_cv,
3720 &arc_user_evicts_lock, hz);
3721 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3724 arc_user_evicts_thread_exit = FALSE;
3725 cv_broadcast(&arc_user_evicts_cv);
3726 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3731 * Adapt arc info given the number of bytes we are trying to add and
3732 * the state that we are comming from. This function is only called
3733 * when we are adding new content to the cache.
3736 arc_adapt(int bytes, arc_state_t *state)
3739 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3740 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3741 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3743 if (state == arc_l2c_only)
3748 * Adapt the target size of the MRU list:
3749 * - if we just hit in the MRU ghost list, then increase
3750 * the target size of the MRU list.
3751 * - if we just hit in the MFU ghost list, then increase
3752 * the target size of the MFU list by decreasing the
3753 * target size of the MRU list.
3755 if (state == arc_mru_ghost) {
3756 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3757 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3759 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3760 } else if (state == arc_mfu_ghost) {
3763 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3764 mult = MIN(mult, 10);
3766 delta = MIN(bytes * mult, arc_p);
3767 arc_p = MAX(arc_p_min, arc_p - delta);
3769 ASSERT((int64_t)arc_p >= 0);
3771 if (arc_reclaim_needed()) {
3772 cv_signal(&arc_reclaim_thread_cv);
3779 if (arc_c >= arc_c_max)
3783 * If we're within (2 * maxblocksize) bytes of the target
3784 * cache size, increment the target cache size
3786 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3787 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3788 atomic_add_64(&arc_c, (int64_t)bytes);
3789 if (arc_c > arc_c_max)
3791 else if (state == arc_anon)
3792 atomic_add_64(&arc_p, (int64_t)bytes);
3796 ASSERT((int64_t)arc_p >= 0);
3800 * Check if arc_size has grown past our upper threshold, determined by
3801 * zfs_arc_overflow_shift.
3804 arc_is_overflowing(void)
3806 /* Always allow at least one block of overflow */
3807 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3808 arc_c >> zfs_arc_overflow_shift);
3810 return (arc_size >= arc_c + overflow);
3814 * The buffer, supplied as the first argument, needs a data block. If we
3815 * are hitting the hard limit for the cache size, we must sleep, waiting
3816 * for the eviction thread to catch up. If we're past the target size
3817 * but below the hard limit, we'll only signal the reclaim thread and
3821 arc_get_data_buf(arc_buf_t *buf)
3823 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3824 uint64_t size = buf->b_hdr->b_size;
3825 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3827 arc_adapt(size, state);
3830 * If arc_size is currently overflowing, and has grown past our
3831 * upper limit, we must be adding data faster than the evict
3832 * thread can evict. Thus, to ensure we don't compound the
3833 * problem by adding more data and forcing arc_size to grow even
3834 * further past it's target size, we halt and wait for the
3835 * eviction thread to catch up.
3837 * It's also possible that the reclaim thread is unable to evict
3838 * enough buffers to get arc_size below the overflow limit (e.g.
3839 * due to buffers being un-evictable, or hash lock collisions).
3840 * In this case, we want to proceed regardless if we're
3841 * overflowing; thus we don't use a while loop here.
3843 if (arc_is_overflowing()) {
3844 mutex_enter(&arc_reclaim_lock);
3847 * Now that we've acquired the lock, we may no longer be
3848 * over the overflow limit, lets check.
3850 * We're ignoring the case of spurious wake ups. If that
3851 * were to happen, it'd let this thread consume an ARC
3852 * buffer before it should have (i.e. before we're under
3853 * the overflow limit and were signalled by the reclaim
3854 * thread). As long as that is a rare occurrence, it
3855 * shouldn't cause any harm.
3857 if (arc_is_overflowing()) {
3858 cv_signal(&arc_reclaim_thread_cv);
3859 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3862 mutex_exit(&arc_reclaim_lock);
3865 if (type == ARC_BUFC_METADATA) {
3866 buf->b_data = zio_buf_alloc(size);
3867 arc_space_consume(size, ARC_SPACE_META);
3869 ASSERT(type == ARC_BUFC_DATA);
3870 buf->b_data = zio_data_buf_alloc(size);
3871 arc_space_consume(size, ARC_SPACE_DATA);
3875 * Update the state size. Note that ghost states have a
3876 * "ghost size" and so don't need to be updated.
3878 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3879 arc_buf_hdr_t *hdr = buf->b_hdr;
3880 arc_state_t *state = hdr->b_l1hdr.b_state;
3882 (void) refcount_add_many(&state->arcs_size, size, buf);
3885 * If this is reached via arc_read, the link is
3886 * protected by the hash lock. If reached via
3887 * arc_buf_alloc, the header should not be accessed by
3888 * any other thread. And, if reached via arc_read_done,
3889 * the hash lock will protect it if it's found in the
3890 * hash table; otherwise no other thread should be
3891 * trying to [add|remove]_reference it.
3893 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3894 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3895 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3899 * If we are growing the cache, and we are adding anonymous
3900 * data, and we have outgrown arc_p, update arc_p
3902 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3903 (refcount_count(&arc_anon->arcs_size) +
3904 refcount_count(&arc_mru->arcs_size) > arc_p))
3905 arc_p = MIN(arc_c, arc_p + size);
3907 ARCSTAT_BUMP(arcstat_allocated);
3911 * This routine is called whenever a buffer is accessed.
3912 * NOTE: the hash lock is dropped in this function.
3915 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3919 ASSERT(MUTEX_HELD(hash_lock));
3920 ASSERT(HDR_HAS_L1HDR(hdr));
3922 if (hdr->b_l1hdr.b_state == arc_anon) {
3924 * This buffer is not in the cache, and does not
3925 * appear in our "ghost" list. Add the new buffer
3929 ASSERT0(hdr->b_l1hdr.b_arc_access);
3930 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3931 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3932 arc_change_state(arc_mru, hdr, hash_lock);
3934 } else if (hdr->b_l1hdr.b_state == arc_mru) {
3935 now = ddi_get_lbolt();
3938 * If this buffer is here because of a prefetch, then either:
3939 * - clear the flag if this is a "referencing" read
3940 * (any subsequent access will bump this into the MFU state).
3942 * - move the buffer to the head of the list if this is
3943 * another prefetch (to make it less likely to be evicted).
3945 if (HDR_PREFETCH(hdr)) {
3946 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3947 /* link protected by hash lock */
3948 ASSERT(multilist_link_active(
3949 &hdr->b_l1hdr.b_arc_node));
3951 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3952 ARCSTAT_BUMP(arcstat_mru_hits);
3954 hdr->b_l1hdr.b_arc_access = now;
3959 * This buffer has been "accessed" only once so far,
3960 * but it is still in the cache. Move it to the MFU
3963 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3965 * More than 125ms have passed since we
3966 * instantiated this buffer. Move it to the
3967 * most frequently used state.
3969 hdr->b_l1hdr.b_arc_access = now;
3970 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3971 arc_change_state(arc_mfu, hdr, hash_lock);
3973 ARCSTAT_BUMP(arcstat_mru_hits);
3974 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3975 arc_state_t *new_state;
3977 * This buffer has been "accessed" recently, but
3978 * was evicted from the cache. Move it to the
3982 if (HDR_PREFETCH(hdr)) {
3983 new_state = arc_mru;
3984 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3985 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3986 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3988 new_state = arc_mfu;
3989 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3992 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3993 arc_change_state(new_state, hdr, hash_lock);
3995 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3996 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
3998 * This buffer has been accessed more than once and is
3999 * still in the cache. Keep it in the MFU state.
4001 * NOTE: an add_reference() that occurred when we did
4002 * the arc_read() will have kicked this off the list.
4003 * If it was a prefetch, we will explicitly move it to
4004 * the head of the list now.
4006 if ((HDR_PREFETCH(hdr)) != 0) {
4007 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4008 /* link protected by hash_lock */
4009 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4011 ARCSTAT_BUMP(arcstat_mfu_hits);
4012 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4013 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4014 arc_state_t *new_state = arc_mfu;
4016 * This buffer has been accessed more than once but has
4017 * been evicted from the cache. Move it back to the
4021 if (HDR_PREFETCH(hdr)) {
4023 * This is a prefetch access...
4024 * move this block back to the MRU state.
4026 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4027 new_state = arc_mru;
4030 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4031 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4032 arc_change_state(new_state, hdr, hash_lock);
4034 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4035 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4037 * This buffer is on the 2nd Level ARC.
4040 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4041 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4042 arc_change_state(arc_mfu, hdr, hash_lock);
4044 ASSERT(!"invalid arc state");
4048 /* a generic arc_done_func_t which you can use */
4051 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4053 if (zio == NULL || zio->io_error == 0)
4054 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4055 VERIFY(arc_buf_remove_ref(buf, arg));
4058 /* a generic arc_done_func_t */
4060 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4062 arc_buf_t **bufp = arg;
4063 if (zio && zio->io_error) {
4064 VERIFY(arc_buf_remove_ref(buf, arg));
4068 ASSERT(buf->b_data);
4073 arc_read_done(zio_t *zio)
4077 arc_buf_t *abuf; /* buffer we're assigning to callback */
4078 kmutex_t *hash_lock = NULL;
4079 arc_callback_t *callback_list, *acb;
4080 int freeable = FALSE;
4082 buf = zio->io_private;
4086 * The hdr was inserted into hash-table and removed from lists
4087 * prior to starting I/O. We should find this header, since
4088 * it's in the hash table, and it should be legit since it's
4089 * not possible to evict it during the I/O. The only possible
4090 * reason for it not to be found is if we were freed during the
4093 if (HDR_IN_HASH_TABLE(hdr)) {
4094 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4095 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4096 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4097 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4098 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4100 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4103 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4104 hash_lock == NULL) ||
4106 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4107 (found == hdr && HDR_L2_READING(hdr)));
4110 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4111 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4112 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4114 /* byteswap if necessary */
4115 callback_list = hdr->b_l1hdr.b_acb;
4116 ASSERT(callback_list != NULL);
4117 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4118 dmu_object_byteswap_t bswap =
4119 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4120 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4121 byteswap_uint64_array :
4122 dmu_ot_byteswap[bswap].ob_func;
4123 func(buf->b_data, hdr->b_size);
4126 arc_cksum_compute(buf, B_FALSE);
4129 #endif /* illumos */
4131 if (hash_lock && zio->io_error == 0 &&
4132 hdr->b_l1hdr.b_state == arc_anon) {
4134 * Only call arc_access on anonymous buffers. This is because
4135 * if we've issued an I/O for an evicted buffer, we've already
4136 * called arc_access (to prevent any simultaneous readers from
4137 * getting confused).
4139 arc_access(hdr, hash_lock);
4142 /* create copies of the data buffer for the callers */
4144 for (acb = callback_list; acb; acb = acb->acb_next) {
4145 if (acb->acb_done) {
4147 ARCSTAT_BUMP(arcstat_duplicate_reads);
4148 abuf = arc_buf_clone(buf);
4150 acb->acb_buf = abuf;
4154 hdr->b_l1hdr.b_acb = NULL;
4155 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4156 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4158 ASSERT(buf->b_efunc == NULL);
4159 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4160 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4163 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4164 callback_list != NULL);
4166 if (zio->io_error != 0) {
4167 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4168 if (hdr->b_l1hdr.b_state != arc_anon)
4169 arc_change_state(arc_anon, hdr, hash_lock);
4170 if (HDR_IN_HASH_TABLE(hdr))
4171 buf_hash_remove(hdr);
4172 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4176 * Broadcast before we drop the hash_lock to avoid the possibility
4177 * that the hdr (and hence the cv) might be freed before we get to
4178 * the cv_broadcast().
4180 cv_broadcast(&hdr->b_l1hdr.b_cv);
4182 if (hash_lock != NULL) {
4183 mutex_exit(hash_lock);
4186 * This block was freed while we waited for the read to
4187 * complete. It has been removed from the hash table and
4188 * moved to the anonymous state (so that it won't show up
4191 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4192 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4195 /* execute each callback and free its structure */
4196 while ((acb = callback_list) != NULL) {
4198 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4200 if (acb->acb_zio_dummy != NULL) {
4201 acb->acb_zio_dummy->io_error = zio->io_error;
4202 zio_nowait(acb->acb_zio_dummy);
4205 callback_list = acb->acb_next;
4206 kmem_free(acb, sizeof (arc_callback_t));
4210 arc_hdr_destroy(hdr);
4214 * "Read" the block at the specified DVA (in bp) via the
4215 * cache. If the block is found in the cache, invoke the provided
4216 * callback immediately and return. Note that the `zio' parameter
4217 * in the callback will be NULL in this case, since no IO was
4218 * required. If the block is not in the cache pass the read request
4219 * on to the spa with a substitute callback function, so that the
4220 * requested block will be added to the cache.
4222 * If a read request arrives for a block that has a read in-progress,
4223 * either wait for the in-progress read to complete (and return the
4224 * results); or, if this is a read with a "done" func, add a record
4225 * to the read to invoke the "done" func when the read completes,
4226 * and return; or just return.
4228 * arc_read_done() will invoke all the requested "done" functions
4229 * for readers of this block.
4232 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4233 void *private, zio_priority_t priority, int zio_flags,
4234 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4236 arc_buf_hdr_t *hdr = NULL;
4237 arc_buf_t *buf = NULL;
4238 kmutex_t *hash_lock = NULL;
4240 uint64_t guid = spa_load_guid(spa);
4242 ASSERT(!BP_IS_EMBEDDED(bp) ||
4243 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4246 if (!BP_IS_EMBEDDED(bp)) {
4248 * Embedded BP's have no DVA and require no I/O to "read".
4249 * Create an anonymous arc buf to back it.
4251 hdr = buf_hash_find(guid, bp, &hash_lock);
4254 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4256 *arc_flags |= ARC_FLAG_CACHED;
4258 if (HDR_IO_IN_PROGRESS(hdr)) {
4260 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4261 priority == ZIO_PRIORITY_SYNC_READ) {
4263 * This sync read must wait for an
4264 * in-progress async read (e.g. a predictive
4265 * prefetch). Async reads are queued
4266 * separately at the vdev_queue layer, so
4267 * this is a form of priority inversion.
4268 * Ideally, we would "inherit" the demand
4269 * i/o's priority by moving the i/o from
4270 * the async queue to the synchronous queue,
4271 * but there is currently no mechanism to do
4272 * so. Track this so that we can evaluate
4273 * the magnitude of this potential performance
4276 * Note that if the prefetch i/o is already
4277 * active (has been issued to the device),
4278 * the prefetch improved performance, because
4279 * we issued it sooner than we would have
4280 * without the prefetch.
4282 DTRACE_PROBE1(arc__sync__wait__for__async,
4283 arc_buf_hdr_t *, hdr);
4284 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4286 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4287 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4290 if (*arc_flags & ARC_FLAG_WAIT) {
4291 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4292 mutex_exit(hash_lock);
4295 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4298 arc_callback_t *acb = NULL;
4300 acb = kmem_zalloc(sizeof (arc_callback_t),
4302 acb->acb_done = done;
4303 acb->acb_private = private;
4305 acb->acb_zio_dummy = zio_null(pio,
4306 spa, NULL, NULL, NULL, zio_flags);
4308 ASSERT(acb->acb_done != NULL);
4309 acb->acb_next = hdr->b_l1hdr.b_acb;
4310 hdr->b_l1hdr.b_acb = acb;
4311 add_reference(hdr, hash_lock, private);
4312 mutex_exit(hash_lock);
4315 mutex_exit(hash_lock);
4319 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4320 hdr->b_l1hdr.b_state == arc_mfu);
4323 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4325 * This is a demand read which does not have to
4326 * wait for i/o because we did a predictive
4327 * prefetch i/o for it, which has completed.
4330 arc__demand__hit__predictive__prefetch,
4331 arc_buf_hdr_t *, hdr);
4333 arcstat_demand_hit_predictive_prefetch);
4334 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4336 add_reference(hdr, hash_lock, private);
4338 * If this block is already in use, create a new
4339 * copy of the data so that we will be guaranteed
4340 * that arc_release() will always succeed.
4342 buf = hdr->b_l1hdr.b_buf;
4344 ASSERT(buf->b_data);
4345 if (HDR_BUF_AVAILABLE(hdr)) {
4346 ASSERT(buf->b_efunc == NULL);
4347 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4349 buf = arc_buf_clone(buf);
4352 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4353 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4354 hdr->b_flags |= ARC_FLAG_PREFETCH;
4356 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4357 arc_access(hdr, hash_lock);
4358 if (*arc_flags & ARC_FLAG_L2CACHE)
4359 hdr->b_flags |= ARC_FLAG_L2CACHE;
4360 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4361 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4362 mutex_exit(hash_lock);
4363 ARCSTAT_BUMP(arcstat_hits);
4364 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4365 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4366 data, metadata, hits);
4369 done(NULL, buf, private);
4371 uint64_t size = BP_GET_LSIZE(bp);
4372 arc_callback_t *acb;
4375 boolean_t devw = B_FALSE;
4376 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4377 int32_t b_asize = 0;
4380 /* this block is not in the cache */
4381 arc_buf_hdr_t *exists = NULL;
4382 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4383 buf = arc_buf_alloc(spa, size, private, type);
4385 if (!BP_IS_EMBEDDED(bp)) {
4386 hdr->b_dva = *BP_IDENTITY(bp);
4387 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4388 exists = buf_hash_insert(hdr, &hash_lock);
4390 if (exists != NULL) {
4391 /* somebody beat us to the hash insert */
4392 mutex_exit(hash_lock);
4393 buf_discard_identity(hdr);
4394 (void) arc_buf_remove_ref(buf, private);
4395 goto top; /* restart the IO request */
4399 * If there is a callback, we pass our reference to
4400 * it; otherwise we remove our reference.
4403 (void) remove_reference(hdr, hash_lock,
4406 if (*arc_flags & ARC_FLAG_PREFETCH)
4407 hdr->b_flags |= ARC_FLAG_PREFETCH;
4408 if (*arc_flags & ARC_FLAG_L2CACHE)
4409 hdr->b_flags |= ARC_FLAG_L2CACHE;
4410 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4411 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4412 if (BP_GET_LEVEL(bp) > 0)
4413 hdr->b_flags |= ARC_FLAG_INDIRECT;
4416 * This block is in the ghost cache. If it was L2-only
4417 * (and thus didn't have an L1 hdr), we realloc the
4418 * header to add an L1 hdr.
4420 if (!HDR_HAS_L1HDR(hdr)) {
4421 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4425 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4426 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4427 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4428 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4431 * If there is a callback, we pass a reference to it.
4434 add_reference(hdr, hash_lock, private);
4435 if (*arc_flags & ARC_FLAG_PREFETCH)
4436 hdr->b_flags |= ARC_FLAG_PREFETCH;
4437 if (*arc_flags & ARC_FLAG_L2CACHE)
4438 hdr->b_flags |= ARC_FLAG_L2CACHE;
4439 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4440 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4441 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4444 buf->b_efunc = NULL;
4445 buf->b_private = NULL;
4447 hdr->b_l1hdr.b_buf = buf;
4448 ASSERT0(hdr->b_l1hdr.b_datacnt);
4449 hdr->b_l1hdr.b_datacnt = 1;
4450 arc_get_data_buf(buf);
4451 arc_access(hdr, hash_lock);
4454 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4455 hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
4456 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4458 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4459 acb->acb_done = done;
4460 acb->acb_private = private;
4462 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4463 hdr->b_l1hdr.b_acb = acb;
4464 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4466 if (HDR_HAS_L2HDR(hdr) &&
4467 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4468 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4469 addr = hdr->b_l2hdr.b_daddr;
4470 b_compress = HDR_GET_COMPRESS(hdr);
4471 b_asize = hdr->b_l2hdr.b_asize;
4473 * Lock out device removal.
4475 if (vdev_is_dead(vd) ||
4476 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4480 if (hash_lock != NULL)
4481 mutex_exit(hash_lock);
4484 * At this point, we have a level 1 cache miss. Try again in
4485 * L2ARC if possible.
4487 ASSERT3U(hdr->b_size, ==, size);
4488 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4489 uint64_t, size, zbookmark_phys_t *, zb);
4490 ARCSTAT_BUMP(arcstat_misses);
4491 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4492 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4493 data, metadata, misses);
4495 curthread->td_ru.ru_inblock++;
4498 if (priority == ZIO_PRIORITY_ASYNC_READ)
4499 hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4501 hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4503 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4505 * Read from the L2ARC if the following are true:
4506 * 1. The L2ARC vdev was previously cached.
4507 * 2. This buffer still has L2ARC metadata.
4508 * 3. This buffer isn't currently writing to the L2ARC.
4509 * 4. The L2ARC entry wasn't evicted, which may
4510 * also have invalidated the vdev.
4511 * 5. This isn't prefetch and l2arc_noprefetch is set.
4513 if (HDR_HAS_L2HDR(hdr) &&
4514 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4515 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4516 l2arc_read_callback_t *cb;
4518 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4519 ARCSTAT_BUMP(arcstat_l2_hits);
4521 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4523 cb->l2rcb_buf = buf;
4524 cb->l2rcb_spa = spa;
4527 cb->l2rcb_flags = zio_flags;
4528 cb->l2rcb_compress = b_compress;
4530 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4531 addr + size < vd->vdev_psize -
4532 VDEV_LABEL_END_SIZE);
4535 * l2arc read. The SCL_L2ARC lock will be
4536 * released by l2arc_read_done().
4537 * Issue a null zio if the underlying buffer
4538 * was squashed to zero size by compression.
4540 if (b_compress == ZIO_COMPRESS_EMPTY) {
4541 rzio = zio_null(pio, spa, vd,
4542 l2arc_read_done, cb,
4543 zio_flags | ZIO_FLAG_DONT_CACHE |
4545 ZIO_FLAG_DONT_PROPAGATE |
4546 ZIO_FLAG_DONT_RETRY);
4548 rzio = zio_read_phys(pio, vd, addr,
4549 b_asize, buf->b_data,
4551 l2arc_read_done, cb, priority,
4552 zio_flags | ZIO_FLAG_DONT_CACHE |
4554 ZIO_FLAG_DONT_PROPAGATE |
4555 ZIO_FLAG_DONT_RETRY, B_FALSE);
4557 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4559 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4561 if (*arc_flags & ARC_FLAG_NOWAIT) {
4566 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4567 if (zio_wait(rzio) == 0)
4570 /* l2arc read error; goto zio_read() */
4572 DTRACE_PROBE1(l2arc__miss,
4573 arc_buf_hdr_t *, hdr);
4574 ARCSTAT_BUMP(arcstat_l2_misses);
4575 if (HDR_L2_WRITING(hdr))
4576 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4577 spa_config_exit(spa, SCL_L2ARC, vd);
4581 spa_config_exit(spa, SCL_L2ARC, vd);
4582 if (l2arc_ndev != 0) {
4583 DTRACE_PROBE1(l2arc__miss,
4584 arc_buf_hdr_t *, hdr);
4585 ARCSTAT_BUMP(arcstat_l2_misses);
4589 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4590 arc_read_done, buf, priority, zio_flags, zb);
4592 if (*arc_flags & ARC_FLAG_WAIT)
4593 return (zio_wait(rzio));
4595 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4602 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4604 ASSERT(buf->b_hdr != NULL);
4605 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4606 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4608 ASSERT(buf->b_efunc == NULL);
4609 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4611 buf->b_efunc = func;
4612 buf->b_private = private;
4616 * Notify the arc that a block was freed, and thus will never be used again.
4619 arc_freed(spa_t *spa, const blkptr_t *bp)
4622 kmutex_t *hash_lock;
4623 uint64_t guid = spa_load_guid(spa);
4625 ASSERT(!BP_IS_EMBEDDED(bp));
4627 hdr = buf_hash_find(guid, bp, &hash_lock);
4630 if (HDR_BUF_AVAILABLE(hdr)) {
4631 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4632 add_reference(hdr, hash_lock, FTAG);
4633 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4634 mutex_exit(hash_lock);
4636 arc_release(buf, FTAG);
4637 (void) arc_buf_remove_ref(buf, FTAG);
4639 mutex_exit(hash_lock);
4645 * Clear the user eviction callback set by arc_set_callback(), first calling
4646 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4647 * clearing the callback may result in the arc_buf being destroyed. However,
4648 * it will not result in the *last* arc_buf being destroyed, hence the data
4649 * will remain cached in the ARC. We make a copy of the arc buffer here so
4650 * that we can process the callback without holding any locks.
4652 * It's possible that the callback is already in the process of being cleared
4653 * by another thread. In this case we can not clear the callback.
4655 * Returns B_TRUE if the callback was successfully called and cleared.
4658 arc_clear_callback(arc_buf_t *buf)
4661 kmutex_t *hash_lock;
4662 arc_evict_func_t *efunc = buf->b_efunc;
4663 void *private = buf->b_private;
4665 mutex_enter(&buf->b_evict_lock);
4669 * We are in arc_do_user_evicts().
4671 ASSERT(buf->b_data == NULL);
4672 mutex_exit(&buf->b_evict_lock);
4674 } else if (buf->b_data == NULL) {
4676 * We are on the eviction list; process this buffer now
4677 * but let arc_do_user_evicts() do the reaping.
4679 buf->b_efunc = NULL;
4680 mutex_exit(&buf->b_evict_lock);
4681 VERIFY0(efunc(private));
4684 hash_lock = HDR_LOCK(hdr);
4685 mutex_enter(hash_lock);
4687 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4689 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4690 hdr->b_l1hdr.b_datacnt);
4691 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4692 hdr->b_l1hdr.b_state == arc_mfu);
4694 buf->b_efunc = NULL;
4695 buf->b_private = NULL;
4697 if (hdr->b_l1hdr.b_datacnt > 1) {
4698 mutex_exit(&buf->b_evict_lock);
4699 arc_buf_destroy(buf, TRUE);
4701 ASSERT(buf == hdr->b_l1hdr.b_buf);
4702 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4703 mutex_exit(&buf->b_evict_lock);
4706 mutex_exit(hash_lock);
4707 VERIFY0(efunc(private));
4712 * Release this buffer from the cache, making it an anonymous buffer. This
4713 * must be done after a read and prior to modifying the buffer contents.
4714 * If the buffer has more than one reference, we must make
4715 * a new hdr for the buffer.
4718 arc_release(arc_buf_t *buf, void *tag)
4720 arc_buf_hdr_t *hdr = buf->b_hdr;
4723 * It would be nice to assert that if it's DMU metadata (level >
4724 * 0 || it's the dnode file), then it must be syncing context.
4725 * But we don't know that information at this level.
4728 mutex_enter(&buf->b_evict_lock);
4730 ASSERT(HDR_HAS_L1HDR(hdr));
4733 * We don't grab the hash lock prior to this check, because if
4734 * the buffer's header is in the arc_anon state, it won't be
4735 * linked into the hash table.
4737 if (hdr->b_l1hdr.b_state == arc_anon) {
4738 mutex_exit(&buf->b_evict_lock);
4739 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4740 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4741 ASSERT(!HDR_HAS_L2HDR(hdr));
4742 ASSERT(BUF_EMPTY(hdr));
4743 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4744 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4745 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4747 ASSERT3P(buf->b_efunc, ==, NULL);
4748 ASSERT3P(buf->b_private, ==, NULL);
4750 hdr->b_l1hdr.b_arc_access = 0;
4756 kmutex_t *hash_lock = HDR_LOCK(hdr);
4757 mutex_enter(hash_lock);
4760 * This assignment is only valid as long as the hash_lock is
4761 * held, we must be careful not to reference state or the
4762 * b_state field after dropping the lock.
4764 arc_state_t *state = hdr->b_l1hdr.b_state;
4765 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4766 ASSERT3P(state, !=, arc_anon);
4768 /* this buffer is not on any list */
4769 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4771 if (HDR_HAS_L2HDR(hdr)) {
4772 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4775 * We have to recheck this conditional again now that
4776 * we're holding the l2ad_mtx to prevent a race with
4777 * another thread which might be concurrently calling
4778 * l2arc_evict(). In that case, l2arc_evict() might have
4779 * destroyed the header's L2 portion as we were waiting
4780 * to acquire the l2ad_mtx.
4782 if (HDR_HAS_L2HDR(hdr)) {
4783 if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
4784 trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
4785 hdr->b_l2hdr.b_daddr,
4786 hdr->b_l2hdr.b_asize, 0);
4787 arc_hdr_l2hdr_destroy(hdr);
4790 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4794 * Do we have more than one buf?
4796 if (hdr->b_l1hdr.b_datacnt > 1) {
4797 arc_buf_hdr_t *nhdr;
4799 uint64_t blksz = hdr->b_size;
4800 uint64_t spa = hdr->b_spa;
4801 arc_buf_contents_t type = arc_buf_type(hdr);
4802 uint32_t flags = hdr->b_flags;
4804 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4806 * Pull the data off of this hdr and attach it to
4807 * a new anonymous hdr.
4809 (void) remove_reference(hdr, hash_lock, tag);
4810 bufp = &hdr->b_l1hdr.b_buf;
4811 while (*bufp != buf)
4812 bufp = &(*bufp)->b_next;
4813 *bufp = buf->b_next;
4816 ASSERT3P(state, !=, arc_l2c_only);
4818 (void) refcount_remove_many(
4819 &state->arcs_size, hdr->b_size, buf);
4821 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4822 ASSERT3P(state, !=, arc_l2c_only);
4823 uint64_t *size = &state->arcs_lsize[type];
4824 ASSERT3U(*size, >=, hdr->b_size);
4825 atomic_add_64(size, -hdr->b_size);
4829 * We're releasing a duplicate user data buffer, update
4830 * our statistics accordingly.
4832 if (HDR_ISTYPE_DATA(hdr)) {
4833 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4834 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4837 hdr->b_l1hdr.b_datacnt -= 1;
4838 arc_cksum_verify(buf);
4840 arc_buf_unwatch(buf);
4841 #endif /* illumos */
4843 mutex_exit(hash_lock);
4845 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4846 nhdr->b_size = blksz;
4849 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4850 nhdr->b_flags |= arc_bufc_to_flags(type);
4851 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4853 nhdr->b_l1hdr.b_buf = buf;
4854 nhdr->b_l1hdr.b_datacnt = 1;
4855 nhdr->b_l1hdr.b_state = arc_anon;
4856 nhdr->b_l1hdr.b_arc_access = 0;
4857 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4858 nhdr->b_freeze_cksum = NULL;
4860 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4862 mutex_exit(&buf->b_evict_lock);
4863 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4865 mutex_exit(&buf->b_evict_lock);
4866 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4867 /* protected by hash lock, or hdr is on arc_anon */
4868 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4869 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4870 arc_change_state(arc_anon, hdr, hash_lock);
4871 hdr->b_l1hdr.b_arc_access = 0;
4872 mutex_exit(hash_lock);
4874 buf_discard_identity(hdr);
4877 buf->b_efunc = NULL;
4878 buf->b_private = NULL;
4882 arc_released(arc_buf_t *buf)
4886 mutex_enter(&buf->b_evict_lock);
4887 released = (buf->b_data != NULL &&
4888 buf->b_hdr->b_l1hdr.b_state == arc_anon);
4889 mutex_exit(&buf->b_evict_lock);
4895 arc_referenced(arc_buf_t *buf)
4899 mutex_enter(&buf->b_evict_lock);
4900 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4901 mutex_exit(&buf->b_evict_lock);
4902 return (referenced);
4907 arc_write_ready(zio_t *zio)
4909 arc_write_callback_t *callback = zio->io_private;
4910 arc_buf_t *buf = callback->awcb_buf;
4911 arc_buf_hdr_t *hdr = buf->b_hdr;
4913 ASSERT(HDR_HAS_L1HDR(hdr));
4914 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4915 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4916 callback->awcb_ready(zio, buf, callback->awcb_private);
4919 * If the IO is already in progress, then this is a re-write
4920 * attempt, so we need to thaw and re-compute the cksum.
4921 * It is the responsibility of the callback to handle the
4922 * accounting for any re-write attempt.
4924 if (HDR_IO_IN_PROGRESS(hdr)) {
4925 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4926 if (hdr->b_freeze_cksum != NULL) {
4927 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4928 hdr->b_freeze_cksum = NULL;
4930 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4932 arc_cksum_compute(buf, B_FALSE);
4933 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4937 * The SPA calls this callback for each physical write that happens on behalf
4938 * of a logical write. See the comment in dbuf_write_physdone() for details.
4941 arc_write_physdone(zio_t *zio)
4943 arc_write_callback_t *cb = zio->io_private;
4944 if (cb->awcb_physdone != NULL)
4945 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4949 arc_write_done(zio_t *zio)
4951 arc_write_callback_t *callback = zio->io_private;
4952 arc_buf_t *buf = callback->awcb_buf;
4953 arc_buf_hdr_t *hdr = buf->b_hdr;
4955 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4957 if (zio->io_error == 0) {
4958 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4959 buf_discard_identity(hdr);
4961 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4962 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4965 ASSERT(BUF_EMPTY(hdr));
4969 * If the block to be written was all-zero or compressed enough to be
4970 * embedded in the BP, no write was performed so there will be no
4971 * dva/birth/checksum. The buffer must therefore remain anonymous
4974 if (!BUF_EMPTY(hdr)) {
4975 arc_buf_hdr_t *exists;
4976 kmutex_t *hash_lock;
4978 ASSERT(zio->io_error == 0);
4980 arc_cksum_verify(buf);
4982 exists = buf_hash_insert(hdr, &hash_lock);
4983 if (exists != NULL) {
4985 * This can only happen if we overwrite for
4986 * sync-to-convergence, because we remove
4987 * buffers from the hash table when we arc_free().
4989 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4990 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4991 panic("bad overwrite, hdr=%p exists=%p",
4992 (void *)hdr, (void *)exists);
4993 ASSERT(refcount_is_zero(
4994 &exists->b_l1hdr.b_refcnt));
4995 arc_change_state(arc_anon, exists, hash_lock);
4996 mutex_exit(hash_lock);
4997 arc_hdr_destroy(exists);
4998 exists = buf_hash_insert(hdr, &hash_lock);
4999 ASSERT3P(exists, ==, NULL);
5000 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5002 ASSERT(zio->io_prop.zp_nopwrite);
5003 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5004 panic("bad nopwrite, hdr=%p exists=%p",
5005 (void *)hdr, (void *)exists);
5008 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5009 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5010 ASSERT(BP_GET_DEDUP(zio->io_bp));
5011 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5014 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5015 /* if it's not anon, we are doing a scrub */
5016 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5017 arc_access(hdr, hash_lock);
5018 mutex_exit(hash_lock);
5020 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5023 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5024 callback->awcb_done(zio, buf, callback->awcb_private);
5026 kmem_free(callback, sizeof (arc_write_callback_t));
5030 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
5031 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
5032 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
5033 arc_done_func_t *done, void *private, zio_priority_t priority,
5034 int zio_flags, const zbookmark_phys_t *zb)
5036 arc_buf_hdr_t *hdr = buf->b_hdr;
5037 arc_write_callback_t *callback;
5040 ASSERT(ready != NULL);
5041 ASSERT(done != NULL);
5042 ASSERT(!HDR_IO_ERROR(hdr));
5043 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5044 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5045 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5047 hdr->b_flags |= ARC_FLAG_L2CACHE;
5049 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
5050 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5051 callback->awcb_ready = ready;
5052 callback->awcb_physdone = physdone;
5053 callback->awcb_done = done;
5054 callback->awcb_private = private;
5055 callback->awcb_buf = buf;
5057 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
5058 arc_write_ready, arc_write_physdone, arc_write_done, callback,
5059 priority, zio_flags, zb);
5065 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5068 uint64_t available_memory = ptob(freemem);
5069 static uint64_t page_load = 0;
5070 static uint64_t last_txg = 0;
5072 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5074 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5077 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5080 if (txg > last_txg) {
5085 * If we are in pageout, we know that memory is already tight,
5086 * the arc is already going to be evicting, so we just want to
5087 * continue to let page writes occur as quickly as possible.
5089 if (curproc == pageproc) {
5090 if (page_load > MAX(ptob(minfree), available_memory) / 4)
5091 return (SET_ERROR(ERESTART));
5092 /* Note: reserve is inflated, so we deflate */
5093 page_load += reserve / 8;
5095 } else if (page_load > 0 && arc_reclaim_needed()) {
5096 /* memory is low, delay before restarting */
5097 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5098 return (SET_ERROR(EAGAIN));
5106 arc_tempreserve_clear(uint64_t reserve)
5108 atomic_add_64(&arc_tempreserve, -reserve);
5109 ASSERT((int64_t)arc_tempreserve >= 0);
5113 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5118 if (reserve > arc_c/4 && !arc_no_grow) {
5119 arc_c = MIN(arc_c_max, reserve * 4);
5120 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5122 if (reserve > arc_c)
5123 return (SET_ERROR(ENOMEM));
5126 * Don't count loaned bufs as in flight dirty data to prevent long
5127 * network delays from blocking transactions that are ready to be
5128 * assigned to a txg.
5130 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5131 arc_loaned_bytes), 0);
5134 * Writes will, almost always, require additional memory allocations
5135 * in order to compress/encrypt/etc the data. We therefore need to
5136 * make sure that there is sufficient available memory for this.
5138 error = arc_memory_throttle(reserve, txg);
5143 * Throttle writes when the amount of dirty data in the cache
5144 * gets too large. We try to keep the cache less than half full
5145 * of dirty blocks so that our sync times don't grow too large.
5146 * Note: if two requests come in concurrently, we might let them
5147 * both succeed, when one of them should fail. Not a huge deal.
5150 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5151 anon_size > arc_c / 4) {
5152 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5153 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5154 arc_tempreserve>>10,
5155 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5156 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5157 reserve>>10, arc_c>>10);
5158 return (SET_ERROR(ERESTART));
5160 atomic_add_64(&arc_tempreserve, reserve);
5165 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5166 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5168 size->value.ui64 = refcount_count(&state->arcs_size);
5169 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5170 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5174 arc_kstat_update(kstat_t *ksp, int rw)
5176 arc_stats_t *as = ksp->ks_data;
5178 if (rw == KSTAT_WRITE) {
5181 arc_kstat_update_state(arc_anon,
5182 &as->arcstat_anon_size,
5183 &as->arcstat_anon_evictable_data,
5184 &as->arcstat_anon_evictable_metadata);
5185 arc_kstat_update_state(arc_mru,
5186 &as->arcstat_mru_size,
5187 &as->arcstat_mru_evictable_data,
5188 &as->arcstat_mru_evictable_metadata);
5189 arc_kstat_update_state(arc_mru_ghost,
5190 &as->arcstat_mru_ghost_size,
5191 &as->arcstat_mru_ghost_evictable_data,
5192 &as->arcstat_mru_ghost_evictable_metadata);
5193 arc_kstat_update_state(arc_mfu,
5194 &as->arcstat_mfu_size,
5195 &as->arcstat_mfu_evictable_data,
5196 &as->arcstat_mfu_evictable_metadata);
5197 arc_kstat_update_state(arc_mfu_ghost,
5198 &as->arcstat_mfu_ghost_size,
5199 &as->arcstat_mfu_ghost_evictable_data,
5200 &as->arcstat_mfu_ghost_evictable_metadata);
5207 * This function *must* return indices evenly distributed between all
5208 * sublists of the multilist. This is needed due to how the ARC eviction
5209 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5210 * distributed between all sublists and uses this assumption when
5211 * deciding which sublist to evict from and how much to evict from it.
5214 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5216 arc_buf_hdr_t *hdr = obj;
5219 * We rely on b_dva to generate evenly distributed index
5220 * numbers using buf_hash below. So, as an added precaution,
5221 * let's make sure we never add empty buffers to the arc lists.
5223 ASSERT(!BUF_EMPTY(hdr));
5226 * The assumption here, is the hash value for a given
5227 * arc_buf_hdr_t will remain constant throughout it's lifetime
5228 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5229 * Thus, we don't need to store the header's sublist index
5230 * on insertion, as this index can be recalculated on removal.
5232 * Also, the low order bits of the hash value are thought to be
5233 * distributed evenly. Otherwise, in the case that the multilist
5234 * has a power of two number of sublists, each sublists' usage
5235 * would not be evenly distributed.
5237 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5238 multilist_get_num_sublists(ml));
5242 static eventhandler_tag arc_event_lowmem = NULL;
5245 arc_lowmem(void *arg __unused, int howto __unused)
5248 mutex_enter(&arc_reclaim_lock);
5249 /* XXX: Memory deficit should be passed as argument. */
5250 needfree = btoc(arc_c >> arc_shrink_shift);
5251 DTRACE_PROBE(arc__needfree);
5252 cv_signal(&arc_reclaim_thread_cv);
5255 * It is unsafe to block here in arbitrary threads, because we can come
5256 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5257 * with ARC reclaim thread.
5259 if (curproc == pageproc)
5260 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5261 mutex_exit(&arc_reclaim_lock);
5268 int i, prefetch_tunable_set = 0;
5270 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5271 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5272 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5274 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5275 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5277 /* Convert seconds to clock ticks */
5278 arc_min_prefetch_lifespan = 1 * hz;
5280 /* Start out with 1/8 of all memory */
5281 arc_c = kmem_size() / 8;
5286 * On architectures where the physical memory can be larger
5287 * than the addressable space (intel in 32-bit mode), we may
5288 * need to limit the cache to 1/8 of VM size.
5290 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5293 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5294 arc_c_min = MAX(arc_c / 4, 16 << 20);
5295 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5296 if (arc_c * 8 >= 1 << 30)
5297 arc_c_max = (arc_c * 8) - (1 << 30);
5299 arc_c_max = arc_c_min;
5300 arc_c_max = MAX(arc_c * 5, arc_c_max);
5304 * Allow the tunables to override our calculations if they are
5305 * reasonable (ie. over 16MB)
5307 if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5308 arc_c_max = zfs_arc_max;
5309 if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5310 arc_c_min = zfs_arc_min;
5314 arc_p = (arc_c >> 1);
5316 /* limit meta-data to 1/4 of the arc capacity */
5317 arc_meta_limit = arc_c_max / 4;
5319 /* Allow the tunable to override if it is reasonable */
5320 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5321 arc_meta_limit = zfs_arc_meta_limit;
5323 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5324 arc_c_min = arc_meta_limit / 2;
5326 if (zfs_arc_meta_min > 0) {
5327 arc_meta_min = zfs_arc_meta_min;
5329 arc_meta_min = arc_c_min / 2;
5332 if (zfs_arc_grow_retry > 0)
5333 arc_grow_retry = zfs_arc_grow_retry;
5335 if (zfs_arc_shrink_shift > 0)
5336 arc_shrink_shift = zfs_arc_shrink_shift;
5339 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5341 if (arc_no_grow_shift >= arc_shrink_shift)
5342 arc_no_grow_shift = arc_shrink_shift - 1;
5344 if (zfs_arc_p_min_shift > 0)
5345 arc_p_min_shift = zfs_arc_p_min_shift;
5347 if (zfs_arc_num_sublists_per_state < 1)
5348 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5350 /* if kmem_flags are set, lets try to use less memory */
5351 if (kmem_debugging())
5353 if (arc_c < arc_c_min)
5356 zfs_arc_min = arc_c_min;
5357 zfs_arc_max = arc_c_max;
5359 arc_anon = &ARC_anon;
5361 arc_mru_ghost = &ARC_mru_ghost;
5363 arc_mfu_ghost = &ARC_mfu_ghost;
5364 arc_l2c_only = &ARC_l2c_only;
5367 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5368 sizeof (arc_buf_hdr_t),
5369 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5370 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5371 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5372 sizeof (arc_buf_hdr_t),
5373 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5374 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5375 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5376 sizeof (arc_buf_hdr_t),
5377 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5378 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5379 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5380 sizeof (arc_buf_hdr_t),
5381 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5382 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5383 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5384 sizeof (arc_buf_hdr_t),
5385 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5386 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5387 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5388 sizeof (arc_buf_hdr_t),
5389 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5390 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5391 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5392 sizeof (arc_buf_hdr_t),
5393 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5394 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5395 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5396 sizeof (arc_buf_hdr_t),
5397 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5398 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5399 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5400 sizeof (arc_buf_hdr_t),
5401 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5402 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5403 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5404 sizeof (arc_buf_hdr_t),
5405 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5406 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5408 refcount_create(&arc_anon->arcs_size);
5409 refcount_create(&arc_mru->arcs_size);
5410 refcount_create(&arc_mru_ghost->arcs_size);
5411 refcount_create(&arc_mfu->arcs_size);
5412 refcount_create(&arc_mfu_ghost->arcs_size);
5413 refcount_create(&arc_l2c_only->arcs_size);
5417 arc_reclaim_thread_exit = FALSE;
5418 arc_user_evicts_thread_exit = FALSE;
5419 arc_eviction_list = NULL;
5420 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5422 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5423 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5425 if (arc_ksp != NULL) {
5426 arc_ksp->ks_data = &arc_stats;
5427 arc_ksp->ks_update = arc_kstat_update;
5428 kstat_install(arc_ksp);
5431 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5432 TS_RUN, minclsyspri);
5435 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5436 EVENTHANDLER_PRI_FIRST);
5439 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5440 TS_RUN, minclsyspri);
5446 * Calculate maximum amount of dirty data per pool.
5448 * If it has been set by /etc/system, take that.
5449 * Otherwise, use a percentage of physical memory defined by
5450 * zfs_dirty_data_max_percent (default 10%) with a cap at
5451 * zfs_dirty_data_max_max (default 4GB).
5453 if (zfs_dirty_data_max == 0) {
5454 zfs_dirty_data_max = ptob(physmem) *
5455 zfs_dirty_data_max_percent / 100;
5456 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5457 zfs_dirty_data_max_max);
5461 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5462 prefetch_tunable_set = 1;
5465 if (prefetch_tunable_set == 0) {
5466 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5468 printf(" add \"vfs.zfs.prefetch_disable=0\" "
5469 "to /boot/loader.conf.\n");
5470 zfs_prefetch_disable = 1;
5473 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5474 prefetch_tunable_set == 0) {
5475 printf("ZFS NOTICE: Prefetch is disabled by default if less "
5476 "than 4GB of RAM is present;\n"
5477 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
5478 "to /boot/loader.conf.\n");
5479 zfs_prefetch_disable = 1;
5482 /* Warn about ZFS memory and address space requirements. */
5483 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5484 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5485 "expect unstable behavior.\n");
5487 if (kmem_size() < 512 * (1 << 20)) {
5488 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5489 "expect unstable behavior.\n");
5490 printf(" Consider tuning vm.kmem_size and "
5491 "vm.kmem_size_max\n");
5492 printf(" in /boot/loader.conf.\n");
5500 mutex_enter(&arc_reclaim_lock);
5501 arc_reclaim_thread_exit = TRUE;
5503 * The reclaim thread will set arc_reclaim_thread_exit back to
5504 * FALSE when it is finished exiting; we're waiting for that.
5506 while (arc_reclaim_thread_exit) {
5507 cv_signal(&arc_reclaim_thread_cv);
5508 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5510 mutex_exit(&arc_reclaim_lock);
5512 mutex_enter(&arc_user_evicts_lock);
5513 arc_user_evicts_thread_exit = TRUE;
5515 * The user evicts thread will set arc_user_evicts_thread_exit
5516 * to FALSE when it is finished exiting; we're waiting for that.
5518 while (arc_user_evicts_thread_exit) {
5519 cv_signal(&arc_user_evicts_cv);
5520 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5522 mutex_exit(&arc_user_evicts_lock);
5524 /* Use TRUE to ensure *all* buffers are evicted */
5525 arc_flush(NULL, TRUE);
5529 if (arc_ksp != NULL) {
5530 kstat_delete(arc_ksp);
5534 mutex_destroy(&arc_reclaim_lock);
5535 cv_destroy(&arc_reclaim_thread_cv);
5536 cv_destroy(&arc_reclaim_waiters_cv);
5538 mutex_destroy(&arc_user_evicts_lock);
5539 cv_destroy(&arc_user_evicts_cv);
5541 refcount_destroy(&arc_anon->arcs_size);
5542 refcount_destroy(&arc_mru->arcs_size);
5543 refcount_destroy(&arc_mru_ghost->arcs_size);
5544 refcount_destroy(&arc_mfu->arcs_size);
5545 refcount_destroy(&arc_mfu_ghost->arcs_size);
5546 refcount_destroy(&arc_l2c_only->arcs_size);
5548 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5549 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5550 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5551 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5552 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5553 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5554 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5555 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5559 ASSERT0(arc_loaned_bytes);
5562 if (arc_event_lowmem != NULL)
5563 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5570 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5571 * It uses dedicated storage devices to hold cached data, which are populated
5572 * using large infrequent writes. The main role of this cache is to boost
5573 * the performance of random read workloads. The intended L2ARC devices
5574 * include short-stroked disks, solid state disks, and other media with
5575 * substantially faster read latency than disk.
5577 * +-----------------------+
5579 * +-----------------------+
5582 * l2arc_feed_thread() arc_read()
5586 * +---------------+ |
5588 * +---------------+ |
5593 * +-------+ +-------+
5595 * | cache | | cache |
5596 * +-------+ +-------+
5597 * +=========+ .-----.
5598 * : L2ARC : |-_____-|
5599 * : devices : | Disks |
5600 * +=========+ `-_____-'
5602 * Read requests are satisfied from the following sources, in order:
5605 * 2) vdev cache of L2ARC devices
5607 * 4) vdev cache of disks
5610 * Some L2ARC device types exhibit extremely slow write performance.
5611 * To accommodate for this there are some significant differences between
5612 * the L2ARC and traditional cache design:
5614 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5615 * the ARC behave as usual, freeing buffers and placing headers on ghost
5616 * lists. The ARC does not send buffers to the L2ARC during eviction as
5617 * this would add inflated write latencies for all ARC memory pressure.
5619 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5620 * It does this by periodically scanning buffers from the eviction-end of
5621 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5622 * not already there. It scans until a headroom of buffers is satisfied,
5623 * which itself is a buffer for ARC eviction. If a compressible buffer is
5624 * found during scanning and selected for writing to an L2ARC device, we
5625 * temporarily boost scanning headroom during the next scan cycle to make
5626 * sure we adapt to compression effects (which might significantly reduce
5627 * the data volume we write to L2ARC). The thread that does this is
5628 * l2arc_feed_thread(), illustrated below; example sizes are included to
5629 * provide a better sense of ratio than this diagram:
5632 * +---------------------+----------+
5633 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5634 * +---------------------+----------+ | o L2ARC eligible
5635 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5636 * +---------------------+----------+ |
5637 * 15.9 Gbytes ^ 32 Mbytes |
5639 * l2arc_feed_thread()
5641 * l2arc write hand <--[oooo]--'
5645 * +==============================+
5646 * L2ARC dev |####|#|###|###| |####| ... |
5647 * +==============================+
5650 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5651 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5652 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5653 * safe to say that this is an uncommon case, since buffers at the end of
5654 * the ARC lists have moved there due to inactivity.
5656 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5657 * then the L2ARC simply misses copying some buffers. This serves as a
5658 * pressure valve to prevent heavy read workloads from both stalling the ARC
5659 * with waits and clogging the L2ARC with writes. This also helps prevent
5660 * the potential for the L2ARC to churn if it attempts to cache content too
5661 * quickly, such as during backups of the entire pool.
5663 * 5. After system boot and before the ARC has filled main memory, there are
5664 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5665 * lists can remain mostly static. Instead of searching from tail of these
5666 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5667 * for eligible buffers, greatly increasing its chance of finding them.
5669 * The L2ARC device write speed is also boosted during this time so that
5670 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5671 * there are no L2ARC reads, and no fear of degrading read performance
5672 * through increased writes.
5674 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5675 * the vdev queue can aggregate them into larger and fewer writes. Each
5676 * device is written to in a rotor fashion, sweeping writes through
5677 * available space then repeating.
5679 * 7. The L2ARC does not store dirty content. It never needs to flush
5680 * write buffers back to disk based storage.
5682 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5683 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5685 * The performance of the L2ARC can be tweaked by a number of tunables, which
5686 * may be necessary for different workloads:
5688 * l2arc_write_max max write bytes per interval
5689 * l2arc_write_boost extra write bytes during device warmup
5690 * l2arc_noprefetch skip caching prefetched buffers
5691 * l2arc_headroom number of max device writes to precache
5692 * l2arc_headroom_boost when we find compressed buffers during ARC
5693 * scanning, we multiply headroom by this
5694 * percentage factor for the next scan cycle,
5695 * since more compressed buffers are likely to
5697 * l2arc_feed_secs seconds between L2ARC writing
5699 * Tunables may be removed or added as future performance improvements are
5700 * integrated, and also may become zpool properties.
5702 * There are three key functions that control how the L2ARC warms up:
5704 * l2arc_write_eligible() check if a buffer is eligible to cache
5705 * l2arc_write_size() calculate how much to write
5706 * l2arc_write_interval() calculate sleep delay between writes
5708 * These three functions determine what to write, how much, and how quickly
5713 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5716 * A buffer is *not* eligible for the L2ARC if it:
5717 * 1. belongs to a different spa.
5718 * 2. is already cached on the L2ARC.
5719 * 3. has an I/O in progress (it may be an incomplete read).
5720 * 4. is flagged not eligible (zfs property).
5722 if (hdr->b_spa != spa_guid) {
5723 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5726 if (HDR_HAS_L2HDR(hdr)) {
5727 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5730 if (HDR_IO_IN_PROGRESS(hdr)) {
5731 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5734 if (!HDR_L2CACHE(hdr)) {
5735 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5743 l2arc_write_size(void)
5748 * Make sure our globals have meaningful values in case the user
5751 size = l2arc_write_max;
5753 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5754 "be greater than zero, resetting it to the default (%d)",
5756 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5759 if (arc_warm == B_FALSE)
5760 size += l2arc_write_boost;
5767 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5769 clock_t interval, next, now;
5772 * If the ARC lists are busy, increase our write rate; if the
5773 * lists are stale, idle back. This is achieved by checking
5774 * how much we previously wrote - if it was more than half of
5775 * what we wanted, schedule the next write much sooner.
5777 if (l2arc_feed_again && wrote > (wanted / 2))
5778 interval = (hz * l2arc_feed_min_ms) / 1000;
5780 interval = hz * l2arc_feed_secs;
5782 now = ddi_get_lbolt();
5783 next = MAX(now, MIN(now + interval, began + interval));
5789 * Cycle through L2ARC devices. This is how L2ARC load balances.
5790 * If a device is returned, this also returns holding the spa config lock.
5792 static l2arc_dev_t *
5793 l2arc_dev_get_next(void)
5795 l2arc_dev_t *first, *next = NULL;
5798 * Lock out the removal of spas (spa_namespace_lock), then removal
5799 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5800 * both locks will be dropped and a spa config lock held instead.
5802 mutex_enter(&spa_namespace_lock);
5803 mutex_enter(&l2arc_dev_mtx);
5805 /* if there are no vdevs, there is nothing to do */
5806 if (l2arc_ndev == 0)
5810 next = l2arc_dev_last;
5812 /* loop around the list looking for a non-faulted vdev */
5814 next = list_head(l2arc_dev_list);
5816 next = list_next(l2arc_dev_list, next);
5818 next = list_head(l2arc_dev_list);
5821 /* if we have come back to the start, bail out */
5824 else if (next == first)
5827 } while (vdev_is_dead(next->l2ad_vdev));
5829 /* if we were unable to find any usable vdevs, return NULL */
5830 if (vdev_is_dead(next->l2ad_vdev))
5833 l2arc_dev_last = next;
5836 mutex_exit(&l2arc_dev_mtx);
5839 * Grab the config lock to prevent the 'next' device from being
5840 * removed while we are writing to it.
5843 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5844 mutex_exit(&spa_namespace_lock);
5850 * Free buffers that were tagged for destruction.
5853 l2arc_do_free_on_write()
5856 l2arc_data_free_t *df, *df_prev;
5858 mutex_enter(&l2arc_free_on_write_mtx);
5859 buflist = l2arc_free_on_write;
5861 for (df = list_tail(buflist); df; df = df_prev) {
5862 df_prev = list_prev(buflist, df);
5863 ASSERT(df->l2df_data != NULL);
5864 ASSERT(df->l2df_func != NULL);
5865 df->l2df_func(df->l2df_data, df->l2df_size);
5866 list_remove(buflist, df);
5867 kmem_free(df, sizeof (l2arc_data_free_t));
5870 mutex_exit(&l2arc_free_on_write_mtx);
5874 * A write to a cache device has completed. Update all headers to allow
5875 * reads from these buffers to begin.
5878 l2arc_write_done(zio_t *zio)
5880 l2arc_write_callback_t *cb;
5883 arc_buf_hdr_t *head, *hdr, *hdr_prev;
5884 kmutex_t *hash_lock;
5885 int64_t bytes_dropped = 0;
5887 cb = zio->io_private;
5889 dev = cb->l2wcb_dev;
5890 ASSERT(dev != NULL);
5891 head = cb->l2wcb_head;
5892 ASSERT(head != NULL);
5893 buflist = &dev->l2ad_buflist;
5894 ASSERT(buflist != NULL);
5895 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5896 l2arc_write_callback_t *, cb);
5898 if (zio->io_error != 0)
5899 ARCSTAT_BUMP(arcstat_l2_writes_error);
5902 * All writes completed, or an error was hit.
5905 mutex_enter(&dev->l2ad_mtx);
5906 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5907 hdr_prev = list_prev(buflist, hdr);
5909 hash_lock = HDR_LOCK(hdr);
5912 * We cannot use mutex_enter or else we can deadlock
5913 * with l2arc_write_buffers (due to swapping the order
5914 * the hash lock and l2ad_mtx are taken).
5916 if (!mutex_tryenter(hash_lock)) {
5918 * Missed the hash lock. We must retry so we
5919 * don't leave the ARC_FLAG_L2_WRITING bit set.
5921 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5924 * We don't want to rescan the headers we've
5925 * already marked as having been written out, so
5926 * we reinsert the head node so we can pick up
5927 * where we left off.
5929 list_remove(buflist, head);
5930 list_insert_after(buflist, hdr, head);
5932 mutex_exit(&dev->l2ad_mtx);
5935 * We wait for the hash lock to become available
5936 * to try and prevent busy waiting, and increase
5937 * the chance we'll be able to acquire the lock
5938 * the next time around.
5940 mutex_enter(hash_lock);
5941 mutex_exit(hash_lock);
5946 * We could not have been moved into the arc_l2c_only
5947 * state while in-flight due to our ARC_FLAG_L2_WRITING
5948 * bit being set. Let's just ensure that's being enforced.
5950 ASSERT(HDR_HAS_L1HDR(hdr));
5953 * We may have allocated a buffer for L2ARC compression,
5954 * we must release it to avoid leaking this data.
5956 l2arc_release_cdata_buf(hdr);
5958 if (zio->io_error != 0) {
5960 * Error - drop L2ARC entry.
5962 list_remove(buflist, hdr);
5963 trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
5964 hdr->b_l2hdr.b_daddr, hdr->b_l2hdr.b_asize, 0);
5965 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5967 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5968 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5970 bytes_dropped += hdr->b_l2hdr.b_asize;
5971 (void) refcount_remove_many(&dev->l2ad_alloc,
5972 hdr->b_l2hdr.b_asize, hdr);
5976 * Allow ARC to begin reads and ghost list evictions to
5979 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5981 mutex_exit(hash_lock);
5984 atomic_inc_64(&l2arc_writes_done);
5985 list_remove(buflist, head);
5986 ASSERT(!HDR_HAS_L1HDR(head));
5987 kmem_cache_free(hdr_l2only_cache, head);
5988 mutex_exit(&dev->l2ad_mtx);
5990 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5992 l2arc_do_free_on_write();
5994 kmem_free(cb, sizeof (l2arc_write_callback_t));
5998 * A read to a cache device completed. Validate buffer contents before
5999 * handing over to the regular ARC routines.
6002 l2arc_read_done(zio_t *zio)
6004 l2arc_read_callback_t *cb;
6007 kmutex_t *hash_lock;
6010 ASSERT(zio->io_vd != NULL);
6011 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6013 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6015 cb = zio->io_private;
6017 buf = cb->l2rcb_buf;
6018 ASSERT(buf != NULL);
6020 hash_lock = HDR_LOCK(buf->b_hdr);
6021 mutex_enter(hash_lock);
6023 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6026 * If the buffer was compressed, decompress it first.
6028 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
6029 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6030 ASSERT(zio->io_data != NULL);
6033 * Check this survived the L2ARC journey.
6035 equal = arc_cksum_equal(buf);
6036 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6037 mutex_exit(hash_lock);
6038 zio->io_private = buf;
6039 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6040 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6043 mutex_exit(hash_lock);
6045 * Buffer didn't survive caching. Increment stats and
6046 * reissue to the original storage device.
6048 if (zio->io_error != 0) {
6049 ARCSTAT_BUMP(arcstat_l2_io_error);
6051 zio->io_error = SET_ERROR(EIO);
6054 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6057 * If there's no waiter, issue an async i/o to the primary
6058 * storage now. If there *is* a waiter, the caller must
6059 * issue the i/o in a context where it's OK to block.
6061 if (zio->io_waiter == NULL) {
6062 zio_t *pio = zio_unique_parent(zio);
6064 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6066 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6067 buf->b_data, zio->io_size, arc_read_done, buf,
6068 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6072 kmem_free(cb, sizeof (l2arc_read_callback_t));
6076 * This is the list priority from which the L2ARC will search for pages to
6077 * cache. This is used within loops (0..3) to cycle through lists in the
6078 * desired order. This order can have a significant effect on cache
6081 * Currently the metadata lists are hit first, MFU then MRU, followed by
6082 * the data lists. This function returns a locked list, and also returns
6085 static multilist_sublist_t *
6086 l2arc_sublist_lock(int list_num)
6088 multilist_t *ml = NULL;
6091 ASSERT(list_num >= 0 && list_num <= 3);
6095 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6098 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6101 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6104 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6109 * Return a randomly-selected sublist. This is acceptable
6110 * because the caller feeds only a little bit of data for each
6111 * call (8MB). Subsequent calls will result in different
6112 * sublists being selected.
6114 idx = multilist_get_random_index(ml);
6115 return (multilist_sublist_lock(ml, idx));
6119 * Evict buffers from the device write hand to the distance specified in
6120 * bytes. This distance may span populated buffers, it may span nothing.
6121 * This is clearing a region on the L2ARC device ready for writing.
6122 * If the 'all' boolean is set, every buffer is evicted.
6125 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6128 arc_buf_hdr_t *hdr, *hdr_prev;
6129 kmutex_t *hash_lock;
6132 buflist = &dev->l2ad_buflist;
6134 if (!all && dev->l2ad_first) {
6136 * This is the first sweep through the device. There is
6142 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6144 * When nearing the end of the device, evict to the end
6145 * before the device write hand jumps to the start.
6147 taddr = dev->l2ad_end;
6149 taddr = dev->l2ad_hand + distance;
6151 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6152 uint64_t, taddr, boolean_t, all);
6155 mutex_enter(&dev->l2ad_mtx);
6156 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6157 hdr_prev = list_prev(buflist, hdr);
6159 hash_lock = HDR_LOCK(hdr);
6162 * We cannot use mutex_enter or else we can deadlock
6163 * with l2arc_write_buffers (due to swapping the order
6164 * the hash lock and l2ad_mtx are taken).
6166 if (!mutex_tryenter(hash_lock)) {
6168 * Missed the hash lock. Retry.
6170 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6171 mutex_exit(&dev->l2ad_mtx);
6172 mutex_enter(hash_lock);
6173 mutex_exit(hash_lock);
6177 if (HDR_L2_WRITE_HEAD(hdr)) {
6179 * We hit a write head node. Leave it for
6180 * l2arc_write_done().
6182 list_remove(buflist, hdr);
6183 mutex_exit(hash_lock);
6187 if (!all && HDR_HAS_L2HDR(hdr) &&
6188 (hdr->b_l2hdr.b_daddr > taddr ||
6189 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6191 * We've evicted to the target address,
6192 * or the end of the device.
6194 mutex_exit(hash_lock);
6198 ASSERT(HDR_HAS_L2HDR(hdr));
6199 if (!HDR_HAS_L1HDR(hdr)) {
6200 ASSERT(!HDR_L2_READING(hdr));
6202 * This doesn't exist in the ARC. Destroy.
6203 * arc_hdr_destroy() will call list_remove()
6204 * and decrement arcstat_l2_size.
6206 arc_change_state(arc_anon, hdr, hash_lock);
6207 arc_hdr_destroy(hdr);
6209 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6210 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6212 * Invalidate issued or about to be issued
6213 * reads, since we may be about to write
6214 * over this location.
6216 if (HDR_L2_READING(hdr)) {
6217 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6218 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6221 /* Ensure this header has finished being written */
6222 ASSERT(!HDR_L2_WRITING(hdr));
6223 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6225 arc_hdr_l2hdr_destroy(hdr);
6227 mutex_exit(hash_lock);
6229 mutex_exit(&dev->l2ad_mtx);
6233 * Find and write ARC buffers to the L2ARC device.
6235 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6236 * for reading until they have completed writing.
6237 * The headroom_boost is an in-out parameter used to maintain headroom boost
6238 * state between calls to this function.
6240 * Returns the number of bytes actually written (which may be smaller than
6241 * the delta by which the device hand has changed due to alignment).
6244 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6245 boolean_t *headroom_boost)
6247 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6248 uint64_t write_asize, write_sz, headroom, buf_compress_minsz;
6251 l2arc_write_callback_t *cb;
6253 uint64_t guid = spa_load_guid(spa);
6254 const boolean_t do_headroom_boost = *headroom_boost;
6257 ASSERT(dev->l2ad_vdev != NULL);
6259 /* Lower the flag now, we might want to raise it again later. */
6260 *headroom_boost = B_FALSE;
6263 write_sz = write_asize = 0;
6265 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6266 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6267 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6269 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6271 * We will want to try to compress buffers that are at least 2x the
6272 * device sector size.
6274 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6277 * Copy buffers for L2ARC writing.
6279 for (try = 0; try <= 3; try++) {
6280 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6281 uint64_t passed_sz = 0;
6283 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6286 * L2ARC fast warmup.
6288 * Until the ARC is warm and starts to evict, read from the
6289 * head of the ARC lists rather than the tail.
6291 if (arc_warm == B_FALSE)
6292 hdr = multilist_sublist_head(mls);
6294 hdr = multilist_sublist_tail(mls);
6296 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6298 headroom = target_sz * l2arc_headroom;
6299 if (do_headroom_boost)
6300 headroom = (headroom * l2arc_headroom_boost) / 100;
6302 for (; hdr; hdr = hdr_prev) {
6303 kmutex_t *hash_lock;
6307 if (arc_warm == B_FALSE)
6308 hdr_prev = multilist_sublist_next(mls, hdr);
6310 hdr_prev = multilist_sublist_prev(mls, hdr);
6311 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6313 hash_lock = HDR_LOCK(hdr);
6314 if (!mutex_tryenter(hash_lock)) {
6315 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6317 * Skip this buffer rather than waiting.
6322 passed_sz += hdr->b_size;
6323 if (passed_sz > headroom) {
6327 mutex_exit(hash_lock);
6328 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6332 if (!l2arc_write_eligible(guid, hdr)) {
6333 mutex_exit(hash_lock);
6338 * Assume that the buffer is not going to be compressed
6339 * and could take more space on disk because of a larger
6342 buf_sz = hdr->b_size;
6343 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6345 if ((write_asize + buf_a_sz) > target_sz) {
6347 mutex_exit(hash_lock);
6348 ARCSTAT_BUMP(arcstat_l2_write_full);
6354 * Insert a dummy header on the buflist so
6355 * l2arc_write_done() can find where the
6356 * write buffers begin without searching.
6358 mutex_enter(&dev->l2ad_mtx);
6359 list_insert_head(&dev->l2ad_buflist, head);
6360 mutex_exit(&dev->l2ad_mtx);
6363 sizeof (l2arc_write_callback_t), KM_SLEEP);
6364 cb->l2wcb_dev = dev;
6365 cb->l2wcb_head = head;
6366 pio = zio_root(spa, l2arc_write_done, cb,
6368 ARCSTAT_BUMP(arcstat_l2_write_pios);
6372 * Create and add a new L2ARC header.
6374 hdr->b_l2hdr.b_dev = dev;
6375 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6377 * Temporarily stash the data buffer in b_tmp_cdata.
6378 * The subsequent write step will pick it up from
6379 * there. This is because can't access b_l1hdr.b_buf
6380 * without holding the hash_lock, which we in turn
6381 * can't access without holding the ARC list locks
6382 * (which we want to avoid during compression/writing).
6384 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
6385 hdr->b_l2hdr.b_asize = hdr->b_size;
6386 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6389 * Explicitly set the b_daddr field to a known
6390 * value which means "invalid address". This
6391 * enables us to differentiate which stage of
6392 * l2arc_write_buffers() the particular header
6393 * is in (e.g. this loop, or the one below).
6394 * ARC_FLAG_L2_WRITING is not enough to make
6395 * this distinction, and we need to know in
6396 * order to do proper l2arc vdev accounting in
6397 * arc_release() and arc_hdr_destroy().
6399 * Note, we can't use a new flag to distinguish
6400 * the two stages because we don't hold the
6401 * header's hash_lock below, in the second stage
6402 * of this function. Thus, we can't simply
6403 * change the b_flags field to denote that the
6404 * IO has been sent. We can change the b_daddr
6405 * field of the L2 portion, though, since we'll
6406 * be holding the l2ad_mtx; which is why we're
6407 * using it to denote the header's state change.
6409 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6410 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6412 mutex_enter(&dev->l2ad_mtx);
6413 list_insert_head(&dev->l2ad_buflist, hdr);
6414 mutex_exit(&dev->l2ad_mtx);
6417 * Compute and store the buffer cksum before
6418 * writing. On debug the cksum is verified first.
6420 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6421 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6423 mutex_exit(hash_lock);
6426 write_asize += buf_a_sz;
6429 multilist_sublist_unlock(mls);
6435 /* No buffers selected for writing? */
6438 ASSERT(!HDR_HAS_L1HDR(head));
6439 kmem_cache_free(hdr_l2only_cache, head);
6443 mutex_enter(&dev->l2ad_mtx);
6446 * Note that elsewhere in this file arcstat_l2_asize
6447 * and the used space on l2ad_vdev are updated using b_asize,
6448 * which is not necessarily rounded up to the device block size.
6449 * Too keep accounting consistent we do the same here as well:
6450 * stats_size accumulates the sum of b_asize of the written buffers,
6451 * while write_asize accumulates the sum of b_asize rounded up
6452 * to the device block size.
6453 * The latter sum is used only to validate the corectness of the code.
6455 uint64_t stats_size = 0;
6459 * Now start writing the buffers. We're starting at the write head
6460 * and work backwards, retracing the course of the buffer selector
6463 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6464 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6468 * We rely on the L1 portion of the header below, so
6469 * it's invalid for this header to have been evicted out
6470 * of the ghost cache, prior to being written out. The
6471 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6473 ASSERT(HDR_HAS_L1HDR(hdr));
6476 * We shouldn't need to lock the buffer here, since we flagged
6477 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6478 * take care to only access its L2 cache parameters. In
6479 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6482 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6484 if ((HDR_L2COMPRESS(hdr)) &&
6485 hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6486 if (l2arc_compress_buf(hdr)) {
6488 * If compression succeeded, enable headroom
6489 * boost on the next scan cycle.
6491 *headroom_boost = B_TRUE;
6496 * Pick up the buffer data we had previously stashed away
6497 * (and now potentially also compressed).
6499 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6500 buf_sz = hdr->b_l2hdr.b_asize;
6503 * We need to do this regardless if buf_sz is zero or
6504 * not, otherwise, when this l2hdr is evicted we'll
6505 * remove a reference that was never added.
6507 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6509 /* Compression may have squashed the buffer to zero length. */
6513 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6514 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6515 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6516 ZIO_FLAG_CANFAIL, B_FALSE);
6518 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6520 (void) zio_nowait(wzio);
6522 stats_size += buf_sz;
6525 * Keep the clock hand suitably device-aligned.
6527 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6528 write_asize += buf_a_sz;
6529 dev->l2ad_hand += buf_a_sz;
6533 mutex_exit(&dev->l2ad_mtx);
6535 ASSERT3U(write_asize, <=, target_sz);
6536 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6537 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6538 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6539 ARCSTAT_INCR(arcstat_l2_asize, stats_size);
6540 vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
6543 * Bump device hand to the device start if it is approaching the end.
6544 * l2arc_evict() will already have evicted ahead for this case.
6546 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6547 dev->l2ad_hand = dev->l2ad_start;
6548 dev->l2ad_first = B_FALSE;
6551 dev->l2ad_writing = B_TRUE;
6552 (void) zio_wait(pio);
6553 dev->l2ad_writing = B_FALSE;
6555 return (write_asize);
6559 * Compresses an L2ARC buffer.
6560 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6561 * size in l2hdr->b_asize. This routine tries to compress the data and
6562 * depending on the compression result there are three possible outcomes:
6563 * *) The buffer was incompressible. The original l2hdr contents were left
6564 * untouched and are ready for writing to an L2 device.
6565 * *) The buffer was all-zeros, so there is no need to write it to an L2
6566 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6567 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6568 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6569 * data buffer which holds the compressed data to be written, and b_asize
6570 * tells us how much data there is. b_compress is set to the appropriate
6571 * compression algorithm. Once writing is done, invoke
6572 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6574 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6575 * buffer was incompressible).
6578 l2arc_compress_buf(arc_buf_hdr_t *hdr)
6581 size_t csize, len, rounded;
6582 ASSERT(HDR_HAS_L2HDR(hdr));
6583 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6585 ASSERT(HDR_HAS_L1HDR(hdr));
6586 ASSERT(HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF);
6587 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6589 len = l2hdr->b_asize;
6590 cdata = zio_data_buf_alloc(len);
6591 ASSERT3P(cdata, !=, NULL);
6592 csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6593 cdata, l2hdr->b_asize);
6596 /* zero block, indicate that there's nothing to write */
6597 zio_data_buf_free(cdata, len);
6598 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_EMPTY);
6600 hdr->b_l1hdr.b_tmp_cdata = NULL;
6601 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6605 rounded = P2ROUNDUP(csize,
6606 (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
6607 if (rounded < len) {
6609 * Compression succeeded, we'll keep the cdata around for
6610 * writing and release it afterwards.
6612 if (rounded > csize) {
6613 bzero((char *)cdata + csize, rounded - csize);
6616 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_LZ4);
6617 l2hdr->b_asize = csize;
6618 hdr->b_l1hdr.b_tmp_cdata = cdata;
6619 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6623 * Compression failed, release the compressed buffer.
6624 * l2hdr will be left unmodified.
6626 zio_data_buf_free(cdata, len);
6627 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6633 * Decompresses a zio read back from an l2arc device. On success, the
6634 * underlying zio's io_data buffer is overwritten by the uncompressed
6635 * version. On decompression error (corrupt compressed stream), the
6636 * zio->io_error value is set to signal an I/O error.
6638 * Please note that the compressed data stream is not checksummed, so
6639 * if the underlying device is experiencing data corruption, we may feed
6640 * corrupt data to the decompressor, so the decompressor needs to be
6641 * able to handle this situation (LZ4 does).
6644 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6646 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6648 if (zio->io_error != 0) {
6650 * An io error has occured, just restore the original io
6651 * size in preparation for a main pool read.
6653 zio->io_orig_size = zio->io_size = hdr->b_size;
6657 if (c == ZIO_COMPRESS_EMPTY) {
6659 * An empty buffer results in a null zio, which means we
6660 * need to fill its io_data after we're done restoring the
6661 * buffer's contents.
6663 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6664 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6665 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6667 ASSERT(zio->io_data != NULL);
6669 * We copy the compressed data from the start of the arc buffer
6670 * (the zio_read will have pulled in only what we need, the
6671 * rest is garbage which we will overwrite at decompression)
6672 * and then decompress back to the ARC data buffer. This way we
6673 * can minimize copying by simply decompressing back over the
6674 * original compressed data (rather than decompressing to an
6675 * aux buffer and then copying back the uncompressed buffer,
6676 * which is likely to be much larger).
6681 csize = zio->io_size;
6682 cdata = zio_data_buf_alloc(csize);
6683 bcopy(zio->io_data, cdata, csize);
6684 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6686 zio->io_error = EIO;
6687 zio_data_buf_free(cdata, csize);
6690 /* Restore the expected uncompressed IO size. */
6691 zio->io_orig_size = zio->io_size = hdr->b_size;
6695 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6696 * This buffer serves as a temporary holder of compressed data while
6697 * the buffer entry is being written to an l2arc device. Once that is
6698 * done, we can dispose of it.
6701 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6703 enum zio_compress comp = HDR_GET_COMPRESS(hdr);
6705 ASSERT(HDR_HAS_L1HDR(hdr));
6706 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6708 if (comp == ZIO_COMPRESS_OFF) {
6710 * In this case, b_tmp_cdata points to the same buffer
6711 * as the arc_buf_t's b_data field. We don't want to
6712 * free it, since the arc_buf_t will handle that.
6714 hdr->b_l1hdr.b_tmp_cdata = NULL;
6715 } else if (comp == ZIO_COMPRESS_EMPTY) {
6717 * In this case, b_tmp_cdata was compressed to an empty
6718 * buffer, thus there's nothing to free and b_tmp_cdata
6719 * should have been set to NULL in l2arc_write_buffers().
6721 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6724 * If the data was compressed, then we've allocated a
6725 * temporary buffer for it, so now we need to release it.
6727 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6728 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6730 hdr->b_l1hdr.b_tmp_cdata = NULL;
6736 * This thread feeds the L2ARC at regular intervals. This is the beating
6737 * heart of the L2ARC.
6740 l2arc_feed_thread(void *dummy __unused)
6745 uint64_t size, wrote;
6746 clock_t begin, next = ddi_get_lbolt();
6747 boolean_t headroom_boost = B_FALSE;
6749 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6751 mutex_enter(&l2arc_feed_thr_lock);
6753 while (l2arc_thread_exit == 0) {
6754 CALLB_CPR_SAFE_BEGIN(&cpr);
6755 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6756 next - ddi_get_lbolt());
6757 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6758 next = ddi_get_lbolt() + hz;
6761 * Quick check for L2ARC devices.
6763 mutex_enter(&l2arc_dev_mtx);
6764 if (l2arc_ndev == 0) {
6765 mutex_exit(&l2arc_dev_mtx);
6768 mutex_exit(&l2arc_dev_mtx);
6769 begin = ddi_get_lbolt();
6772 * This selects the next l2arc device to write to, and in
6773 * doing so the next spa to feed from: dev->l2ad_spa. This
6774 * will return NULL if there are now no l2arc devices or if
6775 * they are all faulted.
6777 * If a device is returned, its spa's config lock is also
6778 * held to prevent device removal. l2arc_dev_get_next()
6779 * will grab and release l2arc_dev_mtx.
6781 if ((dev = l2arc_dev_get_next()) == NULL)
6784 spa = dev->l2ad_spa;
6785 ASSERT(spa != NULL);
6788 * If the pool is read-only then force the feed thread to
6789 * sleep a little longer.
6791 if (!spa_writeable(spa)) {
6792 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6793 spa_config_exit(spa, SCL_L2ARC, dev);
6798 * Avoid contributing to memory pressure.
6800 if (arc_reclaim_needed()) {
6801 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6802 spa_config_exit(spa, SCL_L2ARC, dev);
6806 ARCSTAT_BUMP(arcstat_l2_feeds);
6808 size = l2arc_write_size();
6811 * Evict L2ARC buffers that will be overwritten.
6813 l2arc_evict(dev, size, B_FALSE);
6816 * Write ARC buffers.
6818 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6821 * Calculate interval between writes.
6823 next = l2arc_write_interval(begin, size, wrote);
6824 spa_config_exit(spa, SCL_L2ARC, dev);
6827 l2arc_thread_exit = 0;
6828 cv_broadcast(&l2arc_feed_thr_cv);
6829 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6834 l2arc_vdev_present(vdev_t *vd)
6838 mutex_enter(&l2arc_dev_mtx);
6839 for (dev = list_head(l2arc_dev_list); dev != NULL;
6840 dev = list_next(l2arc_dev_list, dev)) {
6841 if (dev->l2ad_vdev == vd)
6844 mutex_exit(&l2arc_dev_mtx);
6846 return (dev != NULL);
6850 * Add a vdev for use by the L2ARC. By this point the spa has already
6851 * validated the vdev and opened it.
6854 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6856 l2arc_dev_t *adddev;
6858 ASSERT(!l2arc_vdev_present(vd));
6860 vdev_ashift_optimize(vd);
6863 * Create a new l2arc device entry.
6865 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6866 adddev->l2ad_spa = spa;
6867 adddev->l2ad_vdev = vd;
6868 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6869 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6870 adddev->l2ad_hand = adddev->l2ad_start;
6871 adddev->l2ad_first = B_TRUE;
6872 adddev->l2ad_writing = B_FALSE;
6874 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6876 * This is a list of all ARC buffers that are still valid on the
6879 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6880 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6882 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6883 refcount_create(&adddev->l2ad_alloc);
6886 * Add device to global list
6888 mutex_enter(&l2arc_dev_mtx);
6889 list_insert_head(l2arc_dev_list, adddev);
6890 atomic_inc_64(&l2arc_ndev);
6891 mutex_exit(&l2arc_dev_mtx);
6895 * Remove a vdev from the L2ARC.
6898 l2arc_remove_vdev(vdev_t *vd)
6900 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6903 * Find the device by vdev
6905 mutex_enter(&l2arc_dev_mtx);
6906 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6907 nextdev = list_next(l2arc_dev_list, dev);
6908 if (vd == dev->l2ad_vdev) {
6913 ASSERT(remdev != NULL);
6916 * Remove device from global list
6918 list_remove(l2arc_dev_list, remdev);
6919 l2arc_dev_last = NULL; /* may have been invalidated */
6920 atomic_dec_64(&l2arc_ndev);
6921 mutex_exit(&l2arc_dev_mtx);
6924 * Clear all buflists and ARC references. L2ARC device flush.
6926 l2arc_evict(remdev, 0, B_TRUE);
6927 list_destroy(&remdev->l2ad_buflist);
6928 mutex_destroy(&remdev->l2ad_mtx);
6929 refcount_destroy(&remdev->l2ad_alloc);
6930 kmem_free(remdev, sizeof (l2arc_dev_t));
6936 l2arc_thread_exit = 0;
6938 l2arc_writes_sent = 0;
6939 l2arc_writes_done = 0;
6941 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6942 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6943 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6944 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6946 l2arc_dev_list = &L2ARC_dev_list;
6947 l2arc_free_on_write = &L2ARC_free_on_write;
6948 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6949 offsetof(l2arc_dev_t, l2ad_node));
6950 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6951 offsetof(l2arc_data_free_t, l2df_list_node));
6958 * This is called from dmu_fini(), which is called from spa_fini();
6959 * Because of this, we can assume that all l2arc devices have
6960 * already been removed when the pools themselves were removed.
6963 l2arc_do_free_on_write();
6965 mutex_destroy(&l2arc_feed_thr_lock);
6966 cv_destroy(&l2arc_feed_thr_cv);
6967 mutex_destroy(&l2arc_dev_mtx);
6968 mutex_destroy(&l2arc_free_on_write_mtx);
6970 list_destroy(l2arc_dev_list);
6971 list_destroy(l2arc_free_on_write);
6977 if (!(spa_mode_global & FWRITE))
6980 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6981 TS_RUN, minclsyspri);
6987 if (!(spa_mode_global & FWRITE))
6990 mutex_enter(&l2arc_feed_thr_lock);
6991 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
6992 l2arc_thread_exit = 1;
6993 while (l2arc_thread_exit != 0)
6994 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6995 mutex_exit(&l2arc_feed_thr_lock);