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 */
856 list_node_t b_l2node;
860 /* protected by hash lock */
864 * Even though this checksum is only set/verified when a buffer is in
865 * the L1 cache, it needs to be in the set of common fields because it
866 * must be preserved from the time before a buffer is written out to
867 * L2ARC until after it is read back in.
869 zio_cksum_t *b_freeze_cksum;
871 arc_buf_hdr_t *b_hash_next;
878 /* L2ARC fields. Undefined when not in L2ARC. */
879 l2arc_buf_hdr_t b_l2hdr;
880 /* L1ARC fields. Undefined when in l2arc_only state */
881 l1arc_buf_hdr_t b_l1hdr;
886 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
891 val = arc_meta_limit;
892 err = sysctl_handle_64(oidp, &val, 0, req);
893 if (err != 0 || req->newptr == NULL)
896 if (val <= 0 || val > arc_c_max)
899 arc_meta_limit = val;
904 static arc_buf_t *arc_eviction_list;
905 static arc_buf_hdr_t arc_eviction_hdr;
907 #define GHOST_STATE(state) \
908 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
909 (state) == arc_l2c_only)
911 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
912 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
913 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
914 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
915 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
916 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
918 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
919 #define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
920 #define HDR_L2_READING(hdr) \
921 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
922 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
923 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
924 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
925 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
927 #define HDR_ISTYPE_METADATA(hdr) \
928 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
929 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
931 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
932 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
938 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
939 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
942 * Hash table routines
945 #define HT_LOCK_PAD CACHE_LINE_SIZE
950 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
954 #define BUF_LOCKS 256
955 typedef struct buf_hash_table {
957 arc_buf_hdr_t **ht_table;
958 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
961 static buf_hash_table_t buf_hash_table;
963 #define BUF_HASH_INDEX(spa, dva, birth) \
964 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
965 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
966 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
967 #define HDR_LOCK(hdr) \
968 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
970 uint64_t zfs_crc64_table[256];
976 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
977 #define L2ARC_HEADROOM 2 /* num of writes */
979 * If we discover during ARC scan any buffers to be compressed, we boost
980 * our headroom for the next scanning cycle by this percentage multiple.
982 #define L2ARC_HEADROOM_BOOST 200
983 #define L2ARC_FEED_SECS 1 /* caching interval secs */
984 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
987 * Used to distinguish headers that are being process by
988 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
989 * address. This can happen when the header is added to the l2arc's list
990 * of buffers to write in the first stage of l2arc_write_buffers(), but
991 * has not yet been written out which happens in the second stage of
992 * l2arc_write_buffers().
994 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
996 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
997 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
999 /* L2ARC Performance Tunables */
1000 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1001 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1002 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1003 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1004 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1005 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1006 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1007 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1008 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1010 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1011 &l2arc_write_max, 0, "max write size");
1012 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1013 &l2arc_write_boost, 0, "extra write during warmup");
1014 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1015 &l2arc_headroom, 0, "number of dev writes");
1016 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1017 &l2arc_feed_secs, 0, "interval seconds");
1018 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1019 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1021 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1022 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1023 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1024 &l2arc_feed_again, 0, "turbo warmup");
1025 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1026 &l2arc_norw, 0, "no reads during writes");
1028 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1029 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1030 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1031 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1032 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1033 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1035 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1036 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1037 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1038 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1039 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1040 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1042 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1043 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1044 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1045 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1046 "size of metadata in mru ghost state");
1047 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1048 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1049 "size of data in mru ghost state");
1051 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1052 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1053 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1054 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1055 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1056 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1058 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1059 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1060 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1061 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1062 "size of metadata in mfu ghost state");
1063 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1064 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1065 "size of data in mfu ghost state");
1067 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1068 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1074 vdev_t *l2ad_vdev; /* vdev */
1075 spa_t *l2ad_spa; /* spa */
1076 uint64_t l2ad_hand; /* next write location */
1077 uint64_t l2ad_start; /* first addr on device */
1078 uint64_t l2ad_end; /* last addr on device */
1079 boolean_t l2ad_first; /* first sweep through */
1080 boolean_t l2ad_writing; /* currently writing */
1081 kmutex_t l2ad_mtx; /* lock for buffer list */
1082 list_t l2ad_buflist; /* buffer list */
1083 list_node_t l2ad_node; /* device list node */
1084 refcount_t l2ad_alloc; /* allocated bytes */
1087 static list_t L2ARC_dev_list; /* device list */
1088 static list_t *l2arc_dev_list; /* device list pointer */
1089 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1090 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1091 static list_t L2ARC_free_on_write; /* free after write buf list */
1092 static list_t *l2arc_free_on_write; /* free after write list ptr */
1093 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1094 static uint64_t l2arc_ndev; /* number of devices */
1096 typedef struct l2arc_read_callback {
1097 arc_buf_t *l2rcb_buf; /* read buffer */
1098 spa_t *l2rcb_spa; /* spa */
1099 blkptr_t l2rcb_bp; /* original blkptr */
1100 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1101 int l2rcb_flags; /* original flags */
1102 enum zio_compress l2rcb_compress; /* applied compress */
1103 } l2arc_read_callback_t;
1105 typedef struct l2arc_write_callback {
1106 l2arc_dev_t *l2wcb_dev; /* device info */
1107 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1108 } l2arc_write_callback_t;
1110 typedef struct l2arc_data_free {
1111 /* protected by l2arc_free_on_write_mtx */
1114 void (*l2df_func)(void *, size_t);
1115 list_node_t l2df_list_node;
1116 } l2arc_data_free_t;
1118 static kmutex_t l2arc_feed_thr_lock;
1119 static kcondvar_t l2arc_feed_thr_cv;
1120 static uint8_t l2arc_thread_exit;
1122 static void arc_get_data_buf(arc_buf_t *);
1123 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1124 static boolean_t arc_is_overflowing();
1125 static void arc_buf_watch(arc_buf_t *);
1127 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1128 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1130 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1131 static void l2arc_read_done(zio_t *);
1133 static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
1134 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1135 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1138 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1140 uint8_t *vdva = (uint8_t *)dva;
1141 uint64_t crc = -1ULL;
1144 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1146 for (i = 0; i < sizeof (dva_t); i++)
1147 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1149 crc ^= (spa>>8) ^ birth;
1154 #define BUF_EMPTY(buf) \
1155 ((buf)->b_dva.dva_word[0] == 0 && \
1156 (buf)->b_dva.dva_word[1] == 0)
1158 #define BUF_EQUAL(spa, dva, birth, buf) \
1159 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1160 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1161 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1164 buf_discard_identity(arc_buf_hdr_t *hdr)
1166 hdr->b_dva.dva_word[0] = 0;
1167 hdr->b_dva.dva_word[1] = 0;
1171 static arc_buf_hdr_t *
1172 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1174 const dva_t *dva = BP_IDENTITY(bp);
1175 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1176 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1177 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1180 mutex_enter(hash_lock);
1181 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1182 hdr = hdr->b_hash_next) {
1183 if (BUF_EQUAL(spa, dva, birth, hdr)) {
1188 mutex_exit(hash_lock);
1194 * Insert an entry into the hash table. If there is already an element
1195 * equal to elem in the hash table, then the already existing element
1196 * will be returned and the new element will not be inserted.
1197 * Otherwise returns NULL.
1198 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1200 static arc_buf_hdr_t *
1201 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1203 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1204 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1205 arc_buf_hdr_t *fhdr;
1208 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1209 ASSERT(hdr->b_birth != 0);
1210 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1212 if (lockp != NULL) {
1214 mutex_enter(hash_lock);
1216 ASSERT(MUTEX_HELD(hash_lock));
1219 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1220 fhdr = fhdr->b_hash_next, i++) {
1221 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1225 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1226 buf_hash_table.ht_table[idx] = hdr;
1227 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1229 /* collect some hash table performance data */
1231 ARCSTAT_BUMP(arcstat_hash_collisions);
1233 ARCSTAT_BUMP(arcstat_hash_chains);
1235 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1238 ARCSTAT_BUMP(arcstat_hash_elements);
1239 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1245 buf_hash_remove(arc_buf_hdr_t *hdr)
1247 arc_buf_hdr_t *fhdr, **hdrp;
1248 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1250 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1251 ASSERT(HDR_IN_HASH_TABLE(hdr));
1253 hdrp = &buf_hash_table.ht_table[idx];
1254 while ((fhdr = *hdrp) != hdr) {
1255 ASSERT(fhdr != NULL);
1256 hdrp = &fhdr->b_hash_next;
1258 *hdrp = hdr->b_hash_next;
1259 hdr->b_hash_next = NULL;
1260 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1262 /* collect some hash table performance data */
1263 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1265 if (buf_hash_table.ht_table[idx] &&
1266 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1267 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1271 * Global data structures and functions for the buf kmem cache.
1273 static kmem_cache_t *hdr_full_cache;
1274 static kmem_cache_t *hdr_l2only_cache;
1275 static kmem_cache_t *buf_cache;
1282 kmem_free(buf_hash_table.ht_table,
1283 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1284 for (i = 0; i < BUF_LOCKS; i++)
1285 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1286 kmem_cache_destroy(hdr_full_cache);
1287 kmem_cache_destroy(hdr_l2only_cache);
1288 kmem_cache_destroy(buf_cache);
1292 * Constructor callback - called when the cache is empty
1293 * and a new buf is requested.
1297 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1299 arc_buf_hdr_t *hdr = vbuf;
1301 bzero(hdr, HDR_FULL_SIZE);
1302 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1303 refcount_create(&hdr->b_l1hdr.b_refcnt);
1304 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1305 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1306 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1313 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1315 arc_buf_hdr_t *hdr = vbuf;
1317 bzero(hdr, HDR_L2ONLY_SIZE);
1318 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1325 buf_cons(void *vbuf, void *unused, int kmflag)
1327 arc_buf_t *buf = vbuf;
1329 bzero(buf, sizeof (arc_buf_t));
1330 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1331 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1337 * Destructor callback - called when a cached buf is
1338 * no longer required.
1342 hdr_full_dest(void *vbuf, void *unused)
1344 arc_buf_hdr_t *hdr = vbuf;
1346 ASSERT(BUF_EMPTY(hdr));
1347 cv_destroy(&hdr->b_l1hdr.b_cv);
1348 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1349 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1350 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1351 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1356 hdr_l2only_dest(void *vbuf, void *unused)
1358 arc_buf_hdr_t *hdr = vbuf;
1360 ASSERT(BUF_EMPTY(hdr));
1361 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1366 buf_dest(void *vbuf, void *unused)
1368 arc_buf_t *buf = vbuf;
1370 mutex_destroy(&buf->b_evict_lock);
1371 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1375 * Reclaim callback -- invoked when memory is low.
1379 hdr_recl(void *unused)
1381 dprintf("hdr_recl called\n");
1383 * umem calls the reclaim func when we destroy the buf cache,
1384 * which is after we do arc_fini().
1387 cv_signal(&arc_reclaim_thread_cv);
1394 uint64_t hsize = 1ULL << 12;
1398 * The hash table is big enough to fill all of physical memory
1399 * with an average block size of zfs_arc_average_blocksize (default 8K).
1400 * By default, the table will take up
1401 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1403 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1406 buf_hash_table.ht_mask = hsize - 1;
1407 buf_hash_table.ht_table =
1408 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1409 if (buf_hash_table.ht_table == NULL) {
1410 ASSERT(hsize > (1ULL << 8));
1415 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1416 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1417 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1418 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1420 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1421 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1423 for (i = 0; i < 256; i++)
1424 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1425 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1427 for (i = 0; i < BUF_LOCKS; i++) {
1428 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1429 NULL, MUTEX_DEFAULT, NULL);
1434 * Transition between the two allocation states for the arc_buf_hdr struct.
1435 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1436 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1437 * version is used when a cache buffer is only in the L2ARC in order to reduce
1440 static arc_buf_hdr_t *
1441 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1443 ASSERT(HDR_HAS_L2HDR(hdr));
1445 arc_buf_hdr_t *nhdr;
1446 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1448 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1449 (old == hdr_l2only_cache && new == hdr_full_cache));
1451 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1453 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1454 buf_hash_remove(hdr);
1456 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1458 if (new == hdr_full_cache) {
1459 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1461 * arc_access and arc_change_state need to be aware that a
1462 * header has just come out of L2ARC, so we set its state to
1463 * l2c_only even though it's about to change.
1465 nhdr->b_l1hdr.b_state = arc_l2c_only;
1467 /* Verify previous threads set to NULL before freeing */
1468 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1470 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1471 ASSERT0(hdr->b_l1hdr.b_datacnt);
1474 * If we've reached here, We must have been called from
1475 * arc_evict_hdr(), as such we should have already been
1476 * removed from any ghost list we were previously on
1477 * (which protects us from racing with arc_evict_state),
1478 * thus no locking is needed during this check.
1480 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1483 * A buffer must not be moved into the arc_l2c_only
1484 * state if it's not finished being written out to the
1485 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1486 * might try to be accessed, even though it was removed.
1488 VERIFY(!HDR_L2_WRITING(hdr));
1489 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1491 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1494 * The header has been reallocated so we need to re-insert it into any
1497 (void) buf_hash_insert(nhdr, NULL);
1499 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1501 mutex_enter(&dev->l2ad_mtx);
1504 * We must place the realloc'ed header back into the list at
1505 * the same spot. Otherwise, if it's placed earlier in the list,
1506 * l2arc_write_buffers() could find it during the function's
1507 * write phase, and try to write it out to the l2arc.
1509 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1510 list_remove(&dev->l2ad_buflist, hdr);
1512 mutex_exit(&dev->l2ad_mtx);
1515 * Since we're using the pointer address as the tag when
1516 * incrementing and decrementing the l2ad_alloc refcount, we
1517 * must remove the old pointer (that we're about to destroy) and
1518 * add the new pointer to the refcount. Otherwise we'd remove
1519 * the wrong pointer address when calling arc_hdr_destroy() later.
1522 (void) refcount_remove_many(&dev->l2ad_alloc,
1523 hdr->b_l2hdr.b_asize, hdr);
1525 (void) refcount_add_many(&dev->l2ad_alloc,
1526 nhdr->b_l2hdr.b_asize, nhdr);
1528 buf_discard_identity(hdr);
1529 hdr->b_freeze_cksum = NULL;
1530 kmem_cache_free(old, hdr);
1536 #define ARC_MINTIME (hz>>4) /* 62 ms */
1539 arc_cksum_verify(arc_buf_t *buf)
1543 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1546 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1547 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1548 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1551 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1552 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1553 panic("buffer modified while frozen!");
1554 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1558 arc_cksum_equal(arc_buf_t *buf)
1563 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1564 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1565 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1566 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1572 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1574 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1577 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1578 if (buf->b_hdr->b_freeze_cksum != NULL) {
1579 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1582 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1583 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1584 buf->b_hdr->b_freeze_cksum);
1585 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1588 #endif /* illumos */
1593 typedef struct procctl {
1601 arc_buf_unwatch(arc_buf_t *buf)
1608 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1609 ctl.prwatch.pr_size = 0;
1610 ctl.prwatch.pr_wflags = 0;
1611 result = write(arc_procfd, &ctl, sizeof (ctl));
1612 ASSERT3U(result, ==, sizeof (ctl));
1619 arc_buf_watch(arc_buf_t *buf)
1626 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1627 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1628 ctl.prwatch.pr_wflags = WA_WRITE;
1629 result = write(arc_procfd, &ctl, sizeof (ctl));
1630 ASSERT3U(result, ==, sizeof (ctl));
1634 #endif /* illumos */
1636 static arc_buf_contents_t
1637 arc_buf_type(arc_buf_hdr_t *hdr)
1639 if (HDR_ISTYPE_METADATA(hdr)) {
1640 return (ARC_BUFC_METADATA);
1642 return (ARC_BUFC_DATA);
1647 arc_bufc_to_flags(arc_buf_contents_t type)
1651 /* metadata field is 0 if buffer contains normal data */
1653 case ARC_BUFC_METADATA:
1654 return (ARC_FLAG_BUFC_METADATA);
1658 panic("undefined ARC buffer type!");
1659 return ((uint32_t)-1);
1663 arc_buf_thaw(arc_buf_t *buf)
1665 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1666 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1667 panic("modifying non-anon buffer!");
1668 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1669 panic("modifying buffer while i/o in progress!");
1670 arc_cksum_verify(buf);
1673 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1674 if (buf->b_hdr->b_freeze_cksum != NULL) {
1675 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1676 buf->b_hdr->b_freeze_cksum = NULL;
1680 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1681 if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1682 kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1683 buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1687 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1690 arc_buf_unwatch(buf);
1691 #endif /* illumos */
1695 arc_buf_freeze(arc_buf_t *buf)
1697 kmutex_t *hash_lock;
1699 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1702 hash_lock = HDR_LOCK(buf->b_hdr);
1703 mutex_enter(hash_lock);
1705 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1706 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1707 arc_cksum_compute(buf, B_FALSE);
1708 mutex_exit(hash_lock);
1713 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1715 ASSERT(HDR_HAS_L1HDR(hdr));
1716 ASSERT(MUTEX_HELD(hash_lock));
1717 arc_state_t *state = hdr->b_l1hdr.b_state;
1719 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1720 (state != arc_anon)) {
1721 /* We don't use the L2-only state list. */
1722 if (state != arc_l2c_only) {
1723 arc_buf_contents_t type = arc_buf_type(hdr);
1724 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1725 multilist_t *list = &state->arcs_list[type];
1726 uint64_t *size = &state->arcs_lsize[type];
1728 multilist_remove(list, hdr);
1730 if (GHOST_STATE(state)) {
1731 ASSERT0(hdr->b_l1hdr.b_datacnt);
1732 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1733 delta = hdr->b_size;
1736 ASSERT3U(*size, >=, delta);
1737 atomic_add_64(size, -delta);
1739 /* remove the prefetch flag if we get a reference */
1740 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1745 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1748 arc_state_t *state = hdr->b_l1hdr.b_state;
1750 ASSERT(HDR_HAS_L1HDR(hdr));
1751 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1752 ASSERT(!GHOST_STATE(state));
1755 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1756 * check to prevent usage of the arc_l2c_only list.
1758 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1759 (state != arc_anon)) {
1760 arc_buf_contents_t type = arc_buf_type(hdr);
1761 multilist_t *list = &state->arcs_list[type];
1762 uint64_t *size = &state->arcs_lsize[type];
1764 multilist_insert(list, hdr);
1766 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1767 atomic_add_64(size, hdr->b_size *
1768 hdr->b_l1hdr.b_datacnt);
1774 * Move the supplied buffer to the indicated state. The hash lock
1775 * for the buffer must be held by the caller.
1778 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1779 kmutex_t *hash_lock)
1781 arc_state_t *old_state;
1784 uint64_t from_delta, to_delta;
1785 arc_buf_contents_t buftype = arc_buf_type(hdr);
1788 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1789 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1790 * L1 hdr doesn't always exist when we change state to arc_anon before
1791 * destroying a header, in which case reallocating to add the L1 hdr is
1794 if (HDR_HAS_L1HDR(hdr)) {
1795 old_state = hdr->b_l1hdr.b_state;
1796 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1797 datacnt = hdr->b_l1hdr.b_datacnt;
1799 old_state = arc_l2c_only;
1804 ASSERT(MUTEX_HELD(hash_lock));
1805 ASSERT3P(new_state, !=, old_state);
1806 ASSERT(refcnt == 0 || datacnt > 0);
1807 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1808 ASSERT(old_state != arc_anon || datacnt <= 1);
1810 from_delta = to_delta = datacnt * hdr->b_size;
1813 * If this buffer is evictable, transfer it from the
1814 * old state list to the new state list.
1817 if (old_state != arc_anon && old_state != arc_l2c_only) {
1818 uint64_t *size = &old_state->arcs_lsize[buftype];
1820 ASSERT(HDR_HAS_L1HDR(hdr));
1821 multilist_remove(&old_state->arcs_list[buftype], hdr);
1824 * If prefetching out of the ghost cache,
1825 * we will have a non-zero datacnt.
1827 if (GHOST_STATE(old_state) && datacnt == 0) {
1828 /* ghost elements have a ghost size */
1829 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1830 from_delta = hdr->b_size;
1832 ASSERT3U(*size, >=, from_delta);
1833 atomic_add_64(size, -from_delta);
1835 if (new_state != arc_anon && new_state != arc_l2c_only) {
1836 uint64_t *size = &new_state->arcs_lsize[buftype];
1839 * An L1 header always exists here, since if we're
1840 * moving to some L1-cached state (i.e. not l2c_only or
1841 * anonymous), we realloc the header to add an L1hdr
1844 ASSERT(HDR_HAS_L1HDR(hdr));
1845 multilist_insert(&new_state->arcs_list[buftype], hdr);
1847 /* ghost elements have a ghost size */
1848 if (GHOST_STATE(new_state)) {
1850 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1851 to_delta = hdr->b_size;
1853 atomic_add_64(size, to_delta);
1857 ASSERT(!BUF_EMPTY(hdr));
1858 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1859 buf_hash_remove(hdr);
1861 /* adjust state sizes (ignore arc_l2c_only) */
1863 if (to_delta && new_state != arc_l2c_only) {
1864 ASSERT(HDR_HAS_L1HDR(hdr));
1865 if (GHOST_STATE(new_state)) {
1869 * We moving a header to a ghost state, we first
1870 * remove all arc buffers. Thus, we'll have a
1871 * datacnt of zero, and no arc buffer to use for
1872 * the reference. As a result, we use the arc
1873 * header pointer for the reference.
1875 (void) refcount_add_many(&new_state->arcs_size,
1878 ASSERT3U(datacnt, !=, 0);
1881 * Each individual buffer holds a unique reference,
1882 * thus we must remove each of these references one
1885 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1886 buf = buf->b_next) {
1887 (void) refcount_add_many(&new_state->arcs_size,
1893 if (from_delta && old_state != arc_l2c_only) {
1894 ASSERT(HDR_HAS_L1HDR(hdr));
1895 if (GHOST_STATE(old_state)) {
1897 * When moving a header off of a ghost state,
1898 * there's the possibility for datacnt to be
1899 * non-zero. This is because we first add the
1900 * arc buffer to the header prior to changing
1901 * the header's state. Since we used the header
1902 * for the reference when putting the header on
1903 * the ghost state, we must balance that and use
1904 * the header when removing off the ghost state
1905 * (even though datacnt is non zero).
1908 IMPLY(datacnt == 0, new_state == arc_anon ||
1909 new_state == arc_l2c_only);
1911 (void) refcount_remove_many(&old_state->arcs_size,
1914 ASSERT3P(datacnt, !=, 0);
1917 * Each individual buffer holds a unique reference,
1918 * thus we must remove each of these references one
1921 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1922 buf = buf->b_next) {
1923 (void) refcount_remove_many(
1924 &old_state->arcs_size, hdr->b_size, buf);
1929 if (HDR_HAS_L1HDR(hdr))
1930 hdr->b_l1hdr.b_state = new_state;
1933 * L2 headers should never be on the L2 state list since they don't
1934 * have L1 headers allocated.
1936 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1937 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1941 arc_space_consume(uint64_t space, arc_space_type_t type)
1943 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1946 case ARC_SPACE_DATA:
1947 ARCSTAT_INCR(arcstat_data_size, space);
1949 case ARC_SPACE_META:
1950 ARCSTAT_INCR(arcstat_metadata_size, space);
1952 case ARC_SPACE_OTHER:
1953 ARCSTAT_INCR(arcstat_other_size, space);
1955 case ARC_SPACE_HDRS:
1956 ARCSTAT_INCR(arcstat_hdr_size, space);
1958 case ARC_SPACE_L2HDRS:
1959 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1963 if (type != ARC_SPACE_DATA)
1964 ARCSTAT_INCR(arcstat_meta_used, space);
1966 atomic_add_64(&arc_size, space);
1970 arc_space_return(uint64_t space, arc_space_type_t type)
1972 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1975 case ARC_SPACE_DATA:
1976 ARCSTAT_INCR(arcstat_data_size, -space);
1978 case ARC_SPACE_META:
1979 ARCSTAT_INCR(arcstat_metadata_size, -space);
1981 case ARC_SPACE_OTHER:
1982 ARCSTAT_INCR(arcstat_other_size, -space);
1984 case ARC_SPACE_HDRS:
1985 ARCSTAT_INCR(arcstat_hdr_size, -space);
1987 case ARC_SPACE_L2HDRS:
1988 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1992 if (type != ARC_SPACE_DATA) {
1993 ASSERT(arc_meta_used >= space);
1994 if (arc_meta_max < arc_meta_used)
1995 arc_meta_max = arc_meta_used;
1996 ARCSTAT_INCR(arcstat_meta_used, -space);
1999 ASSERT(arc_size >= space);
2000 atomic_add_64(&arc_size, -space);
2004 arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2009 ASSERT3U(size, >, 0);
2010 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2011 ASSERT(BUF_EMPTY(hdr));
2012 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
2014 hdr->b_spa = spa_load_guid(spa);
2016 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2019 buf->b_efunc = NULL;
2020 buf->b_private = NULL;
2023 hdr->b_flags = arc_bufc_to_flags(type);
2024 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
2026 hdr->b_l1hdr.b_buf = buf;
2027 hdr->b_l1hdr.b_state = arc_anon;
2028 hdr->b_l1hdr.b_arc_access = 0;
2029 hdr->b_l1hdr.b_datacnt = 1;
2030 hdr->b_l1hdr.b_tmp_cdata = NULL;
2032 arc_get_data_buf(buf);
2033 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2034 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2039 static char *arc_onloan_tag = "onloan";
2042 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2043 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2044 * buffers must be returned to the arc before they can be used by the DMU or
2048 arc_loan_buf(spa_t *spa, int size)
2052 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2054 atomic_add_64(&arc_loaned_bytes, size);
2059 * Return a loaned arc buffer to the arc.
2062 arc_return_buf(arc_buf_t *buf, void *tag)
2064 arc_buf_hdr_t *hdr = buf->b_hdr;
2066 ASSERT(buf->b_data != NULL);
2067 ASSERT(HDR_HAS_L1HDR(hdr));
2068 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2069 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2071 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2074 /* Detach an arc_buf from a dbuf (tag) */
2076 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2078 arc_buf_hdr_t *hdr = buf->b_hdr;
2080 ASSERT(buf->b_data != NULL);
2081 ASSERT(HDR_HAS_L1HDR(hdr));
2082 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2083 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2084 buf->b_efunc = NULL;
2085 buf->b_private = NULL;
2087 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2091 arc_buf_clone(arc_buf_t *from)
2094 arc_buf_hdr_t *hdr = from->b_hdr;
2095 uint64_t size = hdr->b_size;
2097 ASSERT(HDR_HAS_L1HDR(hdr));
2098 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2100 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2103 buf->b_efunc = NULL;
2104 buf->b_private = NULL;
2105 buf->b_next = hdr->b_l1hdr.b_buf;
2106 hdr->b_l1hdr.b_buf = buf;
2107 arc_get_data_buf(buf);
2108 bcopy(from->b_data, buf->b_data, size);
2111 * This buffer already exists in the arc so create a duplicate
2112 * copy for the caller. If the buffer is associated with user data
2113 * then track the size and number of duplicates. These stats will be
2114 * updated as duplicate buffers are created and destroyed.
2116 if (HDR_ISTYPE_DATA(hdr)) {
2117 ARCSTAT_BUMP(arcstat_duplicate_buffers);
2118 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2120 hdr->b_l1hdr.b_datacnt += 1;
2125 arc_buf_add_ref(arc_buf_t *buf, void* tag)
2128 kmutex_t *hash_lock;
2131 * Check to see if this buffer is evicted. Callers
2132 * must verify b_data != NULL to know if the add_ref
2135 mutex_enter(&buf->b_evict_lock);
2136 if (buf->b_data == NULL) {
2137 mutex_exit(&buf->b_evict_lock);
2140 hash_lock = HDR_LOCK(buf->b_hdr);
2141 mutex_enter(hash_lock);
2143 ASSERT(HDR_HAS_L1HDR(hdr));
2144 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2145 mutex_exit(&buf->b_evict_lock);
2147 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2148 hdr->b_l1hdr.b_state == arc_mfu);
2150 add_reference(hdr, hash_lock, tag);
2151 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2152 arc_access(hdr, hash_lock);
2153 mutex_exit(hash_lock);
2154 ARCSTAT_BUMP(arcstat_hits);
2155 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2156 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2157 data, metadata, hits);
2161 arc_buf_free_on_write(void *data, size_t size,
2162 void (*free_func)(void *, size_t))
2164 l2arc_data_free_t *df;
2166 df = kmem_alloc(sizeof (*df), KM_SLEEP);
2167 df->l2df_data = data;
2168 df->l2df_size = size;
2169 df->l2df_func = free_func;
2170 mutex_enter(&l2arc_free_on_write_mtx);
2171 list_insert_head(l2arc_free_on_write, df);
2172 mutex_exit(&l2arc_free_on_write_mtx);
2176 * Free the arc data buffer. If it is an l2arc write in progress,
2177 * the buffer is placed on l2arc_free_on_write to be freed later.
2180 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2182 arc_buf_hdr_t *hdr = buf->b_hdr;
2184 if (HDR_L2_WRITING(hdr)) {
2185 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2186 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2188 free_func(buf->b_data, hdr->b_size);
2193 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2195 ASSERT(HDR_HAS_L2HDR(hdr));
2196 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2199 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2200 * that doesn't exist, the header is in the arc_l2c_only state,
2201 * and there isn't anything to free (it's already been freed).
2203 if (!HDR_HAS_L1HDR(hdr))
2207 * The header isn't being written to the l2arc device, thus it
2208 * shouldn't have a b_tmp_cdata to free.
2210 if (!HDR_L2_WRITING(hdr)) {
2211 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2216 * The header does not have compression enabled. This can be due
2217 * to the buffer not being compressible, or because we're
2218 * freeing the buffer before the second phase of
2219 * l2arc_write_buffer() has started (which does the compression
2220 * step). In either case, b_tmp_cdata does not point to a
2221 * separately compressed buffer, so there's nothing to free (it
2222 * points to the same buffer as the arc_buf_t's b_data field).
2224 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_OFF) {
2225 hdr->b_l1hdr.b_tmp_cdata = NULL;
2230 * There's nothing to free since the buffer was all zero's and
2231 * compressed to a zero length buffer.
2233 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_EMPTY) {
2234 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2238 ASSERT(L2ARC_IS_VALID_COMPRESS(hdr->b_l2hdr.b_compress));
2240 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
2241 hdr->b_size, zio_data_buf_free);
2243 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2244 hdr->b_l1hdr.b_tmp_cdata = NULL;
2248 * Free up buf->b_data and if 'remove' is set, then pull the
2249 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2252 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2256 /* free up data associated with the buf */
2257 if (buf->b_data != NULL) {
2258 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2259 uint64_t size = buf->b_hdr->b_size;
2260 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2262 arc_cksum_verify(buf);
2264 arc_buf_unwatch(buf);
2265 #endif /* illumos */
2267 if (type == ARC_BUFC_METADATA) {
2268 arc_buf_data_free(buf, zio_buf_free);
2269 arc_space_return(size, ARC_SPACE_META);
2271 ASSERT(type == ARC_BUFC_DATA);
2272 arc_buf_data_free(buf, zio_data_buf_free);
2273 arc_space_return(size, ARC_SPACE_DATA);
2276 /* protected by hash lock, if in the hash table */
2277 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2278 uint64_t *cnt = &state->arcs_lsize[type];
2280 ASSERT(refcount_is_zero(
2281 &buf->b_hdr->b_l1hdr.b_refcnt));
2282 ASSERT(state != arc_anon && state != arc_l2c_only);
2284 ASSERT3U(*cnt, >=, size);
2285 atomic_add_64(cnt, -size);
2288 (void) refcount_remove_many(&state->arcs_size, size, buf);
2292 * If we're destroying a duplicate buffer make sure
2293 * that the appropriate statistics are updated.
2295 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2296 HDR_ISTYPE_DATA(buf->b_hdr)) {
2297 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2298 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2300 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2301 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2304 /* only remove the buf if requested */
2308 /* remove the buf from the hdr list */
2309 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2310 bufp = &(*bufp)->b_next)
2312 *bufp = buf->b_next;
2315 ASSERT(buf->b_efunc == NULL);
2317 /* clean up the buf */
2319 kmem_cache_free(buf_cache, buf);
2323 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2325 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2326 l2arc_dev_t *dev = l2hdr->b_dev;
2328 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2329 ASSERT(HDR_HAS_L2HDR(hdr));
2331 list_remove(&dev->l2ad_buflist, hdr);
2334 * We don't want to leak the b_tmp_cdata buffer that was
2335 * allocated in l2arc_write_buffers()
2337 arc_buf_l2_cdata_free(hdr);
2340 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2341 * this header is being processed by l2arc_write_buffers() (i.e.
2342 * it's in the first stage of l2arc_write_buffers()).
2343 * Re-affirming that truth here, just to serve as a reminder. If
2344 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2345 * may not have its HDR_L2_WRITING flag set. (the write may have
2346 * completed, in which case HDR_L2_WRITING will be false and the
2347 * b_daddr field will point to the address of the buffer on disk).
2349 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2352 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2353 * l2arc_write_buffers(). Since we've just removed this header
2354 * from the l2arc buffer list, this header will never reach the
2355 * second stage of l2arc_write_buffers(), which increments the
2356 * accounting stats for this header. Thus, we must be careful
2357 * not to decrement them for this header either.
2359 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2360 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2361 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2363 vdev_space_update(dev->l2ad_vdev,
2364 -l2hdr->b_asize, 0, 0);
2366 (void) refcount_remove_many(&dev->l2ad_alloc,
2367 l2hdr->b_asize, hdr);
2370 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2374 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2376 if (HDR_HAS_L1HDR(hdr)) {
2377 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2378 hdr->b_l1hdr.b_datacnt > 0);
2379 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2380 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2382 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2383 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2385 if (HDR_HAS_L2HDR(hdr)) {
2386 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2387 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2390 mutex_enter(&dev->l2ad_mtx);
2393 * Even though we checked this conditional above, we
2394 * need to check this again now that we have the
2395 * l2ad_mtx. This is because we could be racing with
2396 * another thread calling l2arc_evict() which might have
2397 * destroyed this header's L2 portion as we were waiting
2398 * to acquire the l2ad_mtx. If that happens, we don't
2399 * want to re-destroy the header's L2 portion.
2401 if (HDR_HAS_L2HDR(hdr)) {
2402 if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
2403 trim_map_free(dev->l2ad_vdev,
2404 hdr->b_l2hdr.b_daddr,
2405 hdr->b_l2hdr.b_asize, 0);
2406 arc_hdr_l2hdr_destroy(hdr);
2410 mutex_exit(&dev->l2ad_mtx);
2413 if (!BUF_EMPTY(hdr))
2414 buf_discard_identity(hdr);
2416 if (hdr->b_freeze_cksum != NULL) {
2417 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2418 hdr->b_freeze_cksum = NULL;
2421 if (HDR_HAS_L1HDR(hdr)) {
2422 while (hdr->b_l1hdr.b_buf) {
2423 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2425 if (buf->b_efunc != NULL) {
2426 mutex_enter(&arc_user_evicts_lock);
2427 mutex_enter(&buf->b_evict_lock);
2428 ASSERT(buf->b_hdr != NULL);
2429 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2430 hdr->b_l1hdr.b_buf = buf->b_next;
2431 buf->b_hdr = &arc_eviction_hdr;
2432 buf->b_next = arc_eviction_list;
2433 arc_eviction_list = buf;
2434 mutex_exit(&buf->b_evict_lock);
2435 cv_signal(&arc_user_evicts_cv);
2436 mutex_exit(&arc_user_evicts_lock);
2438 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2442 if (hdr->b_l1hdr.b_thawed != NULL) {
2443 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2444 hdr->b_l1hdr.b_thawed = NULL;
2449 ASSERT3P(hdr->b_hash_next, ==, NULL);
2450 if (HDR_HAS_L1HDR(hdr)) {
2451 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2452 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2453 kmem_cache_free(hdr_full_cache, hdr);
2455 kmem_cache_free(hdr_l2only_cache, hdr);
2460 arc_buf_free(arc_buf_t *buf, void *tag)
2462 arc_buf_hdr_t *hdr = buf->b_hdr;
2463 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2465 ASSERT(buf->b_efunc == NULL);
2466 ASSERT(buf->b_data != NULL);
2469 kmutex_t *hash_lock = HDR_LOCK(hdr);
2471 mutex_enter(hash_lock);
2473 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2475 (void) remove_reference(hdr, hash_lock, tag);
2476 if (hdr->b_l1hdr.b_datacnt > 1) {
2477 arc_buf_destroy(buf, TRUE);
2479 ASSERT(buf == hdr->b_l1hdr.b_buf);
2480 ASSERT(buf->b_efunc == NULL);
2481 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2483 mutex_exit(hash_lock);
2484 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2487 * We are in the middle of an async write. Don't destroy
2488 * this buffer unless the write completes before we finish
2489 * decrementing the reference count.
2491 mutex_enter(&arc_user_evicts_lock);
2492 (void) remove_reference(hdr, NULL, tag);
2493 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2494 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2495 mutex_exit(&arc_user_evicts_lock);
2497 arc_hdr_destroy(hdr);
2499 if (remove_reference(hdr, NULL, tag) > 0)
2500 arc_buf_destroy(buf, TRUE);
2502 arc_hdr_destroy(hdr);
2507 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2509 arc_buf_hdr_t *hdr = buf->b_hdr;
2510 kmutex_t *hash_lock = HDR_LOCK(hdr);
2511 boolean_t no_callback = (buf->b_efunc == NULL);
2513 if (hdr->b_l1hdr.b_state == arc_anon) {
2514 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2515 arc_buf_free(buf, tag);
2516 return (no_callback);
2519 mutex_enter(hash_lock);
2521 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2522 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2523 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2524 ASSERT(buf->b_data != NULL);
2526 (void) remove_reference(hdr, hash_lock, tag);
2527 if (hdr->b_l1hdr.b_datacnt > 1) {
2529 arc_buf_destroy(buf, TRUE);
2530 } else if (no_callback) {
2531 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2532 ASSERT(buf->b_efunc == NULL);
2533 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2535 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2536 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2537 mutex_exit(hash_lock);
2538 return (no_callback);
2542 arc_buf_size(arc_buf_t *buf)
2544 return (buf->b_hdr->b_size);
2548 * Called from the DMU to determine if the current buffer should be
2549 * evicted. In order to ensure proper locking, the eviction must be initiated
2550 * from the DMU. Return true if the buffer is associated with user data and
2551 * duplicate buffers still exist.
2554 arc_buf_eviction_needed(arc_buf_t *buf)
2557 boolean_t evict_needed = B_FALSE;
2559 if (zfs_disable_dup_eviction)
2562 mutex_enter(&buf->b_evict_lock);
2566 * We are in arc_do_user_evicts(); let that function
2567 * perform the eviction.
2569 ASSERT(buf->b_data == NULL);
2570 mutex_exit(&buf->b_evict_lock);
2572 } else if (buf->b_data == NULL) {
2574 * We have already been added to the arc eviction list;
2575 * recommend eviction.
2577 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2578 mutex_exit(&buf->b_evict_lock);
2582 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2583 evict_needed = B_TRUE;
2585 mutex_exit(&buf->b_evict_lock);
2586 return (evict_needed);
2590 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2591 * state of the header is dependent on it's state prior to entering this
2592 * function. The following transitions are possible:
2594 * - arc_mru -> arc_mru_ghost
2595 * - arc_mfu -> arc_mfu_ghost
2596 * - arc_mru_ghost -> arc_l2c_only
2597 * - arc_mru_ghost -> deleted
2598 * - arc_mfu_ghost -> arc_l2c_only
2599 * - arc_mfu_ghost -> deleted
2602 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2604 arc_state_t *evicted_state, *state;
2605 int64_t bytes_evicted = 0;
2607 ASSERT(MUTEX_HELD(hash_lock));
2608 ASSERT(HDR_HAS_L1HDR(hdr));
2610 state = hdr->b_l1hdr.b_state;
2611 if (GHOST_STATE(state)) {
2612 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2613 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2616 * l2arc_write_buffers() relies on a header's L1 portion
2617 * (i.e. it's b_tmp_cdata field) during it's write phase.
2618 * Thus, we cannot push a header onto the arc_l2c_only
2619 * state (removing it's L1 piece) until the header is
2620 * done being written to the l2arc.
2622 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2623 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2624 return (bytes_evicted);
2627 ARCSTAT_BUMP(arcstat_deleted);
2628 bytes_evicted += hdr->b_size;
2630 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2632 if (HDR_HAS_L2HDR(hdr)) {
2634 * This buffer is cached on the 2nd Level ARC;
2635 * don't destroy the header.
2637 arc_change_state(arc_l2c_only, hdr, hash_lock);
2639 * dropping from L1+L2 cached to L2-only,
2640 * realloc to remove the L1 header.
2642 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2645 arc_change_state(arc_anon, hdr, hash_lock);
2646 arc_hdr_destroy(hdr);
2648 return (bytes_evicted);
2651 ASSERT(state == arc_mru || state == arc_mfu);
2652 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2654 /* prefetch buffers have a minimum lifespan */
2655 if (HDR_IO_IN_PROGRESS(hdr) ||
2656 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2657 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2658 arc_min_prefetch_lifespan)) {
2659 ARCSTAT_BUMP(arcstat_evict_skip);
2660 return (bytes_evicted);
2663 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2664 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2665 while (hdr->b_l1hdr.b_buf) {
2666 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2667 if (!mutex_tryenter(&buf->b_evict_lock)) {
2668 ARCSTAT_BUMP(arcstat_mutex_miss);
2671 if (buf->b_data != NULL)
2672 bytes_evicted += hdr->b_size;
2673 if (buf->b_efunc != NULL) {
2674 mutex_enter(&arc_user_evicts_lock);
2675 arc_buf_destroy(buf, FALSE);
2676 hdr->b_l1hdr.b_buf = buf->b_next;
2677 buf->b_hdr = &arc_eviction_hdr;
2678 buf->b_next = arc_eviction_list;
2679 arc_eviction_list = buf;
2680 cv_signal(&arc_user_evicts_cv);
2681 mutex_exit(&arc_user_evicts_lock);
2682 mutex_exit(&buf->b_evict_lock);
2684 mutex_exit(&buf->b_evict_lock);
2685 arc_buf_destroy(buf, TRUE);
2689 if (HDR_HAS_L2HDR(hdr)) {
2690 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2692 if (l2arc_write_eligible(hdr->b_spa, hdr))
2693 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2695 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2698 if (hdr->b_l1hdr.b_datacnt == 0) {
2699 arc_change_state(evicted_state, hdr, hash_lock);
2700 ASSERT(HDR_IN_HASH_TABLE(hdr));
2701 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2702 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2703 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2706 return (bytes_evicted);
2710 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2711 uint64_t spa, int64_t bytes)
2713 multilist_sublist_t *mls;
2714 uint64_t bytes_evicted = 0;
2716 kmutex_t *hash_lock;
2717 int evict_count = 0;
2719 ASSERT3P(marker, !=, NULL);
2720 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2722 mls = multilist_sublist_lock(ml, idx);
2724 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2725 hdr = multilist_sublist_prev(mls, marker)) {
2726 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2727 (evict_count >= zfs_arc_evict_batch_limit))
2731 * To keep our iteration location, move the marker
2732 * forward. Since we're not holding hdr's hash lock, we
2733 * must be very careful and not remove 'hdr' from the
2734 * sublist. Otherwise, other consumers might mistake the
2735 * 'hdr' as not being on a sublist when they call the
2736 * multilist_link_active() function (they all rely on
2737 * the hash lock protecting concurrent insertions and
2738 * removals). multilist_sublist_move_forward() was
2739 * specifically implemented to ensure this is the case
2740 * (only 'marker' will be removed and re-inserted).
2742 multilist_sublist_move_forward(mls, marker);
2745 * The only case where the b_spa field should ever be
2746 * zero, is the marker headers inserted by
2747 * arc_evict_state(). It's possible for multiple threads
2748 * to be calling arc_evict_state() concurrently (e.g.
2749 * dsl_pool_close() and zio_inject_fault()), so we must
2750 * skip any markers we see from these other threads.
2752 if (hdr->b_spa == 0)
2755 /* we're only interested in evicting buffers of a certain spa */
2756 if (spa != 0 && hdr->b_spa != spa) {
2757 ARCSTAT_BUMP(arcstat_evict_skip);
2761 hash_lock = HDR_LOCK(hdr);
2764 * We aren't calling this function from any code path
2765 * that would already be holding a hash lock, so we're
2766 * asserting on this assumption to be defensive in case
2767 * this ever changes. Without this check, it would be
2768 * possible to incorrectly increment arcstat_mutex_miss
2769 * below (e.g. if the code changed such that we called
2770 * this function with a hash lock held).
2772 ASSERT(!MUTEX_HELD(hash_lock));
2774 if (mutex_tryenter(hash_lock)) {
2775 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2776 mutex_exit(hash_lock);
2778 bytes_evicted += evicted;
2781 * If evicted is zero, arc_evict_hdr() must have
2782 * decided to skip this header, don't increment
2783 * evict_count in this case.
2789 * If arc_size isn't overflowing, signal any
2790 * threads that might happen to be waiting.
2792 * For each header evicted, we wake up a single
2793 * thread. If we used cv_broadcast, we could
2794 * wake up "too many" threads causing arc_size
2795 * to significantly overflow arc_c; since
2796 * arc_get_data_buf() doesn't check for overflow
2797 * when it's woken up (it doesn't because it's
2798 * possible for the ARC to be overflowing while
2799 * full of un-evictable buffers, and the
2800 * function should proceed in this case).
2802 * If threads are left sleeping, due to not
2803 * using cv_broadcast, they will be woken up
2804 * just before arc_reclaim_thread() sleeps.
2806 mutex_enter(&arc_reclaim_lock);
2807 if (!arc_is_overflowing())
2808 cv_signal(&arc_reclaim_waiters_cv);
2809 mutex_exit(&arc_reclaim_lock);
2811 ARCSTAT_BUMP(arcstat_mutex_miss);
2815 multilist_sublist_unlock(mls);
2817 return (bytes_evicted);
2821 * Evict buffers from the given arc state, until we've removed the
2822 * specified number of bytes. Move the removed buffers to the
2823 * appropriate evict state.
2825 * This function makes a "best effort". It skips over any buffers
2826 * it can't get a hash_lock on, and so, may not catch all candidates.
2827 * It may also return without evicting as much space as requested.
2829 * If bytes is specified using the special value ARC_EVICT_ALL, this
2830 * will evict all available (i.e. unlocked and evictable) buffers from
2831 * the given arc state; which is used by arc_flush().
2834 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2835 arc_buf_contents_t type)
2837 uint64_t total_evicted = 0;
2838 multilist_t *ml = &state->arcs_list[type];
2840 arc_buf_hdr_t **markers;
2842 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2844 num_sublists = multilist_get_num_sublists(ml);
2847 * If we've tried to evict from each sublist, made some
2848 * progress, but still have not hit the target number of bytes
2849 * to evict, we want to keep trying. The markers allow us to
2850 * pick up where we left off for each individual sublist, rather
2851 * than starting from the tail each time.
2853 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2854 for (int i = 0; i < num_sublists; i++) {
2855 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2858 * A b_spa of 0 is used to indicate that this header is
2859 * a marker. This fact is used in arc_adjust_type() and
2860 * arc_evict_state_impl().
2862 markers[i]->b_spa = 0;
2864 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2865 multilist_sublist_insert_tail(mls, markers[i]);
2866 multilist_sublist_unlock(mls);
2870 * While we haven't hit our target number of bytes to evict, or
2871 * we're evicting all available buffers.
2873 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2875 * Start eviction using a randomly selected sublist,
2876 * this is to try and evenly balance eviction across all
2877 * sublists. Always starting at the same sublist
2878 * (e.g. index 0) would cause evictions to favor certain
2879 * sublists over others.
2881 int sublist_idx = multilist_get_random_index(ml);
2882 uint64_t scan_evicted = 0;
2884 for (int i = 0; i < num_sublists; i++) {
2885 uint64_t bytes_remaining;
2886 uint64_t bytes_evicted;
2888 if (bytes == ARC_EVICT_ALL)
2889 bytes_remaining = ARC_EVICT_ALL;
2890 else if (total_evicted < bytes)
2891 bytes_remaining = bytes - total_evicted;
2895 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2896 markers[sublist_idx], spa, bytes_remaining);
2898 scan_evicted += bytes_evicted;
2899 total_evicted += bytes_evicted;
2901 /* we've reached the end, wrap to the beginning */
2902 if (++sublist_idx >= num_sublists)
2907 * If we didn't evict anything during this scan, we have
2908 * no reason to believe we'll evict more during another
2909 * scan, so break the loop.
2911 if (scan_evicted == 0) {
2912 /* This isn't possible, let's make that obvious */
2913 ASSERT3S(bytes, !=, 0);
2916 * When bytes is ARC_EVICT_ALL, the only way to
2917 * break the loop is when scan_evicted is zero.
2918 * In that case, we actually have evicted enough,
2919 * so we don't want to increment the kstat.
2921 if (bytes != ARC_EVICT_ALL) {
2922 ASSERT3S(total_evicted, <, bytes);
2923 ARCSTAT_BUMP(arcstat_evict_not_enough);
2930 for (int i = 0; i < num_sublists; i++) {
2931 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2932 multilist_sublist_remove(mls, markers[i]);
2933 multilist_sublist_unlock(mls);
2935 kmem_cache_free(hdr_full_cache, markers[i]);
2937 kmem_free(markers, sizeof (*markers) * num_sublists);
2939 return (total_evicted);
2943 * Flush all "evictable" data of the given type from the arc state
2944 * specified. This will not evict any "active" buffers (i.e. referenced).
2946 * When 'retry' is set to FALSE, the function will make a single pass
2947 * over the state and evict any buffers that it can. Since it doesn't
2948 * continually retry the eviction, it might end up leaving some buffers
2949 * in the ARC due to lock misses.
2951 * When 'retry' is set to TRUE, the function will continually retry the
2952 * eviction until *all* evictable buffers have been removed from the
2953 * state. As a result, if concurrent insertions into the state are
2954 * allowed (e.g. if the ARC isn't shutting down), this function might
2955 * wind up in an infinite loop, continually trying to evict buffers.
2958 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2961 uint64_t evicted = 0;
2963 while (state->arcs_lsize[type] != 0) {
2964 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2974 * Evict the specified number of bytes from the state specified,
2975 * restricting eviction to the spa and type given. This function
2976 * prevents us from trying to evict more from a state's list than
2977 * is "evictable", and to skip evicting altogether when passed a
2978 * negative value for "bytes". In contrast, arc_evict_state() will
2979 * evict everything it can, when passed a negative value for "bytes".
2982 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2983 arc_buf_contents_t type)
2987 if (bytes > 0 && state->arcs_lsize[type] > 0) {
2988 delta = MIN(state->arcs_lsize[type], bytes);
2989 return (arc_evict_state(state, spa, delta, type));
2996 * Evict metadata buffers from the cache, such that arc_meta_used is
2997 * capped by the arc_meta_limit tunable.
3000 arc_adjust_meta(void)
3002 uint64_t total_evicted = 0;
3006 * If we're over the meta limit, we want to evict enough
3007 * metadata to get back under the meta limit. We don't want to
3008 * evict so much that we drop the MRU below arc_p, though. If
3009 * we're over the meta limit more than we're over arc_p, we
3010 * evict some from the MRU here, and some from the MFU below.
3012 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3013 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3014 refcount_count(&arc_mru->arcs_size) - arc_p));
3016 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3019 * Similar to the above, we want to evict enough bytes to get us
3020 * below the meta limit, but not so much as to drop us below the
3021 * space alloted to the MFU (which is defined as arc_c - arc_p).
3023 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3024 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3026 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3028 return (total_evicted);
3032 * Return the type of the oldest buffer in the given arc state
3034 * This function will select a random sublist of type ARC_BUFC_DATA and
3035 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3036 * is compared, and the type which contains the "older" buffer will be
3039 static arc_buf_contents_t
3040 arc_adjust_type(arc_state_t *state)
3042 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3043 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3044 int data_idx = multilist_get_random_index(data_ml);
3045 int meta_idx = multilist_get_random_index(meta_ml);
3046 multilist_sublist_t *data_mls;
3047 multilist_sublist_t *meta_mls;
3048 arc_buf_contents_t type;
3049 arc_buf_hdr_t *data_hdr;
3050 arc_buf_hdr_t *meta_hdr;
3053 * We keep the sublist lock until we're finished, to prevent
3054 * the headers from being destroyed via arc_evict_state().
3056 data_mls = multilist_sublist_lock(data_ml, data_idx);
3057 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3060 * These two loops are to ensure we skip any markers that
3061 * might be at the tail of the lists due to arc_evict_state().
3064 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3065 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3066 if (data_hdr->b_spa != 0)
3070 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3071 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3072 if (meta_hdr->b_spa != 0)
3076 if (data_hdr == NULL && meta_hdr == NULL) {
3077 type = ARC_BUFC_DATA;
3078 } else if (data_hdr == NULL) {
3079 ASSERT3P(meta_hdr, !=, NULL);
3080 type = ARC_BUFC_METADATA;
3081 } else if (meta_hdr == NULL) {
3082 ASSERT3P(data_hdr, !=, NULL);
3083 type = ARC_BUFC_DATA;
3085 ASSERT3P(data_hdr, !=, NULL);
3086 ASSERT3P(meta_hdr, !=, NULL);
3088 /* The headers can't be on the sublist without an L1 header */
3089 ASSERT(HDR_HAS_L1HDR(data_hdr));
3090 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3092 if (data_hdr->b_l1hdr.b_arc_access <
3093 meta_hdr->b_l1hdr.b_arc_access) {
3094 type = ARC_BUFC_DATA;
3096 type = ARC_BUFC_METADATA;
3100 multilist_sublist_unlock(meta_mls);
3101 multilist_sublist_unlock(data_mls);
3107 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3112 uint64_t total_evicted = 0;
3117 * If we're over arc_meta_limit, we want to correct that before
3118 * potentially evicting data buffers below.
3120 total_evicted += arc_adjust_meta();
3125 * If we're over the target cache size, we want to evict enough
3126 * from the list to get back to our target size. We don't want
3127 * to evict too much from the MRU, such that it drops below
3128 * arc_p. So, if we're over our target cache size more than
3129 * the MRU is over arc_p, we'll evict enough to get back to
3130 * arc_p here, and then evict more from the MFU below.
3132 target = MIN((int64_t)(arc_size - arc_c),
3133 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3134 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3137 * If we're below arc_meta_min, always prefer to evict data.
3138 * Otherwise, try to satisfy the requested number of bytes to
3139 * evict from the type which contains older buffers; in an
3140 * effort to keep newer buffers in the cache regardless of their
3141 * type. If we cannot satisfy the number of bytes from this
3142 * type, spill over into the next type.
3144 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3145 arc_meta_used > arc_meta_min) {
3146 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3147 total_evicted += bytes;
3150 * If we couldn't evict our target number of bytes from
3151 * metadata, we try to get the rest from data.
3156 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3158 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3159 total_evicted += bytes;
3162 * If we couldn't evict our target number of bytes from
3163 * data, we try to get the rest from metadata.
3168 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3174 * Now that we've tried to evict enough from the MRU to get its
3175 * size back to arc_p, if we're still above the target cache
3176 * size, we evict the rest from the MFU.
3178 target = arc_size - arc_c;
3180 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3181 arc_meta_used > arc_meta_min) {
3182 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3183 total_evicted += bytes;
3186 * If we couldn't evict our target number of bytes from
3187 * metadata, we try to get the rest from data.
3192 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3194 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3195 total_evicted += bytes;
3198 * If we couldn't evict our target number of bytes from
3199 * data, we try to get the rest from data.
3204 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3208 * Adjust ghost lists
3210 * In addition to the above, the ARC also defines target values
3211 * for the ghost lists. The sum of the mru list and mru ghost
3212 * list should never exceed the target size of the cache, and
3213 * the sum of the mru list, mfu list, mru ghost list, and mfu
3214 * ghost list should never exceed twice the target size of the
3215 * cache. The following logic enforces these limits on the ghost
3216 * caches, and evicts from them as needed.
3218 target = refcount_count(&arc_mru->arcs_size) +
3219 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3221 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3222 total_evicted += bytes;
3227 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3230 * We assume the sum of the mru list and mfu list is less than
3231 * or equal to arc_c (we enforced this above), which means we
3232 * can use the simpler of the two equations below:
3234 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3235 * mru ghost + mfu ghost <= arc_c
3237 target = refcount_count(&arc_mru_ghost->arcs_size) +
3238 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3240 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3241 total_evicted += bytes;
3246 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3248 return (total_evicted);
3252 arc_do_user_evicts(void)
3254 mutex_enter(&arc_user_evicts_lock);
3255 while (arc_eviction_list != NULL) {
3256 arc_buf_t *buf = arc_eviction_list;
3257 arc_eviction_list = buf->b_next;
3258 mutex_enter(&buf->b_evict_lock);
3260 mutex_exit(&buf->b_evict_lock);
3261 mutex_exit(&arc_user_evicts_lock);
3263 if (buf->b_efunc != NULL)
3264 VERIFY0(buf->b_efunc(buf->b_private));
3266 buf->b_efunc = NULL;
3267 buf->b_private = NULL;
3268 kmem_cache_free(buf_cache, buf);
3269 mutex_enter(&arc_user_evicts_lock);
3271 mutex_exit(&arc_user_evicts_lock);
3275 arc_flush(spa_t *spa, boolean_t retry)
3280 * If retry is TRUE, a spa must not be specified since we have
3281 * no good way to determine if all of a spa's buffers have been
3282 * evicted from an arc state.
3284 ASSERT(!retry || spa == 0);
3287 guid = spa_load_guid(spa);
3289 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3290 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3292 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3293 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3295 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3296 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3298 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3299 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3301 arc_do_user_evicts();
3302 ASSERT(spa || arc_eviction_list == NULL);
3306 arc_shrink(int64_t to_free)
3308 if (arc_c > arc_c_min) {
3309 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3310 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3311 if (arc_c > arc_c_min + to_free)
3312 atomic_add_64(&arc_c, -to_free);
3316 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3317 if (arc_c > arc_size)
3318 arc_c = MAX(arc_size, arc_c_min);
3320 arc_p = (arc_c >> 1);
3322 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3325 ASSERT(arc_c >= arc_c_min);
3326 ASSERT((int64_t)arc_p >= 0);
3329 if (arc_size > arc_c) {
3330 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3332 (void) arc_adjust();
3336 static long needfree = 0;
3338 typedef enum free_memory_reason_t {
3343 FMR_PAGES_PP_MAXIMUM,
3347 } free_memory_reason_t;
3349 int64_t last_free_memory;
3350 free_memory_reason_t last_free_reason;
3353 * Additional reserve of pages for pp_reserve.
3355 int64_t arc_pages_pp_reserve = 64;
3358 * Additional reserve of pages for swapfs.
3360 int64_t arc_swapfs_reserve = 64;
3363 * Return the amount of memory that can be consumed before reclaim will be
3364 * needed. Positive if there is sufficient free memory, negative indicates
3365 * the amount of memory that needs to be freed up.
3368 arc_available_memory(void)
3370 int64_t lowest = INT64_MAX;
3372 free_memory_reason_t r = FMR_UNKNOWN;
3376 n = PAGESIZE * (-needfree);
3384 * Cooperate with pagedaemon when it's time for it to scan
3385 * and reclaim some pages.
3387 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3395 * check that we're out of range of the pageout scanner. It starts to
3396 * schedule paging if freemem is less than lotsfree and needfree.
3397 * lotsfree is the high-water mark for pageout, and needfree is the
3398 * number of needed free pages. We add extra pages here to make sure
3399 * the scanner doesn't start up while we're freeing memory.
3401 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3408 * check to make sure that swapfs has enough space so that anon
3409 * reservations can still succeed. anon_resvmem() checks that the
3410 * availrmem is greater than swapfs_minfree, and the number of reserved
3411 * swap pages. We also add a bit of extra here just to prevent
3412 * circumstances from getting really dire.
3414 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3415 desfree - arc_swapfs_reserve);
3418 r = FMR_SWAPFS_MINFREE;
3423 * Check that we have enough availrmem that memory locking (e.g., via
3424 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3425 * stores the number of pages that cannot be locked; when availrmem
3426 * drops below pages_pp_maximum, page locking mechanisms such as
3427 * page_pp_lock() will fail.)
3429 n = PAGESIZE * (availrmem - pages_pp_maximum -
3430 arc_pages_pp_reserve);
3433 r = FMR_PAGES_PP_MAXIMUM;
3437 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3439 * If we're on an i386 platform, it's possible that we'll exhaust the
3440 * kernel heap space before we ever run out of available physical
3441 * memory. Most checks of the size of the heap_area compare against
3442 * tune.t_minarmem, which is the minimum available real memory that we
3443 * can have in the system. However, this is generally fixed at 25 pages
3444 * which is so low that it's useless. In this comparison, we seek to
3445 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3446 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3449 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3450 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3455 #define zio_arena NULL
3457 #define zio_arena heap_arena
3461 * If zio data pages are being allocated out of a separate heap segment,
3462 * then enforce that the size of available vmem for this arena remains
3463 * above about 1/16th free.
3465 * Note: The 1/16th arena free requirement was put in place
3466 * to aggressively evict memory from the arc in order to avoid
3467 * memory fragmentation issues.
3469 if (zio_arena != NULL) {
3470 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3471 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3479 * Above limits know nothing about real level of KVA fragmentation.
3480 * Start aggressive reclamation if too little sequential KVA left.
3483 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3484 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3493 /* Every 100 calls, free a small amount */
3494 if (spa_get_random(100) == 0)
3496 #endif /* _KERNEL */
3498 last_free_memory = lowest;
3499 last_free_reason = r;
3500 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3506 * Determine if the system is under memory pressure and is asking
3507 * to reclaim memory. A return value of TRUE indicates that the system
3508 * is under memory pressure and that the arc should adjust accordingly.
3511 arc_reclaim_needed(void)
3513 return (arc_available_memory() < 0);
3516 extern kmem_cache_t *zio_buf_cache[];
3517 extern kmem_cache_t *zio_data_buf_cache[];
3518 extern kmem_cache_t *range_seg_cache;
3520 static __noinline void
3521 arc_kmem_reap_now(void)
3524 kmem_cache_t *prev_cache = NULL;
3525 kmem_cache_t *prev_data_cache = NULL;
3527 DTRACE_PROBE(arc__kmem_reap_start);
3529 if (arc_meta_used >= arc_meta_limit) {
3531 * We are exceeding our meta-data cache limit.
3532 * Purge some DNLC entries to release holds on meta-data.
3534 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3538 * Reclaim unused memory from all kmem caches.
3544 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3545 if (zio_buf_cache[i] != prev_cache) {
3546 prev_cache = zio_buf_cache[i];
3547 kmem_cache_reap_now(zio_buf_cache[i]);
3549 if (zio_data_buf_cache[i] != prev_data_cache) {
3550 prev_data_cache = zio_data_buf_cache[i];
3551 kmem_cache_reap_now(zio_data_buf_cache[i]);
3554 kmem_cache_reap_now(buf_cache);
3555 kmem_cache_reap_now(hdr_full_cache);
3556 kmem_cache_reap_now(hdr_l2only_cache);
3557 kmem_cache_reap_now(range_seg_cache);
3560 if (zio_arena != NULL) {
3562 * Ask the vmem arena to reclaim unused memory from its
3565 vmem_qcache_reap(zio_arena);
3568 DTRACE_PROBE(arc__kmem_reap_end);
3572 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3573 * enough data and signal them to proceed. When this happens, the threads in
3574 * arc_get_data_buf() are sleeping while holding the hash lock for their
3575 * particular arc header. Thus, we must be careful to never sleep on a
3576 * hash lock in this thread. This is to prevent the following deadlock:
3578 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3579 * waiting for the reclaim thread to signal it.
3581 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3582 * fails, and goes to sleep forever.
3584 * This possible deadlock is avoided by always acquiring a hash lock
3585 * using mutex_tryenter() from arc_reclaim_thread().
3588 arc_reclaim_thread(void *dummy __unused)
3590 clock_t growtime = 0;
3593 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3595 mutex_enter(&arc_reclaim_lock);
3596 while (!arc_reclaim_thread_exit) {
3597 int64_t free_memory = arc_available_memory();
3598 uint64_t evicted = 0;
3600 mutex_exit(&arc_reclaim_lock);
3602 if (free_memory < 0) {
3604 arc_no_grow = B_TRUE;
3608 * Wait at least zfs_grow_retry (default 60) seconds
3609 * before considering growing.
3611 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3613 arc_kmem_reap_now();
3616 * If we are still low on memory, shrink the ARC
3617 * so that we have arc_shrink_min free space.
3619 free_memory = arc_available_memory();
3622 (arc_c >> arc_shrink_shift) - free_memory;
3625 to_free = MAX(to_free, ptob(needfree));
3627 arc_shrink(to_free);
3629 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3630 arc_no_grow = B_TRUE;
3631 } else if (ddi_get_lbolt() >= growtime) {
3632 arc_no_grow = B_FALSE;
3635 evicted = arc_adjust();
3637 mutex_enter(&arc_reclaim_lock);
3640 * If evicted is zero, we couldn't evict anything via
3641 * arc_adjust(). This could be due to hash lock
3642 * collisions, but more likely due to the majority of
3643 * arc buffers being unevictable. Therefore, even if
3644 * arc_size is above arc_c, another pass is unlikely to
3645 * be helpful and could potentially cause us to enter an
3648 if (arc_size <= arc_c || evicted == 0) {
3653 * We're either no longer overflowing, or we
3654 * can't evict anything more, so we should wake
3655 * up any threads before we go to sleep.
3657 cv_broadcast(&arc_reclaim_waiters_cv);
3660 * Block until signaled, or after one second (we
3661 * might need to perform arc_kmem_reap_now()
3662 * even if we aren't being signalled)
3664 CALLB_CPR_SAFE_BEGIN(&cpr);
3665 (void) cv_timedwait(&arc_reclaim_thread_cv,
3666 &arc_reclaim_lock, hz);
3667 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3671 arc_reclaim_thread_exit = FALSE;
3672 cv_broadcast(&arc_reclaim_thread_cv);
3673 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3678 arc_user_evicts_thread(void *dummy __unused)
3682 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3684 mutex_enter(&arc_user_evicts_lock);
3685 while (!arc_user_evicts_thread_exit) {
3686 mutex_exit(&arc_user_evicts_lock);
3688 arc_do_user_evicts();
3691 * This is necessary in order for the mdb ::arc dcmd to
3692 * show up to date information. Since the ::arc command
3693 * does not call the kstat's update function, without
3694 * this call, the command may show stale stats for the
3695 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3696 * with this change, the data might be up to 1 second
3697 * out of date; but that should suffice. The arc_state_t
3698 * structures can be queried directly if more accurate
3699 * information is needed.
3701 if (arc_ksp != NULL)
3702 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3704 mutex_enter(&arc_user_evicts_lock);
3707 * Block until signaled, or after one second (we need to
3708 * call the arc's kstat update function regularly).
3710 CALLB_CPR_SAFE_BEGIN(&cpr);
3711 (void) cv_timedwait(&arc_user_evicts_cv,
3712 &arc_user_evicts_lock, hz);
3713 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3716 arc_user_evicts_thread_exit = FALSE;
3717 cv_broadcast(&arc_user_evicts_cv);
3718 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3723 * Adapt arc info given the number of bytes we are trying to add and
3724 * the state that we are comming from. This function is only called
3725 * when we are adding new content to the cache.
3728 arc_adapt(int bytes, arc_state_t *state)
3731 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3732 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3733 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3735 if (state == arc_l2c_only)
3740 * Adapt the target size of the MRU list:
3741 * - if we just hit in the MRU ghost list, then increase
3742 * the target size of the MRU list.
3743 * - if we just hit in the MFU ghost list, then increase
3744 * the target size of the MFU list by decreasing the
3745 * target size of the MRU list.
3747 if (state == arc_mru_ghost) {
3748 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3749 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3751 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3752 } else if (state == arc_mfu_ghost) {
3755 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3756 mult = MIN(mult, 10);
3758 delta = MIN(bytes * mult, arc_p);
3759 arc_p = MAX(arc_p_min, arc_p - delta);
3761 ASSERT((int64_t)arc_p >= 0);
3763 if (arc_reclaim_needed()) {
3764 cv_signal(&arc_reclaim_thread_cv);
3771 if (arc_c >= arc_c_max)
3775 * If we're within (2 * maxblocksize) bytes of the target
3776 * cache size, increment the target cache size
3778 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3779 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3780 atomic_add_64(&arc_c, (int64_t)bytes);
3781 if (arc_c > arc_c_max)
3783 else if (state == arc_anon)
3784 atomic_add_64(&arc_p, (int64_t)bytes);
3788 ASSERT((int64_t)arc_p >= 0);
3792 * Check if arc_size has grown past our upper threshold, determined by
3793 * zfs_arc_overflow_shift.
3796 arc_is_overflowing(void)
3798 /* Always allow at least one block of overflow */
3799 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3800 arc_c >> zfs_arc_overflow_shift);
3802 return (arc_size >= arc_c + overflow);
3806 * The buffer, supplied as the first argument, needs a data block. If we
3807 * are hitting the hard limit for the cache size, we must sleep, waiting
3808 * for the eviction thread to catch up. If we're past the target size
3809 * but below the hard limit, we'll only signal the reclaim thread and
3813 arc_get_data_buf(arc_buf_t *buf)
3815 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3816 uint64_t size = buf->b_hdr->b_size;
3817 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3819 arc_adapt(size, state);
3822 * If arc_size is currently overflowing, and has grown past our
3823 * upper limit, we must be adding data faster than the evict
3824 * thread can evict. Thus, to ensure we don't compound the
3825 * problem by adding more data and forcing arc_size to grow even
3826 * further past it's target size, we halt and wait for the
3827 * eviction thread to catch up.
3829 * It's also possible that the reclaim thread is unable to evict
3830 * enough buffers to get arc_size below the overflow limit (e.g.
3831 * due to buffers being un-evictable, or hash lock collisions).
3832 * In this case, we want to proceed regardless if we're
3833 * overflowing; thus we don't use a while loop here.
3835 if (arc_is_overflowing()) {
3836 mutex_enter(&arc_reclaim_lock);
3839 * Now that we've acquired the lock, we may no longer be
3840 * over the overflow limit, lets check.
3842 * We're ignoring the case of spurious wake ups. If that
3843 * were to happen, it'd let this thread consume an ARC
3844 * buffer before it should have (i.e. before we're under
3845 * the overflow limit and were signalled by the reclaim
3846 * thread). As long as that is a rare occurrence, it
3847 * shouldn't cause any harm.
3849 if (arc_is_overflowing()) {
3850 cv_signal(&arc_reclaim_thread_cv);
3851 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3854 mutex_exit(&arc_reclaim_lock);
3857 if (type == ARC_BUFC_METADATA) {
3858 buf->b_data = zio_buf_alloc(size);
3859 arc_space_consume(size, ARC_SPACE_META);
3861 ASSERT(type == ARC_BUFC_DATA);
3862 buf->b_data = zio_data_buf_alloc(size);
3863 arc_space_consume(size, ARC_SPACE_DATA);
3867 * Update the state size. Note that ghost states have a
3868 * "ghost size" and so don't need to be updated.
3870 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3871 arc_buf_hdr_t *hdr = buf->b_hdr;
3872 arc_state_t *state = hdr->b_l1hdr.b_state;
3874 (void) refcount_add_many(&state->arcs_size, size, buf);
3877 * If this is reached via arc_read, the link is
3878 * protected by the hash lock. If reached via
3879 * arc_buf_alloc, the header should not be accessed by
3880 * any other thread. And, if reached via arc_read_done,
3881 * the hash lock will protect it if it's found in the
3882 * hash table; otherwise no other thread should be
3883 * trying to [add|remove]_reference it.
3885 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3886 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3887 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3891 * If we are growing the cache, and we are adding anonymous
3892 * data, and we have outgrown arc_p, update arc_p
3894 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3895 (refcount_count(&arc_anon->arcs_size) +
3896 refcount_count(&arc_mru->arcs_size) > arc_p))
3897 arc_p = MIN(arc_c, arc_p + size);
3899 ARCSTAT_BUMP(arcstat_allocated);
3903 * This routine is called whenever a buffer is accessed.
3904 * NOTE: the hash lock is dropped in this function.
3907 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3911 ASSERT(MUTEX_HELD(hash_lock));
3912 ASSERT(HDR_HAS_L1HDR(hdr));
3914 if (hdr->b_l1hdr.b_state == arc_anon) {
3916 * This buffer is not in the cache, and does not
3917 * appear in our "ghost" list. Add the new buffer
3921 ASSERT0(hdr->b_l1hdr.b_arc_access);
3922 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3923 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3924 arc_change_state(arc_mru, hdr, hash_lock);
3926 } else if (hdr->b_l1hdr.b_state == arc_mru) {
3927 now = ddi_get_lbolt();
3930 * If this buffer is here because of a prefetch, then either:
3931 * - clear the flag if this is a "referencing" read
3932 * (any subsequent access will bump this into the MFU state).
3934 * - move the buffer to the head of the list if this is
3935 * another prefetch (to make it less likely to be evicted).
3937 if (HDR_PREFETCH(hdr)) {
3938 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3939 /* link protected by hash lock */
3940 ASSERT(multilist_link_active(
3941 &hdr->b_l1hdr.b_arc_node));
3943 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3944 ARCSTAT_BUMP(arcstat_mru_hits);
3946 hdr->b_l1hdr.b_arc_access = now;
3951 * This buffer has been "accessed" only once so far,
3952 * but it is still in the cache. Move it to the MFU
3955 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3957 * More than 125ms have passed since we
3958 * instantiated this buffer. Move it to the
3959 * most frequently used state.
3961 hdr->b_l1hdr.b_arc_access = now;
3962 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3963 arc_change_state(arc_mfu, hdr, hash_lock);
3965 ARCSTAT_BUMP(arcstat_mru_hits);
3966 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3967 arc_state_t *new_state;
3969 * This buffer has been "accessed" recently, but
3970 * was evicted from the cache. Move it to the
3974 if (HDR_PREFETCH(hdr)) {
3975 new_state = arc_mru;
3976 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3977 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3978 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3980 new_state = arc_mfu;
3981 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3984 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3985 arc_change_state(new_state, hdr, hash_lock);
3987 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3988 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
3990 * This buffer has been accessed more than once and is
3991 * still in the cache. Keep it in the MFU state.
3993 * NOTE: an add_reference() that occurred when we did
3994 * the arc_read() will have kicked this off the list.
3995 * If it was a prefetch, we will explicitly move it to
3996 * the head of the list now.
3998 if ((HDR_PREFETCH(hdr)) != 0) {
3999 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4000 /* link protected by hash_lock */
4001 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4003 ARCSTAT_BUMP(arcstat_mfu_hits);
4004 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4005 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4006 arc_state_t *new_state = arc_mfu;
4008 * This buffer has been accessed more than once but has
4009 * been evicted from the cache. Move it back to the
4013 if (HDR_PREFETCH(hdr)) {
4015 * This is a prefetch access...
4016 * move this block back to the MRU state.
4018 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4019 new_state = arc_mru;
4022 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4023 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4024 arc_change_state(new_state, hdr, hash_lock);
4026 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4027 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4029 * This buffer is on the 2nd Level ARC.
4032 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4033 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4034 arc_change_state(arc_mfu, hdr, hash_lock);
4036 ASSERT(!"invalid arc state");
4040 /* a generic arc_done_func_t which you can use */
4043 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4045 if (zio == NULL || zio->io_error == 0)
4046 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4047 VERIFY(arc_buf_remove_ref(buf, arg));
4050 /* a generic arc_done_func_t */
4052 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4054 arc_buf_t **bufp = arg;
4055 if (zio && zio->io_error) {
4056 VERIFY(arc_buf_remove_ref(buf, arg));
4060 ASSERT(buf->b_data);
4065 arc_read_done(zio_t *zio)
4069 arc_buf_t *abuf; /* buffer we're assigning to callback */
4070 kmutex_t *hash_lock = NULL;
4071 arc_callback_t *callback_list, *acb;
4072 int freeable = FALSE;
4074 buf = zio->io_private;
4078 * The hdr was inserted into hash-table and removed from lists
4079 * prior to starting I/O. We should find this header, since
4080 * it's in the hash table, and it should be legit since it's
4081 * not possible to evict it during the I/O. The only possible
4082 * reason for it not to be found is if we were freed during the
4085 if (HDR_IN_HASH_TABLE(hdr)) {
4086 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4087 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4088 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4089 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4090 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4092 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4095 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4096 hash_lock == NULL) ||
4098 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4099 (found == hdr && HDR_L2_READING(hdr)));
4102 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4103 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4104 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4106 /* byteswap if necessary */
4107 callback_list = hdr->b_l1hdr.b_acb;
4108 ASSERT(callback_list != NULL);
4109 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4110 dmu_object_byteswap_t bswap =
4111 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4112 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4113 byteswap_uint64_array :
4114 dmu_ot_byteswap[bswap].ob_func;
4115 func(buf->b_data, hdr->b_size);
4118 arc_cksum_compute(buf, B_FALSE);
4121 #endif /* illumos */
4123 if (hash_lock && zio->io_error == 0 &&
4124 hdr->b_l1hdr.b_state == arc_anon) {
4126 * Only call arc_access on anonymous buffers. This is because
4127 * if we've issued an I/O for an evicted buffer, we've already
4128 * called arc_access (to prevent any simultaneous readers from
4129 * getting confused).
4131 arc_access(hdr, hash_lock);
4134 /* create copies of the data buffer for the callers */
4136 for (acb = callback_list; acb; acb = acb->acb_next) {
4137 if (acb->acb_done) {
4139 ARCSTAT_BUMP(arcstat_duplicate_reads);
4140 abuf = arc_buf_clone(buf);
4142 acb->acb_buf = abuf;
4146 hdr->b_l1hdr.b_acb = NULL;
4147 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4148 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4150 ASSERT(buf->b_efunc == NULL);
4151 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4152 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4155 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4156 callback_list != NULL);
4158 if (zio->io_error != 0) {
4159 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4160 if (hdr->b_l1hdr.b_state != arc_anon)
4161 arc_change_state(arc_anon, hdr, hash_lock);
4162 if (HDR_IN_HASH_TABLE(hdr))
4163 buf_hash_remove(hdr);
4164 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4168 * Broadcast before we drop the hash_lock to avoid the possibility
4169 * that the hdr (and hence the cv) might be freed before we get to
4170 * the cv_broadcast().
4172 cv_broadcast(&hdr->b_l1hdr.b_cv);
4174 if (hash_lock != NULL) {
4175 mutex_exit(hash_lock);
4178 * This block was freed while we waited for the read to
4179 * complete. It has been removed from the hash table and
4180 * moved to the anonymous state (so that it won't show up
4183 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4184 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4187 /* execute each callback and free its structure */
4188 while ((acb = callback_list) != NULL) {
4190 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4192 if (acb->acb_zio_dummy != NULL) {
4193 acb->acb_zio_dummy->io_error = zio->io_error;
4194 zio_nowait(acb->acb_zio_dummy);
4197 callback_list = acb->acb_next;
4198 kmem_free(acb, sizeof (arc_callback_t));
4202 arc_hdr_destroy(hdr);
4206 * "Read" the block at the specified DVA (in bp) via the
4207 * cache. If the block is found in the cache, invoke the provided
4208 * callback immediately and return. Note that the `zio' parameter
4209 * in the callback will be NULL in this case, since no IO was
4210 * required. If the block is not in the cache pass the read request
4211 * on to the spa with a substitute callback function, so that the
4212 * requested block will be added to the cache.
4214 * If a read request arrives for a block that has a read in-progress,
4215 * either wait for the in-progress read to complete (and return the
4216 * results); or, if this is a read with a "done" func, add a record
4217 * to the read to invoke the "done" func when the read completes,
4218 * and return; or just return.
4220 * arc_read_done() will invoke all the requested "done" functions
4221 * for readers of this block.
4224 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4225 void *private, zio_priority_t priority, int zio_flags,
4226 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4228 arc_buf_hdr_t *hdr = NULL;
4229 arc_buf_t *buf = NULL;
4230 kmutex_t *hash_lock = NULL;
4232 uint64_t guid = spa_load_guid(spa);
4234 ASSERT(!BP_IS_EMBEDDED(bp) ||
4235 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4238 if (!BP_IS_EMBEDDED(bp)) {
4240 * Embedded BP's have no DVA and require no I/O to "read".
4241 * Create an anonymous arc buf to back it.
4243 hdr = buf_hash_find(guid, bp, &hash_lock);
4246 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4248 *arc_flags |= ARC_FLAG_CACHED;
4250 if (HDR_IO_IN_PROGRESS(hdr)) {
4252 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4253 priority == ZIO_PRIORITY_SYNC_READ) {
4255 * This sync read must wait for an
4256 * in-progress async read (e.g. a predictive
4257 * prefetch). Async reads are queued
4258 * separately at the vdev_queue layer, so
4259 * this is a form of priority inversion.
4260 * Ideally, we would "inherit" the demand
4261 * i/o's priority by moving the i/o from
4262 * the async queue to the synchronous queue,
4263 * but there is currently no mechanism to do
4264 * so. Track this so that we can evaluate
4265 * the magnitude of this potential performance
4268 * Note that if the prefetch i/o is already
4269 * active (has been issued to the device),
4270 * the prefetch improved performance, because
4271 * we issued it sooner than we would have
4272 * without the prefetch.
4274 DTRACE_PROBE1(arc__sync__wait__for__async,
4275 arc_buf_hdr_t *, hdr);
4276 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4278 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4279 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4282 if (*arc_flags & ARC_FLAG_WAIT) {
4283 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4284 mutex_exit(hash_lock);
4287 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4290 arc_callback_t *acb = NULL;
4292 acb = kmem_zalloc(sizeof (arc_callback_t),
4294 acb->acb_done = done;
4295 acb->acb_private = private;
4297 acb->acb_zio_dummy = zio_null(pio,
4298 spa, NULL, NULL, NULL, zio_flags);
4300 ASSERT(acb->acb_done != NULL);
4301 acb->acb_next = hdr->b_l1hdr.b_acb;
4302 hdr->b_l1hdr.b_acb = acb;
4303 add_reference(hdr, hash_lock, private);
4304 mutex_exit(hash_lock);
4307 mutex_exit(hash_lock);
4311 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4312 hdr->b_l1hdr.b_state == arc_mfu);
4315 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4317 * This is a demand read which does not have to
4318 * wait for i/o because we did a predictive
4319 * prefetch i/o for it, which has completed.
4322 arc__demand__hit__predictive__prefetch,
4323 arc_buf_hdr_t *, hdr);
4325 arcstat_demand_hit_predictive_prefetch);
4326 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4328 add_reference(hdr, hash_lock, private);
4330 * If this block is already in use, create a new
4331 * copy of the data so that we will be guaranteed
4332 * that arc_release() will always succeed.
4334 buf = hdr->b_l1hdr.b_buf;
4336 ASSERT(buf->b_data);
4337 if (HDR_BUF_AVAILABLE(hdr)) {
4338 ASSERT(buf->b_efunc == NULL);
4339 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4341 buf = arc_buf_clone(buf);
4344 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4345 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4346 hdr->b_flags |= ARC_FLAG_PREFETCH;
4348 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4349 arc_access(hdr, hash_lock);
4350 if (*arc_flags & ARC_FLAG_L2CACHE)
4351 hdr->b_flags |= ARC_FLAG_L2CACHE;
4352 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4353 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4354 mutex_exit(hash_lock);
4355 ARCSTAT_BUMP(arcstat_hits);
4356 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4357 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4358 data, metadata, hits);
4361 done(NULL, buf, private);
4363 uint64_t size = BP_GET_LSIZE(bp);
4364 arc_callback_t *acb;
4367 boolean_t devw = B_FALSE;
4368 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4369 int32_t b_asize = 0;
4372 /* this block is not in the cache */
4373 arc_buf_hdr_t *exists = NULL;
4374 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4375 buf = arc_buf_alloc(spa, size, private, type);
4377 if (!BP_IS_EMBEDDED(bp)) {
4378 hdr->b_dva = *BP_IDENTITY(bp);
4379 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4380 exists = buf_hash_insert(hdr, &hash_lock);
4382 if (exists != NULL) {
4383 /* somebody beat us to the hash insert */
4384 mutex_exit(hash_lock);
4385 buf_discard_identity(hdr);
4386 (void) arc_buf_remove_ref(buf, private);
4387 goto top; /* restart the IO request */
4391 * If there is a callback, we pass our reference to
4392 * it; otherwise we remove our reference.
4395 (void) remove_reference(hdr, hash_lock,
4398 if (*arc_flags & ARC_FLAG_PREFETCH)
4399 hdr->b_flags |= ARC_FLAG_PREFETCH;
4400 if (*arc_flags & ARC_FLAG_L2CACHE)
4401 hdr->b_flags |= ARC_FLAG_L2CACHE;
4402 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4403 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4404 if (BP_GET_LEVEL(bp) > 0)
4405 hdr->b_flags |= ARC_FLAG_INDIRECT;
4408 * This block is in the ghost cache. If it was L2-only
4409 * (and thus didn't have an L1 hdr), we realloc the
4410 * header to add an L1 hdr.
4412 if (!HDR_HAS_L1HDR(hdr)) {
4413 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4417 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4418 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4419 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4420 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4423 * If there is a callback, we pass a reference to it.
4426 add_reference(hdr, hash_lock, private);
4427 if (*arc_flags & ARC_FLAG_PREFETCH)
4428 hdr->b_flags |= ARC_FLAG_PREFETCH;
4429 if (*arc_flags & ARC_FLAG_L2CACHE)
4430 hdr->b_flags |= ARC_FLAG_L2CACHE;
4431 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4432 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4433 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4436 buf->b_efunc = NULL;
4437 buf->b_private = NULL;
4439 hdr->b_l1hdr.b_buf = buf;
4440 ASSERT0(hdr->b_l1hdr.b_datacnt);
4441 hdr->b_l1hdr.b_datacnt = 1;
4442 arc_get_data_buf(buf);
4443 arc_access(hdr, hash_lock);
4446 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4447 hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
4448 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4450 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4451 acb->acb_done = done;
4452 acb->acb_private = private;
4454 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4455 hdr->b_l1hdr.b_acb = acb;
4456 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4458 if (HDR_HAS_L2HDR(hdr) &&
4459 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4460 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4461 addr = hdr->b_l2hdr.b_daddr;
4462 b_compress = hdr->b_l2hdr.b_compress;
4463 b_asize = hdr->b_l2hdr.b_asize;
4465 * Lock out device removal.
4467 if (vdev_is_dead(vd) ||
4468 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4472 if (hash_lock != NULL)
4473 mutex_exit(hash_lock);
4476 * At this point, we have a level 1 cache miss. Try again in
4477 * L2ARC if possible.
4479 ASSERT3U(hdr->b_size, ==, size);
4480 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4481 uint64_t, size, zbookmark_phys_t *, zb);
4482 ARCSTAT_BUMP(arcstat_misses);
4483 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4484 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4485 data, metadata, misses);
4487 curthread->td_ru.ru_inblock++;
4490 if (priority == ZIO_PRIORITY_ASYNC_READ)
4491 hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4493 hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4495 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4497 * Read from the L2ARC if the following are true:
4498 * 1. The L2ARC vdev was previously cached.
4499 * 2. This buffer still has L2ARC metadata.
4500 * 3. This buffer isn't currently writing to the L2ARC.
4501 * 4. The L2ARC entry wasn't evicted, which may
4502 * also have invalidated the vdev.
4503 * 5. This isn't prefetch and l2arc_noprefetch is set.
4505 if (HDR_HAS_L2HDR(hdr) &&
4506 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4507 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4508 l2arc_read_callback_t *cb;
4510 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4511 ARCSTAT_BUMP(arcstat_l2_hits);
4513 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4515 cb->l2rcb_buf = buf;
4516 cb->l2rcb_spa = spa;
4519 cb->l2rcb_flags = zio_flags;
4520 cb->l2rcb_compress = b_compress;
4522 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4523 addr + size < vd->vdev_psize -
4524 VDEV_LABEL_END_SIZE);
4527 * l2arc read. The SCL_L2ARC lock will be
4528 * released by l2arc_read_done().
4529 * Issue a null zio if the underlying buffer
4530 * was squashed to zero size by compression.
4532 if (b_compress == ZIO_COMPRESS_EMPTY) {
4533 rzio = zio_null(pio, spa, vd,
4534 l2arc_read_done, cb,
4535 zio_flags | ZIO_FLAG_DONT_CACHE |
4537 ZIO_FLAG_DONT_PROPAGATE |
4538 ZIO_FLAG_DONT_RETRY);
4540 rzio = zio_read_phys(pio, vd, addr,
4541 b_asize, buf->b_data,
4543 l2arc_read_done, cb, priority,
4544 zio_flags | ZIO_FLAG_DONT_CACHE |
4546 ZIO_FLAG_DONT_PROPAGATE |
4547 ZIO_FLAG_DONT_RETRY, B_FALSE);
4549 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4551 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4553 if (*arc_flags & ARC_FLAG_NOWAIT) {
4558 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4559 if (zio_wait(rzio) == 0)
4562 /* l2arc read error; goto zio_read() */
4564 DTRACE_PROBE1(l2arc__miss,
4565 arc_buf_hdr_t *, hdr);
4566 ARCSTAT_BUMP(arcstat_l2_misses);
4567 if (HDR_L2_WRITING(hdr))
4568 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4569 spa_config_exit(spa, SCL_L2ARC, vd);
4573 spa_config_exit(spa, SCL_L2ARC, vd);
4574 if (l2arc_ndev != 0) {
4575 DTRACE_PROBE1(l2arc__miss,
4576 arc_buf_hdr_t *, hdr);
4577 ARCSTAT_BUMP(arcstat_l2_misses);
4581 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4582 arc_read_done, buf, priority, zio_flags, zb);
4584 if (*arc_flags & ARC_FLAG_WAIT)
4585 return (zio_wait(rzio));
4587 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4594 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4596 ASSERT(buf->b_hdr != NULL);
4597 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4598 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4600 ASSERT(buf->b_efunc == NULL);
4601 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4603 buf->b_efunc = func;
4604 buf->b_private = private;
4608 * Notify the arc that a block was freed, and thus will never be used again.
4611 arc_freed(spa_t *spa, const blkptr_t *bp)
4614 kmutex_t *hash_lock;
4615 uint64_t guid = spa_load_guid(spa);
4617 ASSERT(!BP_IS_EMBEDDED(bp));
4619 hdr = buf_hash_find(guid, bp, &hash_lock);
4622 if (HDR_BUF_AVAILABLE(hdr)) {
4623 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4624 add_reference(hdr, hash_lock, FTAG);
4625 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4626 mutex_exit(hash_lock);
4628 arc_release(buf, FTAG);
4629 (void) arc_buf_remove_ref(buf, FTAG);
4631 mutex_exit(hash_lock);
4637 * Clear the user eviction callback set by arc_set_callback(), first calling
4638 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4639 * clearing the callback may result in the arc_buf being destroyed. However,
4640 * it will not result in the *last* arc_buf being destroyed, hence the data
4641 * will remain cached in the ARC. We make a copy of the arc buffer here so
4642 * that we can process the callback without holding any locks.
4644 * It's possible that the callback is already in the process of being cleared
4645 * by another thread. In this case we can not clear the callback.
4647 * Returns B_TRUE if the callback was successfully called and cleared.
4650 arc_clear_callback(arc_buf_t *buf)
4653 kmutex_t *hash_lock;
4654 arc_evict_func_t *efunc = buf->b_efunc;
4655 void *private = buf->b_private;
4657 mutex_enter(&buf->b_evict_lock);
4661 * We are in arc_do_user_evicts().
4663 ASSERT(buf->b_data == NULL);
4664 mutex_exit(&buf->b_evict_lock);
4666 } else if (buf->b_data == NULL) {
4668 * We are on the eviction list; process this buffer now
4669 * but let arc_do_user_evicts() do the reaping.
4671 buf->b_efunc = NULL;
4672 mutex_exit(&buf->b_evict_lock);
4673 VERIFY0(efunc(private));
4676 hash_lock = HDR_LOCK(hdr);
4677 mutex_enter(hash_lock);
4679 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4681 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4682 hdr->b_l1hdr.b_datacnt);
4683 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4684 hdr->b_l1hdr.b_state == arc_mfu);
4686 buf->b_efunc = NULL;
4687 buf->b_private = NULL;
4689 if (hdr->b_l1hdr.b_datacnt > 1) {
4690 mutex_exit(&buf->b_evict_lock);
4691 arc_buf_destroy(buf, TRUE);
4693 ASSERT(buf == hdr->b_l1hdr.b_buf);
4694 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4695 mutex_exit(&buf->b_evict_lock);
4698 mutex_exit(hash_lock);
4699 VERIFY0(efunc(private));
4704 * Release this buffer from the cache, making it an anonymous buffer. This
4705 * must be done after a read and prior to modifying the buffer contents.
4706 * If the buffer has more than one reference, we must make
4707 * a new hdr for the buffer.
4710 arc_release(arc_buf_t *buf, void *tag)
4712 arc_buf_hdr_t *hdr = buf->b_hdr;
4715 * It would be nice to assert that if it's DMU metadata (level >
4716 * 0 || it's the dnode file), then it must be syncing context.
4717 * But we don't know that information at this level.
4720 mutex_enter(&buf->b_evict_lock);
4722 ASSERT(HDR_HAS_L1HDR(hdr));
4725 * We don't grab the hash lock prior to this check, because if
4726 * the buffer's header is in the arc_anon state, it won't be
4727 * linked into the hash table.
4729 if (hdr->b_l1hdr.b_state == arc_anon) {
4730 mutex_exit(&buf->b_evict_lock);
4731 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4732 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4733 ASSERT(!HDR_HAS_L2HDR(hdr));
4734 ASSERT(BUF_EMPTY(hdr));
4735 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4736 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4737 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4739 ASSERT3P(buf->b_efunc, ==, NULL);
4740 ASSERT3P(buf->b_private, ==, NULL);
4742 hdr->b_l1hdr.b_arc_access = 0;
4748 kmutex_t *hash_lock = HDR_LOCK(hdr);
4749 mutex_enter(hash_lock);
4752 * This assignment is only valid as long as the hash_lock is
4753 * held, we must be careful not to reference state or the
4754 * b_state field after dropping the lock.
4756 arc_state_t *state = hdr->b_l1hdr.b_state;
4757 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4758 ASSERT3P(state, !=, arc_anon);
4760 /* this buffer is not on any list */
4761 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4763 if (HDR_HAS_L2HDR(hdr)) {
4764 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4767 * We have to recheck this conditional again now that
4768 * we're holding the l2ad_mtx to prevent a race with
4769 * another thread which might be concurrently calling
4770 * l2arc_evict(). In that case, l2arc_evict() might have
4771 * destroyed the header's L2 portion as we were waiting
4772 * to acquire the l2ad_mtx.
4774 if (HDR_HAS_L2HDR(hdr)) {
4775 if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
4776 trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
4777 hdr->b_l2hdr.b_daddr,
4778 hdr->b_l2hdr.b_asize, 0);
4779 arc_hdr_l2hdr_destroy(hdr);
4782 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4786 * Do we have more than one buf?
4788 if (hdr->b_l1hdr.b_datacnt > 1) {
4789 arc_buf_hdr_t *nhdr;
4791 uint64_t blksz = hdr->b_size;
4792 uint64_t spa = hdr->b_spa;
4793 arc_buf_contents_t type = arc_buf_type(hdr);
4794 uint32_t flags = hdr->b_flags;
4796 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4798 * Pull the data off of this hdr and attach it to
4799 * a new anonymous hdr.
4801 (void) remove_reference(hdr, hash_lock, tag);
4802 bufp = &hdr->b_l1hdr.b_buf;
4803 while (*bufp != buf)
4804 bufp = &(*bufp)->b_next;
4805 *bufp = buf->b_next;
4808 ASSERT3P(state, !=, arc_l2c_only);
4810 (void) refcount_remove_many(
4811 &state->arcs_size, hdr->b_size, buf);
4813 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4814 ASSERT3P(state, !=, arc_l2c_only);
4815 uint64_t *size = &state->arcs_lsize[type];
4816 ASSERT3U(*size, >=, hdr->b_size);
4817 atomic_add_64(size, -hdr->b_size);
4821 * We're releasing a duplicate user data buffer, update
4822 * our statistics accordingly.
4824 if (HDR_ISTYPE_DATA(hdr)) {
4825 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4826 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4829 hdr->b_l1hdr.b_datacnt -= 1;
4830 arc_cksum_verify(buf);
4832 arc_buf_unwatch(buf);
4833 #endif /* illumos */
4835 mutex_exit(hash_lock);
4837 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4838 nhdr->b_size = blksz;
4841 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4842 nhdr->b_flags |= arc_bufc_to_flags(type);
4843 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4845 nhdr->b_l1hdr.b_buf = buf;
4846 nhdr->b_l1hdr.b_datacnt = 1;
4847 nhdr->b_l1hdr.b_state = arc_anon;
4848 nhdr->b_l1hdr.b_arc_access = 0;
4849 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4850 nhdr->b_freeze_cksum = NULL;
4852 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4854 mutex_exit(&buf->b_evict_lock);
4855 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4857 mutex_exit(&buf->b_evict_lock);
4858 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4859 /* protected by hash lock, or hdr is on arc_anon */
4860 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4861 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4862 arc_change_state(arc_anon, hdr, hash_lock);
4863 hdr->b_l1hdr.b_arc_access = 0;
4864 mutex_exit(hash_lock);
4866 buf_discard_identity(hdr);
4869 buf->b_efunc = NULL;
4870 buf->b_private = NULL;
4874 arc_released(arc_buf_t *buf)
4878 mutex_enter(&buf->b_evict_lock);
4879 released = (buf->b_data != NULL &&
4880 buf->b_hdr->b_l1hdr.b_state == arc_anon);
4881 mutex_exit(&buf->b_evict_lock);
4887 arc_referenced(arc_buf_t *buf)
4891 mutex_enter(&buf->b_evict_lock);
4892 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4893 mutex_exit(&buf->b_evict_lock);
4894 return (referenced);
4899 arc_write_ready(zio_t *zio)
4901 arc_write_callback_t *callback = zio->io_private;
4902 arc_buf_t *buf = callback->awcb_buf;
4903 arc_buf_hdr_t *hdr = buf->b_hdr;
4905 ASSERT(HDR_HAS_L1HDR(hdr));
4906 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4907 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4908 callback->awcb_ready(zio, buf, callback->awcb_private);
4911 * If the IO is already in progress, then this is a re-write
4912 * attempt, so we need to thaw and re-compute the cksum.
4913 * It is the responsibility of the callback to handle the
4914 * accounting for any re-write attempt.
4916 if (HDR_IO_IN_PROGRESS(hdr)) {
4917 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4918 if (hdr->b_freeze_cksum != NULL) {
4919 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4920 hdr->b_freeze_cksum = NULL;
4922 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4924 arc_cksum_compute(buf, B_FALSE);
4925 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4929 * The SPA calls this callback for each physical write that happens on behalf
4930 * of a logical write. See the comment in dbuf_write_physdone() for details.
4933 arc_write_physdone(zio_t *zio)
4935 arc_write_callback_t *cb = zio->io_private;
4936 if (cb->awcb_physdone != NULL)
4937 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4941 arc_write_done(zio_t *zio)
4943 arc_write_callback_t *callback = zio->io_private;
4944 arc_buf_t *buf = callback->awcb_buf;
4945 arc_buf_hdr_t *hdr = buf->b_hdr;
4947 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4949 if (zio->io_error == 0) {
4950 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4951 buf_discard_identity(hdr);
4953 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4954 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4957 ASSERT(BUF_EMPTY(hdr));
4961 * If the block to be written was all-zero or compressed enough to be
4962 * embedded in the BP, no write was performed so there will be no
4963 * dva/birth/checksum. The buffer must therefore remain anonymous
4966 if (!BUF_EMPTY(hdr)) {
4967 arc_buf_hdr_t *exists;
4968 kmutex_t *hash_lock;
4970 ASSERT(zio->io_error == 0);
4972 arc_cksum_verify(buf);
4974 exists = buf_hash_insert(hdr, &hash_lock);
4975 if (exists != NULL) {
4977 * This can only happen if we overwrite for
4978 * sync-to-convergence, because we remove
4979 * buffers from the hash table when we arc_free().
4981 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4982 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4983 panic("bad overwrite, hdr=%p exists=%p",
4984 (void *)hdr, (void *)exists);
4985 ASSERT(refcount_is_zero(
4986 &exists->b_l1hdr.b_refcnt));
4987 arc_change_state(arc_anon, exists, hash_lock);
4988 mutex_exit(hash_lock);
4989 arc_hdr_destroy(exists);
4990 exists = buf_hash_insert(hdr, &hash_lock);
4991 ASSERT3P(exists, ==, NULL);
4992 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
4994 ASSERT(zio->io_prop.zp_nopwrite);
4995 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4996 panic("bad nopwrite, hdr=%p exists=%p",
4997 (void *)hdr, (void *)exists);
5000 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5001 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5002 ASSERT(BP_GET_DEDUP(zio->io_bp));
5003 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5006 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5007 /* if it's not anon, we are doing a scrub */
5008 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5009 arc_access(hdr, hash_lock);
5010 mutex_exit(hash_lock);
5012 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5015 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5016 callback->awcb_done(zio, buf, callback->awcb_private);
5018 kmem_free(callback, sizeof (arc_write_callback_t));
5022 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
5023 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
5024 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
5025 arc_done_func_t *done, void *private, zio_priority_t priority,
5026 int zio_flags, const zbookmark_phys_t *zb)
5028 arc_buf_hdr_t *hdr = buf->b_hdr;
5029 arc_write_callback_t *callback;
5032 ASSERT(ready != NULL);
5033 ASSERT(done != NULL);
5034 ASSERT(!HDR_IO_ERROR(hdr));
5035 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5036 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5037 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5039 hdr->b_flags |= ARC_FLAG_L2CACHE;
5041 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
5042 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5043 callback->awcb_ready = ready;
5044 callback->awcb_physdone = physdone;
5045 callback->awcb_done = done;
5046 callback->awcb_private = private;
5047 callback->awcb_buf = buf;
5049 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
5050 arc_write_ready, arc_write_physdone, arc_write_done, callback,
5051 priority, zio_flags, zb);
5057 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5060 uint64_t available_memory = ptob(freemem);
5061 static uint64_t page_load = 0;
5062 static uint64_t last_txg = 0;
5064 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5066 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5069 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5072 if (txg > last_txg) {
5077 * If we are in pageout, we know that memory is already tight,
5078 * the arc is already going to be evicting, so we just want to
5079 * continue to let page writes occur as quickly as possible.
5081 if (curproc == pageproc) {
5082 if (page_load > MAX(ptob(minfree), available_memory) / 4)
5083 return (SET_ERROR(ERESTART));
5084 /* Note: reserve is inflated, so we deflate */
5085 page_load += reserve / 8;
5087 } else if (page_load > 0 && arc_reclaim_needed()) {
5088 /* memory is low, delay before restarting */
5089 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5090 return (SET_ERROR(EAGAIN));
5098 arc_tempreserve_clear(uint64_t reserve)
5100 atomic_add_64(&arc_tempreserve, -reserve);
5101 ASSERT((int64_t)arc_tempreserve >= 0);
5105 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5110 if (reserve > arc_c/4 && !arc_no_grow) {
5111 arc_c = MIN(arc_c_max, reserve * 4);
5112 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5114 if (reserve > arc_c)
5115 return (SET_ERROR(ENOMEM));
5118 * Don't count loaned bufs as in flight dirty data to prevent long
5119 * network delays from blocking transactions that are ready to be
5120 * assigned to a txg.
5122 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5123 arc_loaned_bytes), 0);
5126 * Writes will, almost always, require additional memory allocations
5127 * in order to compress/encrypt/etc the data. We therefore need to
5128 * make sure that there is sufficient available memory for this.
5130 error = arc_memory_throttle(reserve, txg);
5135 * Throttle writes when the amount of dirty data in the cache
5136 * gets too large. We try to keep the cache less than half full
5137 * of dirty blocks so that our sync times don't grow too large.
5138 * Note: if two requests come in concurrently, we might let them
5139 * both succeed, when one of them should fail. Not a huge deal.
5142 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5143 anon_size > arc_c / 4) {
5144 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5145 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5146 arc_tempreserve>>10,
5147 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5148 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5149 reserve>>10, arc_c>>10);
5150 return (SET_ERROR(ERESTART));
5152 atomic_add_64(&arc_tempreserve, reserve);
5157 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5158 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5160 size->value.ui64 = refcount_count(&state->arcs_size);
5161 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5162 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5166 arc_kstat_update(kstat_t *ksp, int rw)
5168 arc_stats_t *as = ksp->ks_data;
5170 if (rw == KSTAT_WRITE) {
5173 arc_kstat_update_state(arc_anon,
5174 &as->arcstat_anon_size,
5175 &as->arcstat_anon_evictable_data,
5176 &as->arcstat_anon_evictable_metadata);
5177 arc_kstat_update_state(arc_mru,
5178 &as->arcstat_mru_size,
5179 &as->arcstat_mru_evictable_data,
5180 &as->arcstat_mru_evictable_metadata);
5181 arc_kstat_update_state(arc_mru_ghost,
5182 &as->arcstat_mru_ghost_size,
5183 &as->arcstat_mru_ghost_evictable_data,
5184 &as->arcstat_mru_ghost_evictable_metadata);
5185 arc_kstat_update_state(arc_mfu,
5186 &as->arcstat_mfu_size,
5187 &as->arcstat_mfu_evictable_data,
5188 &as->arcstat_mfu_evictable_metadata);
5189 arc_kstat_update_state(arc_mfu_ghost,
5190 &as->arcstat_mfu_ghost_size,
5191 &as->arcstat_mfu_ghost_evictable_data,
5192 &as->arcstat_mfu_ghost_evictable_metadata);
5199 * This function *must* return indices evenly distributed between all
5200 * sublists of the multilist. This is needed due to how the ARC eviction
5201 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5202 * distributed between all sublists and uses this assumption when
5203 * deciding which sublist to evict from and how much to evict from it.
5206 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5208 arc_buf_hdr_t *hdr = obj;
5211 * We rely on b_dva to generate evenly distributed index
5212 * numbers using buf_hash below. So, as an added precaution,
5213 * let's make sure we never add empty buffers to the arc lists.
5215 ASSERT(!BUF_EMPTY(hdr));
5218 * The assumption here, is the hash value for a given
5219 * arc_buf_hdr_t will remain constant throughout it's lifetime
5220 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5221 * Thus, we don't need to store the header's sublist index
5222 * on insertion, as this index can be recalculated on removal.
5224 * Also, the low order bits of the hash value are thought to be
5225 * distributed evenly. Otherwise, in the case that the multilist
5226 * has a power of two number of sublists, each sublists' usage
5227 * would not be evenly distributed.
5229 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5230 multilist_get_num_sublists(ml));
5234 static eventhandler_tag arc_event_lowmem = NULL;
5237 arc_lowmem(void *arg __unused, int howto __unused)
5240 mutex_enter(&arc_reclaim_lock);
5241 /* XXX: Memory deficit should be passed as argument. */
5242 needfree = btoc(arc_c >> arc_shrink_shift);
5243 DTRACE_PROBE(arc__needfree);
5244 cv_signal(&arc_reclaim_thread_cv);
5247 * It is unsafe to block here in arbitrary threads, because we can come
5248 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5249 * with ARC reclaim thread.
5251 if (curproc == pageproc)
5252 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5253 mutex_exit(&arc_reclaim_lock);
5260 int i, prefetch_tunable_set = 0;
5262 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5263 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5264 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5266 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5267 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5269 /* Convert seconds to clock ticks */
5270 arc_min_prefetch_lifespan = 1 * hz;
5272 /* Start out with 1/8 of all memory */
5273 arc_c = kmem_size() / 8;
5278 * On architectures where the physical memory can be larger
5279 * than the addressable space (intel in 32-bit mode), we may
5280 * need to limit the cache to 1/8 of VM size.
5282 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5285 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5286 arc_c_min = MAX(arc_c / 4, 16 << 20);
5287 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5288 if (arc_c * 8 >= 1 << 30)
5289 arc_c_max = (arc_c * 8) - (1 << 30);
5291 arc_c_max = arc_c_min;
5292 arc_c_max = MAX(arc_c * 5, arc_c_max);
5296 * Allow the tunables to override our calculations if they are
5297 * reasonable (ie. over 16MB)
5299 if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5300 arc_c_max = zfs_arc_max;
5301 if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5302 arc_c_min = zfs_arc_min;
5306 arc_p = (arc_c >> 1);
5308 /* limit meta-data to 1/4 of the arc capacity */
5309 arc_meta_limit = arc_c_max / 4;
5311 /* Allow the tunable to override if it is reasonable */
5312 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5313 arc_meta_limit = zfs_arc_meta_limit;
5315 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5316 arc_c_min = arc_meta_limit / 2;
5318 if (zfs_arc_meta_min > 0) {
5319 arc_meta_min = zfs_arc_meta_min;
5321 arc_meta_min = arc_c_min / 2;
5324 if (zfs_arc_grow_retry > 0)
5325 arc_grow_retry = zfs_arc_grow_retry;
5327 if (zfs_arc_shrink_shift > 0)
5328 arc_shrink_shift = zfs_arc_shrink_shift;
5331 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5333 if (arc_no_grow_shift >= arc_shrink_shift)
5334 arc_no_grow_shift = arc_shrink_shift - 1;
5336 if (zfs_arc_p_min_shift > 0)
5337 arc_p_min_shift = zfs_arc_p_min_shift;
5339 if (zfs_arc_num_sublists_per_state < 1)
5340 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5342 /* if kmem_flags are set, lets try to use less memory */
5343 if (kmem_debugging())
5345 if (arc_c < arc_c_min)
5348 zfs_arc_min = arc_c_min;
5349 zfs_arc_max = arc_c_max;
5351 arc_anon = &ARC_anon;
5353 arc_mru_ghost = &ARC_mru_ghost;
5355 arc_mfu_ghost = &ARC_mfu_ghost;
5356 arc_l2c_only = &ARC_l2c_only;
5359 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5360 sizeof (arc_buf_hdr_t),
5361 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5362 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5363 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5364 sizeof (arc_buf_hdr_t),
5365 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5366 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5367 multilist_create(&arc_mru_ghost->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_ghost->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_mfu->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_mfu->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_ghost->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_ghost->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_l2c_only->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_l2c_only->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);
5400 refcount_create(&arc_anon->arcs_size);
5401 refcount_create(&arc_mru->arcs_size);
5402 refcount_create(&arc_mru_ghost->arcs_size);
5403 refcount_create(&arc_mfu->arcs_size);
5404 refcount_create(&arc_mfu_ghost->arcs_size);
5405 refcount_create(&arc_l2c_only->arcs_size);
5409 arc_reclaim_thread_exit = FALSE;
5410 arc_user_evicts_thread_exit = FALSE;
5411 arc_eviction_list = NULL;
5412 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5414 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5415 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5417 if (arc_ksp != NULL) {
5418 arc_ksp->ks_data = &arc_stats;
5419 arc_ksp->ks_update = arc_kstat_update;
5420 kstat_install(arc_ksp);
5423 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5424 TS_RUN, minclsyspri);
5427 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5428 EVENTHANDLER_PRI_FIRST);
5431 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5432 TS_RUN, minclsyspri);
5438 * Calculate maximum amount of dirty data per pool.
5440 * If it has been set by /etc/system, take that.
5441 * Otherwise, use a percentage of physical memory defined by
5442 * zfs_dirty_data_max_percent (default 10%) with a cap at
5443 * zfs_dirty_data_max_max (default 4GB).
5445 if (zfs_dirty_data_max == 0) {
5446 zfs_dirty_data_max = ptob(physmem) *
5447 zfs_dirty_data_max_percent / 100;
5448 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5449 zfs_dirty_data_max_max);
5453 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5454 prefetch_tunable_set = 1;
5457 if (prefetch_tunable_set == 0) {
5458 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5460 printf(" add \"vfs.zfs.prefetch_disable=0\" "
5461 "to /boot/loader.conf.\n");
5462 zfs_prefetch_disable = 1;
5465 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5466 prefetch_tunable_set == 0) {
5467 printf("ZFS NOTICE: Prefetch is disabled by default if less "
5468 "than 4GB of RAM is present;\n"
5469 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
5470 "to /boot/loader.conf.\n");
5471 zfs_prefetch_disable = 1;
5474 /* Warn about ZFS memory and address space requirements. */
5475 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5476 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5477 "expect unstable behavior.\n");
5479 if (kmem_size() < 512 * (1 << 20)) {
5480 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5481 "expect unstable behavior.\n");
5482 printf(" Consider tuning vm.kmem_size and "
5483 "vm.kmem_size_max\n");
5484 printf(" in /boot/loader.conf.\n");
5492 mutex_enter(&arc_reclaim_lock);
5493 arc_reclaim_thread_exit = TRUE;
5495 * The reclaim thread will set arc_reclaim_thread_exit back to
5496 * FALSE when it is finished exiting; we're waiting for that.
5498 while (arc_reclaim_thread_exit) {
5499 cv_signal(&arc_reclaim_thread_cv);
5500 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5502 mutex_exit(&arc_reclaim_lock);
5504 mutex_enter(&arc_user_evicts_lock);
5505 arc_user_evicts_thread_exit = TRUE;
5507 * The user evicts thread will set arc_user_evicts_thread_exit
5508 * to FALSE when it is finished exiting; we're waiting for that.
5510 while (arc_user_evicts_thread_exit) {
5511 cv_signal(&arc_user_evicts_cv);
5512 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5514 mutex_exit(&arc_user_evicts_lock);
5516 /* Use TRUE to ensure *all* buffers are evicted */
5517 arc_flush(NULL, TRUE);
5521 if (arc_ksp != NULL) {
5522 kstat_delete(arc_ksp);
5526 mutex_destroy(&arc_reclaim_lock);
5527 cv_destroy(&arc_reclaim_thread_cv);
5528 cv_destroy(&arc_reclaim_waiters_cv);
5530 mutex_destroy(&arc_user_evicts_lock);
5531 cv_destroy(&arc_user_evicts_cv);
5533 refcount_destroy(&arc_anon->arcs_size);
5534 refcount_destroy(&arc_mru->arcs_size);
5535 refcount_destroy(&arc_mru_ghost->arcs_size);
5536 refcount_destroy(&arc_mfu->arcs_size);
5537 refcount_destroy(&arc_mfu_ghost->arcs_size);
5538 refcount_destroy(&arc_l2c_only->arcs_size);
5540 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5541 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5542 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5543 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5544 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5545 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5546 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5547 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5551 ASSERT0(arc_loaned_bytes);
5554 if (arc_event_lowmem != NULL)
5555 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5562 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5563 * It uses dedicated storage devices to hold cached data, which are populated
5564 * using large infrequent writes. The main role of this cache is to boost
5565 * the performance of random read workloads. The intended L2ARC devices
5566 * include short-stroked disks, solid state disks, and other media with
5567 * substantially faster read latency than disk.
5569 * +-----------------------+
5571 * +-----------------------+
5574 * l2arc_feed_thread() arc_read()
5578 * +---------------+ |
5580 * +---------------+ |
5585 * +-------+ +-------+
5587 * | cache | | cache |
5588 * +-------+ +-------+
5589 * +=========+ .-----.
5590 * : L2ARC : |-_____-|
5591 * : devices : | Disks |
5592 * +=========+ `-_____-'
5594 * Read requests are satisfied from the following sources, in order:
5597 * 2) vdev cache of L2ARC devices
5599 * 4) vdev cache of disks
5602 * Some L2ARC device types exhibit extremely slow write performance.
5603 * To accommodate for this there are some significant differences between
5604 * the L2ARC and traditional cache design:
5606 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5607 * the ARC behave as usual, freeing buffers and placing headers on ghost
5608 * lists. The ARC does not send buffers to the L2ARC during eviction as
5609 * this would add inflated write latencies for all ARC memory pressure.
5611 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5612 * It does this by periodically scanning buffers from the eviction-end of
5613 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5614 * not already there. It scans until a headroom of buffers is satisfied,
5615 * which itself is a buffer for ARC eviction. If a compressible buffer is
5616 * found during scanning and selected for writing to an L2ARC device, we
5617 * temporarily boost scanning headroom during the next scan cycle to make
5618 * sure we adapt to compression effects (which might significantly reduce
5619 * the data volume we write to L2ARC). The thread that does this is
5620 * l2arc_feed_thread(), illustrated below; example sizes are included to
5621 * provide a better sense of ratio than this diagram:
5624 * +---------------------+----------+
5625 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5626 * +---------------------+----------+ | o L2ARC eligible
5627 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5628 * +---------------------+----------+ |
5629 * 15.9 Gbytes ^ 32 Mbytes |
5631 * l2arc_feed_thread()
5633 * l2arc write hand <--[oooo]--'
5637 * +==============================+
5638 * L2ARC dev |####|#|###|###| |####| ... |
5639 * +==============================+
5642 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5643 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5644 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5645 * safe to say that this is an uncommon case, since buffers at the end of
5646 * the ARC lists have moved there due to inactivity.
5648 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5649 * then the L2ARC simply misses copying some buffers. This serves as a
5650 * pressure valve to prevent heavy read workloads from both stalling the ARC
5651 * with waits and clogging the L2ARC with writes. This also helps prevent
5652 * the potential for the L2ARC to churn if it attempts to cache content too
5653 * quickly, such as during backups of the entire pool.
5655 * 5. After system boot and before the ARC has filled main memory, there are
5656 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5657 * lists can remain mostly static. Instead of searching from tail of these
5658 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5659 * for eligible buffers, greatly increasing its chance of finding them.
5661 * The L2ARC device write speed is also boosted during this time so that
5662 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5663 * there are no L2ARC reads, and no fear of degrading read performance
5664 * through increased writes.
5666 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5667 * the vdev queue can aggregate them into larger and fewer writes. Each
5668 * device is written to in a rotor fashion, sweeping writes through
5669 * available space then repeating.
5671 * 7. The L2ARC does not store dirty content. It never needs to flush
5672 * write buffers back to disk based storage.
5674 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5675 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5677 * The performance of the L2ARC can be tweaked by a number of tunables, which
5678 * may be necessary for different workloads:
5680 * l2arc_write_max max write bytes per interval
5681 * l2arc_write_boost extra write bytes during device warmup
5682 * l2arc_noprefetch skip caching prefetched buffers
5683 * l2arc_headroom number of max device writes to precache
5684 * l2arc_headroom_boost when we find compressed buffers during ARC
5685 * scanning, we multiply headroom by this
5686 * percentage factor for the next scan cycle,
5687 * since more compressed buffers are likely to
5689 * l2arc_feed_secs seconds between L2ARC writing
5691 * Tunables may be removed or added as future performance improvements are
5692 * integrated, and also may become zpool properties.
5694 * There are three key functions that control how the L2ARC warms up:
5696 * l2arc_write_eligible() check if a buffer is eligible to cache
5697 * l2arc_write_size() calculate how much to write
5698 * l2arc_write_interval() calculate sleep delay between writes
5700 * These three functions determine what to write, how much, and how quickly
5705 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5708 * A buffer is *not* eligible for the L2ARC if it:
5709 * 1. belongs to a different spa.
5710 * 2. is already cached on the L2ARC.
5711 * 3. has an I/O in progress (it may be an incomplete read).
5712 * 4. is flagged not eligible (zfs property).
5714 if (hdr->b_spa != spa_guid) {
5715 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5718 if (HDR_HAS_L2HDR(hdr)) {
5719 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5722 if (HDR_IO_IN_PROGRESS(hdr)) {
5723 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5726 if (!HDR_L2CACHE(hdr)) {
5727 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5735 l2arc_write_size(void)
5740 * Make sure our globals have meaningful values in case the user
5743 size = l2arc_write_max;
5745 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5746 "be greater than zero, resetting it to the default (%d)",
5748 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5751 if (arc_warm == B_FALSE)
5752 size += l2arc_write_boost;
5759 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5761 clock_t interval, next, now;
5764 * If the ARC lists are busy, increase our write rate; if the
5765 * lists are stale, idle back. This is achieved by checking
5766 * how much we previously wrote - if it was more than half of
5767 * what we wanted, schedule the next write much sooner.
5769 if (l2arc_feed_again && wrote > (wanted / 2))
5770 interval = (hz * l2arc_feed_min_ms) / 1000;
5772 interval = hz * l2arc_feed_secs;
5774 now = ddi_get_lbolt();
5775 next = MAX(now, MIN(now + interval, began + interval));
5781 * Cycle through L2ARC devices. This is how L2ARC load balances.
5782 * If a device is returned, this also returns holding the spa config lock.
5784 static l2arc_dev_t *
5785 l2arc_dev_get_next(void)
5787 l2arc_dev_t *first, *next = NULL;
5790 * Lock out the removal of spas (spa_namespace_lock), then removal
5791 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5792 * both locks will be dropped and a spa config lock held instead.
5794 mutex_enter(&spa_namespace_lock);
5795 mutex_enter(&l2arc_dev_mtx);
5797 /* if there are no vdevs, there is nothing to do */
5798 if (l2arc_ndev == 0)
5802 next = l2arc_dev_last;
5804 /* loop around the list looking for a non-faulted vdev */
5806 next = list_head(l2arc_dev_list);
5808 next = list_next(l2arc_dev_list, next);
5810 next = list_head(l2arc_dev_list);
5813 /* if we have come back to the start, bail out */
5816 else if (next == first)
5819 } while (vdev_is_dead(next->l2ad_vdev));
5821 /* if we were unable to find any usable vdevs, return NULL */
5822 if (vdev_is_dead(next->l2ad_vdev))
5825 l2arc_dev_last = next;
5828 mutex_exit(&l2arc_dev_mtx);
5831 * Grab the config lock to prevent the 'next' device from being
5832 * removed while we are writing to it.
5835 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5836 mutex_exit(&spa_namespace_lock);
5842 * Free buffers that were tagged for destruction.
5845 l2arc_do_free_on_write()
5848 l2arc_data_free_t *df, *df_prev;
5850 mutex_enter(&l2arc_free_on_write_mtx);
5851 buflist = l2arc_free_on_write;
5853 for (df = list_tail(buflist); df; df = df_prev) {
5854 df_prev = list_prev(buflist, df);
5855 ASSERT(df->l2df_data != NULL);
5856 ASSERT(df->l2df_func != NULL);
5857 df->l2df_func(df->l2df_data, df->l2df_size);
5858 list_remove(buflist, df);
5859 kmem_free(df, sizeof (l2arc_data_free_t));
5862 mutex_exit(&l2arc_free_on_write_mtx);
5866 * A write to a cache device has completed. Update all headers to allow
5867 * reads from these buffers to begin.
5870 l2arc_write_done(zio_t *zio)
5872 l2arc_write_callback_t *cb;
5875 arc_buf_hdr_t *head, *hdr, *hdr_prev;
5876 kmutex_t *hash_lock;
5877 int64_t bytes_dropped = 0;
5879 cb = zio->io_private;
5881 dev = cb->l2wcb_dev;
5882 ASSERT(dev != NULL);
5883 head = cb->l2wcb_head;
5884 ASSERT(head != NULL);
5885 buflist = &dev->l2ad_buflist;
5886 ASSERT(buflist != NULL);
5887 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5888 l2arc_write_callback_t *, cb);
5890 if (zio->io_error != 0)
5891 ARCSTAT_BUMP(arcstat_l2_writes_error);
5894 * All writes completed, or an error was hit.
5897 mutex_enter(&dev->l2ad_mtx);
5898 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5899 hdr_prev = list_prev(buflist, hdr);
5901 hash_lock = HDR_LOCK(hdr);
5904 * We cannot use mutex_enter or else we can deadlock
5905 * with l2arc_write_buffers (due to swapping the order
5906 * the hash lock and l2ad_mtx are taken).
5908 if (!mutex_tryenter(hash_lock)) {
5910 * Missed the hash lock. We must retry so we
5911 * don't leave the ARC_FLAG_L2_WRITING bit set.
5913 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5916 * We don't want to rescan the headers we've
5917 * already marked as having been written out, so
5918 * we reinsert the head node so we can pick up
5919 * where we left off.
5921 list_remove(buflist, head);
5922 list_insert_after(buflist, hdr, head);
5924 mutex_exit(&dev->l2ad_mtx);
5927 * We wait for the hash lock to become available
5928 * to try and prevent busy waiting, and increase
5929 * the chance we'll be able to acquire the lock
5930 * the next time around.
5932 mutex_enter(hash_lock);
5933 mutex_exit(hash_lock);
5938 * We could not have been moved into the arc_l2c_only
5939 * state while in-flight due to our ARC_FLAG_L2_WRITING
5940 * bit being set. Let's just ensure that's being enforced.
5942 ASSERT(HDR_HAS_L1HDR(hdr));
5945 * We may have allocated a buffer for L2ARC compression,
5946 * we must release it to avoid leaking this data.
5948 l2arc_release_cdata_buf(hdr);
5950 if (zio->io_error != 0) {
5952 * Error - drop L2ARC entry.
5954 list_remove(buflist, hdr);
5955 trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
5956 hdr->b_l2hdr.b_daddr, hdr->b_l2hdr.b_asize, 0);
5957 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5959 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5960 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5962 bytes_dropped += hdr->b_l2hdr.b_asize;
5963 (void) refcount_remove_many(&dev->l2ad_alloc,
5964 hdr->b_l2hdr.b_asize, hdr);
5968 * Allow ARC to begin reads and ghost list evictions to
5971 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5973 mutex_exit(hash_lock);
5976 atomic_inc_64(&l2arc_writes_done);
5977 list_remove(buflist, head);
5978 ASSERT(!HDR_HAS_L1HDR(head));
5979 kmem_cache_free(hdr_l2only_cache, head);
5980 mutex_exit(&dev->l2ad_mtx);
5982 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5984 l2arc_do_free_on_write();
5986 kmem_free(cb, sizeof (l2arc_write_callback_t));
5990 * A read to a cache device completed. Validate buffer contents before
5991 * handing over to the regular ARC routines.
5994 l2arc_read_done(zio_t *zio)
5996 l2arc_read_callback_t *cb;
5999 kmutex_t *hash_lock;
6002 ASSERT(zio->io_vd != NULL);
6003 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6005 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6007 cb = zio->io_private;
6009 buf = cb->l2rcb_buf;
6010 ASSERT(buf != NULL);
6012 hash_lock = HDR_LOCK(buf->b_hdr);
6013 mutex_enter(hash_lock);
6015 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6018 * If the buffer was compressed, decompress it first.
6020 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
6021 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6022 ASSERT(zio->io_data != NULL);
6023 ASSERT3U(zio->io_size, ==, hdr->b_size);
6024 ASSERT3U(BP_GET_LSIZE(&cb->l2rcb_bp), ==, hdr->b_size);
6027 * Check this survived the L2ARC journey.
6029 equal = arc_cksum_equal(buf);
6030 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6031 mutex_exit(hash_lock);
6032 zio->io_private = buf;
6033 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6034 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6037 mutex_exit(hash_lock);
6039 * Buffer didn't survive caching. Increment stats and
6040 * reissue to the original storage device.
6042 if (zio->io_error != 0) {
6043 ARCSTAT_BUMP(arcstat_l2_io_error);
6045 zio->io_error = SET_ERROR(EIO);
6048 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6051 * If there's no waiter, issue an async i/o to the primary
6052 * storage now. If there *is* a waiter, the caller must
6053 * issue the i/o in a context where it's OK to block.
6055 if (zio->io_waiter == NULL) {
6056 zio_t *pio = zio_unique_parent(zio);
6058 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6060 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6061 buf->b_data, hdr->b_size, arc_read_done, buf,
6062 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6066 kmem_free(cb, sizeof (l2arc_read_callback_t));
6070 * This is the list priority from which the L2ARC will search for pages to
6071 * cache. This is used within loops (0..3) to cycle through lists in the
6072 * desired order. This order can have a significant effect on cache
6075 * Currently the metadata lists are hit first, MFU then MRU, followed by
6076 * the data lists. This function returns a locked list, and also returns
6079 static multilist_sublist_t *
6080 l2arc_sublist_lock(int list_num)
6082 multilist_t *ml = NULL;
6085 ASSERT(list_num >= 0 && list_num <= 3);
6089 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6092 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6095 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6098 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6103 * Return a randomly-selected sublist. This is acceptable
6104 * because the caller feeds only a little bit of data for each
6105 * call (8MB). Subsequent calls will result in different
6106 * sublists being selected.
6108 idx = multilist_get_random_index(ml);
6109 return (multilist_sublist_lock(ml, idx));
6113 * Evict buffers from the device write hand to the distance specified in
6114 * bytes. This distance may span populated buffers, it may span nothing.
6115 * This is clearing a region on the L2ARC device ready for writing.
6116 * If the 'all' boolean is set, every buffer is evicted.
6119 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6122 arc_buf_hdr_t *hdr, *hdr_prev;
6123 kmutex_t *hash_lock;
6126 buflist = &dev->l2ad_buflist;
6128 if (!all && dev->l2ad_first) {
6130 * This is the first sweep through the device. There is
6136 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6138 * When nearing the end of the device, evict to the end
6139 * before the device write hand jumps to the start.
6141 taddr = dev->l2ad_end;
6143 taddr = dev->l2ad_hand + distance;
6145 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6146 uint64_t, taddr, boolean_t, all);
6149 mutex_enter(&dev->l2ad_mtx);
6150 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6151 hdr_prev = list_prev(buflist, hdr);
6153 hash_lock = HDR_LOCK(hdr);
6156 * We cannot use mutex_enter or else we can deadlock
6157 * with l2arc_write_buffers (due to swapping the order
6158 * the hash lock and l2ad_mtx are taken).
6160 if (!mutex_tryenter(hash_lock)) {
6162 * Missed the hash lock. Retry.
6164 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6165 mutex_exit(&dev->l2ad_mtx);
6166 mutex_enter(hash_lock);
6167 mutex_exit(hash_lock);
6171 if (HDR_L2_WRITE_HEAD(hdr)) {
6173 * We hit a write head node. Leave it for
6174 * l2arc_write_done().
6176 list_remove(buflist, hdr);
6177 mutex_exit(hash_lock);
6181 if (!all && HDR_HAS_L2HDR(hdr) &&
6182 (hdr->b_l2hdr.b_daddr > taddr ||
6183 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6185 * We've evicted to the target address,
6186 * or the end of the device.
6188 mutex_exit(hash_lock);
6192 ASSERT(HDR_HAS_L2HDR(hdr));
6193 if (!HDR_HAS_L1HDR(hdr)) {
6194 ASSERT(!HDR_L2_READING(hdr));
6196 * This doesn't exist in the ARC. Destroy.
6197 * arc_hdr_destroy() will call list_remove()
6198 * and decrement arcstat_l2_size.
6200 arc_change_state(arc_anon, hdr, hash_lock);
6201 arc_hdr_destroy(hdr);
6203 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6204 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6206 * Invalidate issued or about to be issued
6207 * reads, since we may be about to write
6208 * over this location.
6210 if (HDR_L2_READING(hdr)) {
6211 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6212 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6215 /* Ensure this header has finished being written */
6216 ASSERT(!HDR_L2_WRITING(hdr));
6217 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6219 arc_hdr_l2hdr_destroy(hdr);
6221 mutex_exit(hash_lock);
6223 mutex_exit(&dev->l2ad_mtx);
6227 * Find and write ARC buffers to the L2ARC device.
6229 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6230 * for reading until they have completed writing.
6231 * The headroom_boost is an in-out parameter used to maintain headroom boost
6232 * state between calls to this function.
6234 * Returns the number of bytes actually written (which may be smaller than
6235 * the delta by which the device hand has changed due to alignment).
6238 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6239 boolean_t *headroom_boost)
6241 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6242 uint64_t write_asize, write_sz, headroom, buf_compress_minsz;
6245 l2arc_write_callback_t *cb;
6247 uint64_t guid = spa_load_guid(spa);
6248 const boolean_t do_headroom_boost = *headroom_boost;
6251 ASSERT(dev->l2ad_vdev != NULL);
6253 /* Lower the flag now, we might want to raise it again later. */
6254 *headroom_boost = B_FALSE;
6257 write_sz = write_asize = 0;
6259 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6260 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6261 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6263 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6265 * We will want to try to compress buffers that are at least 2x the
6266 * device sector size.
6268 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6271 * Copy buffers for L2ARC writing.
6273 for (try = 0; try <= 3; try++) {
6274 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6275 uint64_t passed_sz = 0;
6277 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6280 * L2ARC fast warmup.
6282 * Until the ARC is warm and starts to evict, read from the
6283 * head of the ARC lists rather than the tail.
6285 if (arc_warm == B_FALSE)
6286 hdr = multilist_sublist_head(mls);
6288 hdr = multilist_sublist_tail(mls);
6290 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6292 headroom = target_sz * l2arc_headroom;
6293 if (do_headroom_boost)
6294 headroom = (headroom * l2arc_headroom_boost) / 100;
6296 for (; hdr; hdr = hdr_prev) {
6297 kmutex_t *hash_lock;
6301 if (arc_warm == B_FALSE)
6302 hdr_prev = multilist_sublist_next(mls, hdr);
6304 hdr_prev = multilist_sublist_prev(mls, hdr);
6305 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6307 hash_lock = HDR_LOCK(hdr);
6308 if (!mutex_tryenter(hash_lock)) {
6309 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6311 * Skip this buffer rather than waiting.
6316 passed_sz += hdr->b_size;
6317 if (passed_sz > headroom) {
6321 mutex_exit(hash_lock);
6322 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6326 if (!l2arc_write_eligible(guid, hdr)) {
6327 mutex_exit(hash_lock);
6332 * Assume that the buffer is not going to be compressed
6333 * and could take more space on disk because of a larger
6336 buf_sz = hdr->b_size;
6337 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6339 if ((write_asize + buf_a_sz) > target_sz) {
6341 mutex_exit(hash_lock);
6342 ARCSTAT_BUMP(arcstat_l2_write_full);
6348 * Insert a dummy header on the buflist so
6349 * l2arc_write_done() can find where the
6350 * write buffers begin without searching.
6352 mutex_enter(&dev->l2ad_mtx);
6353 list_insert_head(&dev->l2ad_buflist, head);
6354 mutex_exit(&dev->l2ad_mtx);
6357 sizeof (l2arc_write_callback_t), KM_SLEEP);
6358 cb->l2wcb_dev = dev;
6359 cb->l2wcb_head = head;
6360 pio = zio_root(spa, l2arc_write_done, cb,
6362 ARCSTAT_BUMP(arcstat_l2_write_pios);
6366 * Create and add a new L2ARC header.
6368 hdr->b_l2hdr.b_dev = dev;
6369 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6371 * Temporarily stash the data buffer in b_tmp_cdata.
6372 * The subsequent write step will pick it up from
6373 * there. This is because can't access b_l1hdr.b_buf
6374 * without holding the hash_lock, which we in turn
6375 * can't access without holding the ARC list locks
6376 * (which we want to avoid during compression/writing).
6378 hdr->b_l2hdr.b_compress = ZIO_COMPRESS_OFF;
6379 hdr->b_l2hdr.b_asize = hdr->b_size;
6380 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6383 * Explicitly set the b_daddr field to a known
6384 * value which means "invalid address". This
6385 * enables us to differentiate which stage of
6386 * l2arc_write_buffers() the particular header
6387 * is in (e.g. this loop, or the one below).
6388 * ARC_FLAG_L2_WRITING is not enough to make
6389 * this distinction, and we need to know in
6390 * order to do proper l2arc vdev accounting in
6391 * arc_release() and arc_hdr_destroy().
6393 * Note, we can't use a new flag to distinguish
6394 * the two stages because we don't hold the
6395 * header's hash_lock below, in the second stage
6396 * of this function. Thus, we can't simply
6397 * change the b_flags field to denote that the
6398 * IO has been sent. We can change the b_daddr
6399 * field of the L2 portion, though, since we'll
6400 * be holding the l2ad_mtx; which is why we're
6401 * using it to denote the header's state change.
6403 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6404 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6406 mutex_enter(&dev->l2ad_mtx);
6407 list_insert_head(&dev->l2ad_buflist, hdr);
6408 mutex_exit(&dev->l2ad_mtx);
6411 * Compute and store the buffer cksum before
6412 * writing. On debug the cksum is verified first.
6414 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6415 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6417 mutex_exit(hash_lock);
6420 write_asize += buf_a_sz;
6423 multilist_sublist_unlock(mls);
6429 /* No buffers selected for writing? */
6432 ASSERT(!HDR_HAS_L1HDR(head));
6433 kmem_cache_free(hdr_l2only_cache, head);
6437 mutex_enter(&dev->l2ad_mtx);
6440 * Note that elsewhere in this file arcstat_l2_asize
6441 * and the used space on l2ad_vdev are updated using b_asize,
6442 * which is not necessarily rounded up to the device block size.
6443 * Too keep accounting consistent we do the same here as well:
6444 * stats_size accumulates the sum of b_asize of the written buffers,
6445 * while write_asize accumulates the sum of b_asize rounded up
6446 * to the device block size.
6447 * The latter sum is used only to validate the corectness of the code.
6449 uint64_t stats_size = 0;
6453 * Now start writing the buffers. We're starting at the write head
6454 * and work backwards, retracing the course of the buffer selector
6457 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6458 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6462 * We rely on the L1 portion of the header below, so
6463 * it's invalid for this header to have been evicted out
6464 * of the ghost cache, prior to being written out. The
6465 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6467 ASSERT(HDR_HAS_L1HDR(hdr));
6470 * We shouldn't need to lock the buffer here, since we flagged
6471 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6472 * take care to only access its L2 cache parameters. In
6473 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6476 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6478 if ((HDR_L2COMPRESS(hdr)) &&
6479 hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6480 if (l2arc_compress_buf(hdr)) {
6482 * If compression succeeded, enable headroom
6483 * boost on the next scan cycle.
6485 *headroom_boost = B_TRUE;
6490 * Pick up the buffer data we had previously stashed away
6491 * (and now potentially also compressed).
6493 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6494 buf_sz = hdr->b_l2hdr.b_asize;
6497 * We need to do this regardless if buf_sz is zero or
6498 * not, otherwise, when this l2hdr is evicted we'll
6499 * remove a reference that was never added.
6501 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6503 /* Compression may have squashed the buffer to zero length. */
6507 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6508 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6509 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6510 ZIO_FLAG_CANFAIL, B_FALSE);
6512 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6514 (void) zio_nowait(wzio);
6516 stats_size += buf_sz;
6519 * Keep the clock hand suitably device-aligned.
6521 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6522 write_asize += buf_a_sz;
6523 dev->l2ad_hand += buf_a_sz;
6527 mutex_exit(&dev->l2ad_mtx);
6529 ASSERT3U(write_asize, <=, target_sz);
6530 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6531 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6532 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6533 ARCSTAT_INCR(arcstat_l2_asize, stats_size);
6534 vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
6537 * Bump device hand to the device start if it is approaching the end.
6538 * l2arc_evict() will already have evicted ahead for this case.
6540 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6541 dev->l2ad_hand = dev->l2ad_start;
6542 dev->l2ad_first = B_FALSE;
6545 dev->l2ad_writing = B_TRUE;
6546 (void) zio_wait(pio);
6547 dev->l2ad_writing = B_FALSE;
6549 return (write_asize);
6553 * Compresses an L2ARC buffer.
6554 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6555 * size in l2hdr->b_asize. This routine tries to compress the data and
6556 * depending on the compression result there are three possible outcomes:
6557 * *) The buffer was incompressible. The original l2hdr contents were left
6558 * untouched and are ready for writing to an L2 device.
6559 * *) The buffer was all-zeros, so there is no need to write it to an L2
6560 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6561 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6562 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6563 * data buffer which holds the compressed data to be written, and b_asize
6564 * tells us how much data there is. b_compress is set to the appropriate
6565 * compression algorithm. Once writing is done, invoke
6566 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6568 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6569 * buffer was incompressible).
6572 l2arc_compress_buf(arc_buf_hdr_t *hdr)
6575 size_t csize, len, rounded;
6576 ASSERT(HDR_HAS_L2HDR(hdr));
6577 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6579 ASSERT(HDR_HAS_L1HDR(hdr));
6580 ASSERT3S(l2hdr->b_compress, ==, ZIO_COMPRESS_OFF);
6581 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6583 len = l2hdr->b_asize;
6584 cdata = zio_data_buf_alloc(len);
6585 ASSERT3P(cdata, !=, NULL);
6586 csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6587 cdata, l2hdr->b_asize);
6590 /* zero block, indicate that there's nothing to write */
6591 zio_data_buf_free(cdata, len);
6592 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
6594 hdr->b_l1hdr.b_tmp_cdata = NULL;
6595 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6599 rounded = P2ROUNDUP(csize,
6600 (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
6601 if (rounded < len) {
6603 * Compression succeeded, we'll keep the cdata around for
6604 * writing and release it afterwards.
6606 if (rounded > csize) {
6607 bzero((char *)cdata + csize, rounded - csize);
6610 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
6611 l2hdr->b_asize = csize;
6612 hdr->b_l1hdr.b_tmp_cdata = cdata;
6613 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6617 * Compression failed, release the compressed buffer.
6618 * l2hdr will be left unmodified.
6620 zio_data_buf_free(cdata, len);
6621 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6627 * Decompresses a zio read back from an l2arc device. On success, the
6628 * underlying zio's io_data buffer is overwritten by the uncompressed
6629 * version. On decompression error (corrupt compressed stream), the
6630 * zio->io_error value is set to signal an I/O error.
6632 * Please note that the compressed data stream is not checksummed, so
6633 * if the underlying device is experiencing data corruption, we may feed
6634 * corrupt data to the decompressor, so the decompressor needs to be
6635 * able to handle this situation (LZ4 does).
6638 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6640 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6642 if (zio->io_error != 0) {
6644 * An io error has occured, just restore the original io
6645 * size in preparation for a main pool read.
6647 zio->io_orig_size = zio->io_size = hdr->b_size;
6651 if (c == ZIO_COMPRESS_EMPTY) {
6653 * An empty buffer results in a null zio, which means we
6654 * need to fill its io_data after we're done restoring the
6655 * buffer's contents.
6657 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6658 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6659 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6661 ASSERT(zio->io_data != NULL);
6663 * We copy the compressed data from the start of the arc buffer
6664 * (the zio_read will have pulled in only what we need, the
6665 * rest is garbage which we will overwrite at decompression)
6666 * and then decompress back to the ARC data buffer. This way we
6667 * can minimize copying by simply decompressing back over the
6668 * original compressed data (rather than decompressing to an
6669 * aux buffer and then copying back the uncompressed buffer,
6670 * which is likely to be much larger).
6675 csize = zio->io_size;
6676 cdata = zio_data_buf_alloc(csize);
6677 bcopy(zio->io_data, cdata, csize);
6678 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6680 zio->io_error = EIO;
6681 zio_data_buf_free(cdata, csize);
6684 /* Restore the expected uncompressed IO size. */
6685 zio->io_orig_size = zio->io_size = hdr->b_size;
6689 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6690 * This buffer serves as a temporary holder of compressed data while
6691 * the buffer entry is being written to an l2arc device. Once that is
6692 * done, we can dispose of it.
6695 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6697 ASSERT(HDR_HAS_L2HDR(hdr));
6698 enum zio_compress comp = hdr->b_l2hdr.b_compress;
6700 ASSERT(HDR_HAS_L1HDR(hdr));
6701 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6703 if (comp == ZIO_COMPRESS_OFF) {
6705 * In this case, b_tmp_cdata points to the same buffer
6706 * as the arc_buf_t's b_data field. We don't want to
6707 * free it, since the arc_buf_t will handle that.
6709 hdr->b_l1hdr.b_tmp_cdata = NULL;
6710 } else if (comp == ZIO_COMPRESS_EMPTY) {
6712 * In this case, b_tmp_cdata was compressed to an empty
6713 * buffer, thus there's nothing to free and b_tmp_cdata
6714 * should have been set to NULL in l2arc_write_buffers().
6716 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6719 * If the data was compressed, then we've allocated a
6720 * temporary buffer for it, so now we need to release it.
6722 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6723 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6725 hdr->b_l1hdr.b_tmp_cdata = NULL;
6731 * This thread feeds the L2ARC at regular intervals. This is the beating
6732 * heart of the L2ARC.
6735 l2arc_feed_thread(void *dummy __unused)
6740 uint64_t size, wrote;
6741 clock_t begin, next = ddi_get_lbolt();
6742 boolean_t headroom_boost = B_FALSE;
6744 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6746 mutex_enter(&l2arc_feed_thr_lock);
6748 while (l2arc_thread_exit == 0) {
6749 CALLB_CPR_SAFE_BEGIN(&cpr);
6750 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6751 next - ddi_get_lbolt());
6752 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6753 next = ddi_get_lbolt() + hz;
6756 * Quick check for L2ARC devices.
6758 mutex_enter(&l2arc_dev_mtx);
6759 if (l2arc_ndev == 0) {
6760 mutex_exit(&l2arc_dev_mtx);
6763 mutex_exit(&l2arc_dev_mtx);
6764 begin = ddi_get_lbolt();
6767 * This selects the next l2arc device to write to, and in
6768 * doing so the next spa to feed from: dev->l2ad_spa. This
6769 * will return NULL if there are now no l2arc devices or if
6770 * they are all faulted.
6772 * If a device is returned, its spa's config lock is also
6773 * held to prevent device removal. l2arc_dev_get_next()
6774 * will grab and release l2arc_dev_mtx.
6776 if ((dev = l2arc_dev_get_next()) == NULL)
6779 spa = dev->l2ad_spa;
6780 ASSERT(spa != NULL);
6783 * If the pool is read-only then force the feed thread to
6784 * sleep a little longer.
6786 if (!spa_writeable(spa)) {
6787 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6788 spa_config_exit(spa, SCL_L2ARC, dev);
6793 * Avoid contributing to memory pressure.
6795 if (arc_reclaim_needed()) {
6796 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6797 spa_config_exit(spa, SCL_L2ARC, dev);
6801 ARCSTAT_BUMP(arcstat_l2_feeds);
6803 size = l2arc_write_size();
6806 * Evict L2ARC buffers that will be overwritten.
6808 l2arc_evict(dev, size, B_FALSE);
6811 * Write ARC buffers.
6813 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6816 * Calculate interval between writes.
6818 next = l2arc_write_interval(begin, size, wrote);
6819 spa_config_exit(spa, SCL_L2ARC, dev);
6822 l2arc_thread_exit = 0;
6823 cv_broadcast(&l2arc_feed_thr_cv);
6824 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6829 l2arc_vdev_present(vdev_t *vd)
6833 mutex_enter(&l2arc_dev_mtx);
6834 for (dev = list_head(l2arc_dev_list); dev != NULL;
6835 dev = list_next(l2arc_dev_list, dev)) {
6836 if (dev->l2ad_vdev == vd)
6839 mutex_exit(&l2arc_dev_mtx);
6841 return (dev != NULL);
6845 * Add a vdev for use by the L2ARC. By this point the spa has already
6846 * validated the vdev and opened it.
6849 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6851 l2arc_dev_t *adddev;
6853 ASSERT(!l2arc_vdev_present(vd));
6855 vdev_ashift_optimize(vd);
6858 * Create a new l2arc device entry.
6860 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6861 adddev->l2ad_spa = spa;
6862 adddev->l2ad_vdev = vd;
6863 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6864 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6865 adddev->l2ad_hand = adddev->l2ad_start;
6866 adddev->l2ad_first = B_TRUE;
6867 adddev->l2ad_writing = B_FALSE;
6869 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6871 * This is a list of all ARC buffers that are still valid on the
6874 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6875 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6877 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6878 refcount_create(&adddev->l2ad_alloc);
6881 * Add device to global list
6883 mutex_enter(&l2arc_dev_mtx);
6884 list_insert_head(l2arc_dev_list, adddev);
6885 atomic_inc_64(&l2arc_ndev);
6886 mutex_exit(&l2arc_dev_mtx);
6890 * Remove a vdev from the L2ARC.
6893 l2arc_remove_vdev(vdev_t *vd)
6895 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6898 * Find the device by vdev
6900 mutex_enter(&l2arc_dev_mtx);
6901 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6902 nextdev = list_next(l2arc_dev_list, dev);
6903 if (vd == dev->l2ad_vdev) {
6908 ASSERT(remdev != NULL);
6911 * Remove device from global list
6913 list_remove(l2arc_dev_list, remdev);
6914 l2arc_dev_last = NULL; /* may have been invalidated */
6915 atomic_dec_64(&l2arc_ndev);
6916 mutex_exit(&l2arc_dev_mtx);
6919 * Clear all buflists and ARC references. L2ARC device flush.
6921 l2arc_evict(remdev, 0, B_TRUE);
6922 list_destroy(&remdev->l2ad_buflist);
6923 mutex_destroy(&remdev->l2ad_mtx);
6924 refcount_destroy(&remdev->l2ad_alloc);
6925 kmem_free(remdev, sizeof (l2arc_dev_t));
6931 l2arc_thread_exit = 0;
6933 l2arc_writes_sent = 0;
6934 l2arc_writes_done = 0;
6936 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6937 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6938 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6939 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6941 l2arc_dev_list = &L2ARC_dev_list;
6942 l2arc_free_on_write = &L2ARC_free_on_write;
6943 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6944 offsetof(l2arc_dev_t, l2ad_node));
6945 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6946 offsetof(l2arc_data_free_t, l2df_list_node));
6953 * This is called from dmu_fini(), which is called from spa_fini();
6954 * Because of this, we can assume that all l2arc devices have
6955 * already been removed when the pools themselves were removed.
6958 l2arc_do_free_on_write();
6960 mutex_destroy(&l2arc_feed_thr_lock);
6961 cv_destroy(&l2arc_feed_thr_cv);
6962 mutex_destroy(&l2arc_dev_mtx);
6963 mutex_destroy(&l2arc_free_on_write_mtx);
6965 list_destroy(l2arc_dev_list);
6966 list_destroy(l2arc_free_on_write);
6972 if (!(spa_mode_global & FWRITE))
6975 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6976 TS_RUN, minclsyspri);
6982 if (!(spa_mode_global & FWRITE))
6985 mutex_enter(&l2arc_feed_thr_lock);
6986 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
6987 l2arc_thread_exit = 1;
6988 while (l2arc_thread_exit != 0)
6989 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6990 mutex_exit(&l2arc_feed_thr_lock);