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, 2014 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2014 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 mutexs, rather they rely on the
86 * hash table mutexs for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexs).
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 int 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.
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;
590 static arc_stats_t arc_stats = {
591 { "hits", KSTAT_DATA_UINT64 },
592 { "misses", KSTAT_DATA_UINT64 },
593 { "demand_data_hits", KSTAT_DATA_UINT64 },
594 { "demand_data_misses", KSTAT_DATA_UINT64 },
595 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
596 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
597 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
598 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
599 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
600 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
601 { "mru_hits", KSTAT_DATA_UINT64 },
602 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
603 { "mfu_hits", KSTAT_DATA_UINT64 },
604 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
605 { "allocated", KSTAT_DATA_UINT64 },
606 { "deleted", KSTAT_DATA_UINT64 },
607 { "mutex_miss", KSTAT_DATA_UINT64 },
608 { "evict_skip", KSTAT_DATA_UINT64 },
609 { "evict_not_enough", KSTAT_DATA_UINT64 },
610 { "evict_l2_cached", KSTAT_DATA_UINT64 },
611 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
612 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
613 { "evict_l2_skip", KSTAT_DATA_UINT64 },
614 { "hash_elements", KSTAT_DATA_UINT64 },
615 { "hash_elements_max", KSTAT_DATA_UINT64 },
616 { "hash_collisions", KSTAT_DATA_UINT64 },
617 { "hash_chains", KSTAT_DATA_UINT64 },
618 { "hash_chain_max", KSTAT_DATA_UINT64 },
619 { "p", KSTAT_DATA_UINT64 },
620 { "c", KSTAT_DATA_UINT64 },
621 { "c_min", KSTAT_DATA_UINT64 },
622 { "c_max", KSTAT_DATA_UINT64 },
623 { "size", KSTAT_DATA_UINT64 },
624 { "hdr_size", KSTAT_DATA_UINT64 },
625 { "data_size", KSTAT_DATA_UINT64 },
626 { "metadata_size", KSTAT_DATA_UINT64 },
627 { "other_size", KSTAT_DATA_UINT64 },
628 { "anon_size", KSTAT_DATA_UINT64 },
629 { "anon_evictable_data", KSTAT_DATA_UINT64 },
630 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
631 { "mru_size", KSTAT_DATA_UINT64 },
632 { "mru_evictable_data", KSTAT_DATA_UINT64 },
633 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
634 { "mru_ghost_size", KSTAT_DATA_UINT64 },
635 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
636 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
637 { "mfu_size", KSTAT_DATA_UINT64 },
638 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
639 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
640 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
641 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
642 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
643 { "l2_hits", KSTAT_DATA_UINT64 },
644 { "l2_misses", KSTAT_DATA_UINT64 },
645 { "l2_feeds", KSTAT_DATA_UINT64 },
646 { "l2_rw_clash", KSTAT_DATA_UINT64 },
647 { "l2_read_bytes", KSTAT_DATA_UINT64 },
648 { "l2_write_bytes", KSTAT_DATA_UINT64 },
649 { "l2_writes_sent", KSTAT_DATA_UINT64 },
650 { "l2_writes_done", KSTAT_DATA_UINT64 },
651 { "l2_writes_error", KSTAT_DATA_UINT64 },
652 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
653 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
654 { "l2_evict_reading", KSTAT_DATA_UINT64 },
655 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
656 { "l2_free_on_write", KSTAT_DATA_UINT64 },
657 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
658 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
659 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
660 { "l2_io_error", KSTAT_DATA_UINT64 },
661 { "l2_size", KSTAT_DATA_UINT64 },
662 { "l2_asize", KSTAT_DATA_UINT64 },
663 { "l2_hdr_size", KSTAT_DATA_UINT64 },
664 { "l2_compress_successes", KSTAT_DATA_UINT64 },
665 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
666 { "l2_compress_failures", KSTAT_DATA_UINT64 },
667 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
668 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
669 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
670 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
671 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
672 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
673 { "l2_write_full", KSTAT_DATA_UINT64 },
674 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
675 { "l2_write_pios", KSTAT_DATA_UINT64 },
676 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
677 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
678 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
679 { "memory_throttle_count", KSTAT_DATA_UINT64 },
680 { "duplicate_buffers", KSTAT_DATA_UINT64 },
681 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
682 { "duplicate_reads", KSTAT_DATA_UINT64 },
683 { "arc_meta_used", KSTAT_DATA_UINT64 },
684 { "arc_meta_limit", KSTAT_DATA_UINT64 },
685 { "arc_meta_max", KSTAT_DATA_UINT64 },
686 { "arc_meta_min", KSTAT_DATA_UINT64 }
689 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
691 #define ARCSTAT_INCR(stat, val) \
692 atomic_add_64(&arc_stats.stat.value.ui64, (val))
694 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
695 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
697 #define ARCSTAT_MAX(stat, val) { \
699 while ((val) > (m = arc_stats.stat.value.ui64) && \
700 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
704 #define ARCSTAT_MAXSTAT(stat) \
705 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
708 * We define a macro to allow ARC hits/misses to be easily broken down by
709 * two separate conditions, giving a total of four different subtypes for
710 * each of hits and misses (so eight statistics total).
712 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
715 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
717 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
721 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
723 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
728 static arc_state_t *arc_anon;
729 static arc_state_t *arc_mru;
730 static arc_state_t *arc_mru_ghost;
731 static arc_state_t *arc_mfu;
732 static arc_state_t *arc_mfu_ghost;
733 static arc_state_t *arc_l2c_only;
736 * There are several ARC variables that are critical to export as kstats --
737 * but we don't want to have to grovel around in the kstat whenever we wish to
738 * manipulate them. For these variables, we therefore define them to be in
739 * terms of the statistic variable. This assures that we are not introducing
740 * the possibility of inconsistency by having shadow copies of the variables,
741 * while still allowing the code to be readable.
743 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
744 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
745 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
746 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
747 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
748 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
749 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
750 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
751 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
753 #define L2ARC_IS_VALID_COMPRESS(_c_) \
754 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
756 static int arc_no_grow; /* Don't try to grow cache size */
757 static uint64_t arc_tempreserve;
758 static uint64_t arc_loaned_bytes;
760 typedef struct arc_callback arc_callback_t;
762 struct arc_callback {
764 arc_done_func_t *acb_done;
766 zio_t *acb_zio_dummy;
767 arc_callback_t *acb_next;
770 typedef struct arc_write_callback arc_write_callback_t;
772 struct arc_write_callback {
774 arc_done_func_t *awcb_ready;
775 arc_done_func_t *awcb_physdone;
776 arc_done_func_t *awcb_done;
781 * ARC buffers are separated into multiple structs as a memory saving measure:
782 * - Common fields struct, always defined, and embedded within it:
783 * - L2-only fields, always allocated but undefined when not in L2ARC
784 * - L1-only fields, only allocated when in L1ARC
786 * Buffer in L1 Buffer only in L2
787 * +------------------------+ +------------------------+
788 * | arc_buf_hdr_t | | arc_buf_hdr_t |
792 * +------------------------+ +------------------------+
793 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
794 * | (undefined if L1-only) | | |
795 * +------------------------+ +------------------------+
796 * | l1arc_buf_hdr_t |
801 * +------------------------+
803 * Because it's possible for the L2ARC to become extremely large, we can wind
804 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
805 * is minimized by only allocating the fields necessary for an L1-cached buffer
806 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
807 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
808 * words in pointers. arc_hdr_realloc() is used to switch a header between
809 * these two allocation states.
811 typedef struct l1arc_buf_hdr {
812 kmutex_t b_freeze_lock;
815 * used for debugging wtih kmem_flags - by allocating and freeing
816 * b_thawed when the buffer is thawed, we get a record of the stack
817 * trace that thawed it.
824 /* for waiting on writes to complete */
827 /* protected by arc state mutex */
828 arc_state_t *b_state;
829 multilist_node_t b_arc_node;
831 /* updated atomically */
832 clock_t b_arc_access;
834 /* self protecting */
837 arc_callback_t *b_acb;
838 /* temporary buffer holder for in-flight compressed data */
842 typedef struct l2arc_dev l2arc_dev_t;
844 typedef struct l2arc_buf_hdr {
845 /* protected by arc_buf_hdr mutex */
846 l2arc_dev_t *b_dev; /* L2ARC device */
847 uint64_t b_daddr; /* disk address, offset byte */
848 /* real alloc'd buffer size depending on b_compress applied */
851 list_node_t b_l2node;
855 /* protected by hash lock */
859 * Even though this checksum is only set/verified when a buffer is in
860 * the L1 cache, it needs to be in the set of common fields because it
861 * must be preserved from the time before a buffer is written out to
862 * L2ARC until after it is read back in.
864 zio_cksum_t *b_freeze_cksum;
866 arc_buf_hdr_t *b_hash_next;
873 /* L2ARC fields. Undefined when not in L2ARC. */
874 l2arc_buf_hdr_t b_l2hdr;
875 /* L1ARC fields. Undefined when in l2arc_only state */
876 l1arc_buf_hdr_t b_l1hdr;
881 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
886 val = arc_meta_limit;
887 err = sysctl_handle_64(oidp, &val, 0, req);
888 if (err != 0 || req->newptr == NULL)
891 if (val <= 0 || val > arc_c_max)
894 arc_meta_limit = val;
899 static arc_buf_t *arc_eviction_list;
900 static arc_buf_hdr_t arc_eviction_hdr;
902 #define GHOST_STATE(state) \
903 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
904 (state) == arc_l2c_only)
906 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
907 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
908 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
909 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
910 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
911 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
913 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
914 #define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
915 #define HDR_L2_READING(hdr) \
916 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
917 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
918 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
919 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
920 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
922 #define HDR_ISTYPE_METADATA(hdr) \
923 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
924 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
926 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
927 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
929 /* For storing compression mode in b_flags */
930 #define HDR_COMPRESS_OFFSET 24
931 #define HDR_COMPRESS_NBITS 7
933 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET(hdr->b_flags, \
934 HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS))
935 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET(hdr->b_flags, \
936 HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS, (cmp))
942 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
943 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
946 * Hash table routines
949 #define HT_LOCK_PAD CACHE_LINE_SIZE
954 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
958 #define BUF_LOCKS 256
959 typedef struct buf_hash_table {
961 arc_buf_hdr_t **ht_table;
962 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
965 static buf_hash_table_t buf_hash_table;
967 #define BUF_HASH_INDEX(spa, dva, birth) \
968 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
969 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
970 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
971 #define HDR_LOCK(hdr) \
972 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
974 uint64_t zfs_crc64_table[256];
980 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
981 #define L2ARC_HEADROOM 2 /* num of writes */
983 * If we discover during ARC scan any buffers to be compressed, we boost
984 * our headroom for the next scanning cycle by this percentage multiple.
986 #define L2ARC_HEADROOM_BOOST 200
987 #define L2ARC_FEED_SECS 1 /* caching interval secs */
988 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
991 * Used to distinguish headers that are being process by
992 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
993 * address. This can happen when the header is added to the l2arc's list
994 * of buffers to write in the first stage of l2arc_write_buffers(), but
995 * has not yet been written out which happens in the second stage of
996 * l2arc_write_buffers().
998 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
1000 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1001 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1003 /* L2ARC Performance Tunables */
1004 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1005 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1006 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1007 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1008 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1009 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1010 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1011 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1012 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1014 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1015 &l2arc_write_max, 0, "max write size");
1016 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1017 &l2arc_write_boost, 0, "extra write during warmup");
1018 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1019 &l2arc_headroom, 0, "number of dev writes");
1020 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1021 &l2arc_feed_secs, 0, "interval seconds");
1022 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1023 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1025 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1026 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1027 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1028 &l2arc_feed_again, 0, "turbo warmup");
1029 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1030 &l2arc_norw, 0, "no reads during writes");
1032 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1033 &ARC_anon.arcs_size, 0, "size of anonymous state");
1034 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1035 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1036 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1037 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1039 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1040 &ARC_mru.arcs_size, 0, "size of mru state");
1041 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1042 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1043 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1044 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1046 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1047 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
1048 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1049 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1050 "size of metadata in mru ghost state");
1051 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1052 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1053 "size of data in mru ghost state");
1055 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1056 &ARC_mfu.arcs_size, 0, "size of mfu state");
1057 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1058 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1059 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1060 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1062 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1063 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
1064 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1065 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1066 "size of metadata in mfu ghost state");
1067 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1068 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1069 "size of data in mfu ghost state");
1071 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1072 &ARC_l2c_only.arcs_size, 0, "size of mru state");
1078 vdev_t *l2ad_vdev; /* vdev */
1079 spa_t *l2ad_spa; /* spa */
1080 uint64_t l2ad_hand; /* next write location */
1081 uint64_t l2ad_start; /* first addr on device */
1082 uint64_t l2ad_end; /* last addr on device */
1083 boolean_t l2ad_first; /* first sweep through */
1084 boolean_t l2ad_writing; /* currently writing */
1085 kmutex_t l2ad_mtx; /* lock for buffer list */
1086 list_t l2ad_buflist; /* buffer list */
1087 list_node_t l2ad_node; /* device list node */
1088 refcount_t l2ad_alloc; /* allocated bytes */
1091 static list_t L2ARC_dev_list; /* device list */
1092 static list_t *l2arc_dev_list; /* device list pointer */
1093 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1094 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1095 static list_t L2ARC_free_on_write; /* free after write buf list */
1096 static list_t *l2arc_free_on_write; /* free after write list ptr */
1097 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1098 static uint64_t l2arc_ndev; /* number of devices */
1100 typedef struct l2arc_read_callback {
1101 arc_buf_t *l2rcb_buf; /* read buffer */
1102 spa_t *l2rcb_spa; /* spa */
1103 blkptr_t l2rcb_bp; /* original blkptr */
1104 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1105 int l2rcb_flags; /* original flags */
1106 enum zio_compress l2rcb_compress; /* applied compress */
1107 } l2arc_read_callback_t;
1109 typedef struct l2arc_write_callback {
1110 l2arc_dev_t *l2wcb_dev; /* device info */
1111 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1112 } l2arc_write_callback_t;
1114 typedef struct l2arc_data_free {
1115 /* protected by l2arc_free_on_write_mtx */
1118 void (*l2df_func)(void *, size_t);
1119 list_node_t l2df_list_node;
1120 } l2arc_data_free_t;
1122 static kmutex_t l2arc_feed_thr_lock;
1123 static kcondvar_t l2arc_feed_thr_cv;
1124 static uint8_t l2arc_thread_exit;
1126 static void arc_get_data_buf(arc_buf_t *);
1127 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1128 static boolean_t arc_is_overflowing();
1129 static void arc_buf_watch(arc_buf_t *);
1131 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1132 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1134 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1135 static void l2arc_read_done(zio_t *);
1137 static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
1138 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1139 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1142 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1144 uint8_t *vdva = (uint8_t *)dva;
1145 uint64_t crc = -1ULL;
1148 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1150 for (i = 0; i < sizeof (dva_t); i++)
1151 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1153 crc ^= (spa>>8) ^ birth;
1158 #define BUF_EMPTY(buf) \
1159 ((buf)->b_dva.dva_word[0] == 0 && \
1160 (buf)->b_dva.dva_word[1] == 0)
1162 #define BUF_EQUAL(spa, dva, birth, buf) \
1163 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1164 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1165 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1168 buf_discard_identity(arc_buf_hdr_t *hdr)
1170 hdr->b_dva.dva_word[0] = 0;
1171 hdr->b_dva.dva_word[1] = 0;
1175 static arc_buf_hdr_t *
1176 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1178 const dva_t *dva = BP_IDENTITY(bp);
1179 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1180 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1181 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1184 mutex_enter(hash_lock);
1185 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1186 hdr = hdr->b_hash_next) {
1187 if (BUF_EQUAL(spa, dva, birth, hdr)) {
1192 mutex_exit(hash_lock);
1198 * Insert an entry into the hash table. If there is already an element
1199 * equal to elem in the hash table, then the already existing element
1200 * will be returned and the new element will not be inserted.
1201 * Otherwise returns NULL.
1202 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1204 static arc_buf_hdr_t *
1205 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1207 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1208 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1209 arc_buf_hdr_t *fhdr;
1212 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1213 ASSERT(hdr->b_birth != 0);
1214 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1216 if (lockp != NULL) {
1218 mutex_enter(hash_lock);
1220 ASSERT(MUTEX_HELD(hash_lock));
1223 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1224 fhdr = fhdr->b_hash_next, i++) {
1225 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1229 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1230 buf_hash_table.ht_table[idx] = hdr;
1231 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1233 /* collect some hash table performance data */
1235 ARCSTAT_BUMP(arcstat_hash_collisions);
1237 ARCSTAT_BUMP(arcstat_hash_chains);
1239 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1242 ARCSTAT_BUMP(arcstat_hash_elements);
1243 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1249 buf_hash_remove(arc_buf_hdr_t *hdr)
1251 arc_buf_hdr_t *fhdr, **hdrp;
1252 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1254 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1255 ASSERT(HDR_IN_HASH_TABLE(hdr));
1257 hdrp = &buf_hash_table.ht_table[idx];
1258 while ((fhdr = *hdrp) != hdr) {
1259 ASSERT(fhdr != NULL);
1260 hdrp = &fhdr->b_hash_next;
1262 *hdrp = hdr->b_hash_next;
1263 hdr->b_hash_next = NULL;
1264 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1266 /* collect some hash table performance data */
1267 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1269 if (buf_hash_table.ht_table[idx] &&
1270 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1271 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1275 * Global data structures and functions for the buf kmem cache.
1277 static kmem_cache_t *hdr_full_cache;
1278 static kmem_cache_t *hdr_l2only_cache;
1279 static kmem_cache_t *buf_cache;
1286 kmem_free(buf_hash_table.ht_table,
1287 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1288 for (i = 0; i < BUF_LOCKS; i++)
1289 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1290 kmem_cache_destroy(hdr_full_cache);
1291 kmem_cache_destroy(hdr_l2only_cache);
1292 kmem_cache_destroy(buf_cache);
1296 * Constructor callback - called when the cache is empty
1297 * and a new buf is requested.
1301 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1303 arc_buf_hdr_t *hdr = vbuf;
1305 bzero(hdr, HDR_FULL_SIZE);
1306 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1307 refcount_create(&hdr->b_l1hdr.b_refcnt);
1308 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1309 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1310 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1317 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1319 arc_buf_hdr_t *hdr = vbuf;
1321 bzero(hdr, HDR_L2ONLY_SIZE);
1322 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1329 buf_cons(void *vbuf, void *unused, int kmflag)
1331 arc_buf_t *buf = vbuf;
1333 bzero(buf, sizeof (arc_buf_t));
1334 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1335 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1341 * Destructor callback - called when a cached buf is
1342 * no longer required.
1346 hdr_full_dest(void *vbuf, void *unused)
1348 arc_buf_hdr_t *hdr = vbuf;
1350 ASSERT(BUF_EMPTY(hdr));
1351 cv_destroy(&hdr->b_l1hdr.b_cv);
1352 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1353 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1354 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1355 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1360 hdr_l2only_dest(void *vbuf, void *unused)
1362 arc_buf_hdr_t *hdr = vbuf;
1364 ASSERT(BUF_EMPTY(hdr));
1365 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1370 buf_dest(void *vbuf, void *unused)
1372 arc_buf_t *buf = vbuf;
1374 mutex_destroy(&buf->b_evict_lock);
1375 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1379 * Reclaim callback -- invoked when memory is low.
1383 hdr_recl(void *unused)
1385 dprintf("hdr_recl called\n");
1387 * umem calls the reclaim func when we destroy the buf cache,
1388 * which is after we do arc_fini().
1391 cv_signal(&arc_reclaim_thread_cv);
1398 uint64_t hsize = 1ULL << 12;
1402 * The hash table is big enough to fill all of physical memory
1403 * with an average block size of zfs_arc_average_blocksize (default 8K).
1404 * By default, the table will take up
1405 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1407 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1410 buf_hash_table.ht_mask = hsize - 1;
1411 buf_hash_table.ht_table =
1412 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1413 if (buf_hash_table.ht_table == NULL) {
1414 ASSERT(hsize > (1ULL << 8));
1419 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1420 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1421 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1422 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1424 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1425 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1427 for (i = 0; i < 256; i++)
1428 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1429 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1431 for (i = 0; i < BUF_LOCKS; i++) {
1432 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1433 NULL, MUTEX_DEFAULT, NULL);
1438 * Transition between the two allocation states for the arc_buf_hdr struct.
1439 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1440 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1441 * version is used when a cache buffer is only in the L2ARC in order to reduce
1444 static arc_buf_hdr_t *
1445 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1447 ASSERT(HDR_HAS_L2HDR(hdr));
1449 arc_buf_hdr_t *nhdr;
1450 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1452 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1453 (old == hdr_l2only_cache && new == hdr_full_cache));
1455 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1457 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1458 buf_hash_remove(hdr);
1460 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1462 if (new == hdr_full_cache) {
1463 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1465 * arc_access and arc_change_state need to be aware that a
1466 * header has just come out of L2ARC, so we set its state to
1467 * l2c_only even though it's about to change.
1469 nhdr->b_l1hdr.b_state = arc_l2c_only;
1471 /* Verify previous threads set to NULL before freeing */
1472 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1474 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1475 ASSERT0(hdr->b_l1hdr.b_datacnt);
1478 * If we've reached here, We must have been called from
1479 * arc_evict_hdr(), as such we should have already been
1480 * removed from any ghost list we were previously on
1481 * (which protects us from racing with arc_evict_state),
1482 * thus no locking is needed during this check.
1484 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1487 * A buffer must not be moved into the arc_l2c_only
1488 * state if it's not finished being written out to the
1489 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1490 * might try to be accessed, even though it was removed.
1492 VERIFY(!HDR_L2_WRITING(hdr));
1493 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1495 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1498 * The header has been reallocated so we need to re-insert it into any
1501 (void) buf_hash_insert(nhdr, NULL);
1503 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1505 mutex_enter(&dev->l2ad_mtx);
1508 * We must place the realloc'ed header back into the list at
1509 * the same spot. Otherwise, if it's placed earlier in the list,
1510 * l2arc_write_buffers() could find it during the function's
1511 * write phase, and try to write it out to the l2arc.
1513 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1514 list_remove(&dev->l2ad_buflist, hdr);
1516 mutex_exit(&dev->l2ad_mtx);
1519 * Since we're using the pointer address as the tag when
1520 * incrementing and decrementing the l2ad_alloc refcount, we
1521 * must remove the old pointer (that we're about to destroy) and
1522 * add the new pointer to the refcount. Otherwise we'd remove
1523 * the wrong pointer address when calling arc_hdr_destroy() later.
1526 (void) refcount_remove_many(&dev->l2ad_alloc,
1527 hdr->b_l2hdr.b_asize, hdr);
1529 (void) refcount_add_many(&dev->l2ad_alloc,
1530 nhdr->b_l2hdr.b_asize, nhdr);
1532 buf_discard_identity(hdr);
1533 hdr->b_freeze_cksum = NULL;
1534 kmem_cache_free(old, hdr);
1540 #define ARC_MINTIME (hz>>4) /* 62 ms */
1543 arc_cksum_verify(arc_buf_t *buf)
1547 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1550 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1551 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1552 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1555 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1556 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1557 panic("buffer modified while frozen!");
1558 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1562 arc_cksum_equal(arc_buf_t *buf)
1567 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1568 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1569 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1570 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1576 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1578 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1581 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1582 if (buf->b_hdr->b_freeze_cksum != NULL) {
1583 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1586 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1587 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1588 buf->b_hdr->b_freeze_cksum);
1589 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1592 #endif /* illumos */
1597 typedef struct procctl {
1605 arc_buf_unwatch(arc_buf_t *buf)
1612 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1613 ctl.prwatch.pr_size = 0;
1614 ctl.prwatch.pr_wflags = 0;
1615 result = write(arc_procfd, &ctl, sizeof (ctl));
1616 ASSERT3U(result, ==, sizeof (ctl));
1623 arc_buf_watch(arc_buf_t *buf)
1630 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1631 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1632 ctl.prwatch.pr_wflags = WA_WRITE;
1633 result = write(arc_procfd, &ctl, sizeof (ctl));
1634 ASSERT3U(result, ==, sizeof (ctl));
1638 #endif /* illumos */
1640 static arc_buf_contents_t
1641 arc_buf_type(arc_buf_hdr_t *hdr)
1643 if (HDR_ISTYPE_METADATA(hdr)) {
1644 return (ARC_BUFC_METADATA);
1646 return (ARC_BUFC_DATA);
1651 arc_bufc_to_flags(arc_buf_contents_t type)
1655 /* metadata field is 0 if buffer contains normal data */
1657 case ARC_BUFC_METADATA:
1658 return (ARC_FLAG_BUFC_METADATA);
1662 panic("undefined ARC buffer type!");
1663 return ((uint32_t)-1);
1667 arc_buf_thaw(arc_buf_t *buf)
1669 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1670 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1671 panic("modifying non-anon buffer!");
1672 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1673 panic("modifying buffer while i/o in progress!");
1674 arc_cksum_verify(buf);
1677 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1678 if (buf->b_hdr->b_freeze_cksum != NULL) {
1679 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1680 buf->b_hdr->b_freeze_cksum = NULL;
1684 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1685 if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1686 kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1687 buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1691 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1694 arc_buf_unwatch(buf);
1695 #endif /* illumos */
1699 arc_buf_freeze(arc_buf_t *buf)
1701 kmutex_t *hash_lock;
1703 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1706 hash_lock = HDR_LOCK(buf->b_hdr);
1707 mutex_enter(hash_lock);
1709 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1710 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1711 arc_cksum_compute(buf, B_FALSE);
1712 mutex_exit(hash_lock);
1717 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1719 ASSERT(HDR_HAS_L1HDR(hdr));
1720 ASSERT(MUTEX_HELD(hash_lock));
1721 arc_state_t *state = hdr->b_l1hdr.b_state;
1723 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1724 (state != arc_anon)) {
1725 /* We don't use the L2-only state list. */
1726 if (state != arc_l2c_only) {
1727 arc_buf_contents_t type = arc_buf_type(hdr);
1728 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1729 multilist_t *list = &state->arcs_list[type];
1730 uint64_t *size = &state->arcs_lsize[type];
1732 multilist_remove(list, hdr);
1734 if (GHOST_STATE(state)) {
1735 ASSERT0(hdr->b_l1hdr.b_datacnt);
1736 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1737 delta = hdr->b_size;
1740 ASSERT3U(*size, >=, delta);
1741 atomic_add_64(size, -delta);
1743 /* remove the prefetch flag if we get a reference */
1744 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1749 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1752 arc_state_t *state = hdr->b_l1hdr.b_state;
1754 ASSERT(HDR_HAS_L1HDR(hdr));
1755 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1756 ASSERT(!GHOST_STATE(state));
1759 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1760 * check to prevent usage of the arc_l2c_only list.
1762 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1763 (state != arc_anon)) {
1764 arc_buf_contents_t type = arc_buf_type(hdr);
1765 multilist_t *list = &state->arcs_list[type];
1766 uint64_t *size = &state->arcs_lsize[type];
1768 multilist_insert(list, hdr);
1770 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1771 atomic_add_64(size, hdr->b_size *
1772 hdr->b_l1hdr.b_datacnt);
1778 * Move the supplied buffer to the indicated state. The hash lock
1779 * for the buffer must be held by the caller.
1782 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1783 kmutex_t *hash_lock)
1785 arc_state_t *old_state;
1788 uint64_t from_delta, to_delta;
1789 arc_buf_contents_t buftype = arc_buf_type(hdr);
1792 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1793 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1794 * L1 hdr doesn't always exist when we change state to arc_anon before
1795 * destroying a header, in which case reallocating to add the L1 hdr is
1798 if (HDR_HAS_L1HDR(hdr)) {
1799 old_state = hdr->b_l1hdr.b_state;
1800 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1801 datacnt = hdr->b_l1hdr.b_datacnt;
1803 old_state = arc_l2c_only;
1808 ASSERT(MUTEX_HELD(hash_lock));
1809 ASSERT3P(new_state, !=, old_state);
1810 ASSERT(refcnt == 0 || datacnt > 0);
1811 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1812 ASSERT(old_state != arc_anon || datacnt <= 1);
1814 from_delta = to_delta = datacnt * hdr->b_size;
1817 * If this buffer is evictable, transfer it from the
1818 * old state list to the new state list.
1821 if (old_state != arc_anon && old_state != arc_l2c_only) {
1822 uint64_t *size = &old_state->arcs_lsize[buftype];
1824 ASSERT(HDR_HAS_L1HDR(hdr));
1825 multilist_remove(&old_state->arcs_list[buftype], hdr);
1828 * If prefetching out of the ghost cache,
1829 * we will have a non-zero datacnt.
1831 if (GHOST_STATE(old_state) && datacnt == 0) {
1832 /* ghost elements have a ghost size */
1833 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1834 from_delta = hdr->b_size;
1836 ASSERT3U(*size, >=, from_delta);
1837 atomic_add_64(size, -from_delta);
1839 if (new_state != arc_anon && new_state != arc_l2c_only) {
1840 uint64_t *size = &new_state->arcs_lsize[buftype];
1843 * An L1 header always exists here, since if we're
1844 * moving to some L1-cached state (i.e. not l2c_only or
1845 * anonymous), we realloc the header to add an L1hdr
1848 ASSERT(HDR_HAS_L1HDR(hdr));
1849 multilist_insert(&new_state->arcs_list[buftype], hdr);
1851 /* ghost elements have a ghost size */
1852 if (GHOST_STATE(new_state)) {
1854 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1855 to_delta = hdr->b_size;
1857 atomic_add_64(size, to_delta);
1861 ASSERT(!BUF_EMPTY(hdr));
1862 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1863 buf_hash_remove(hdr);
1865 /* adjust state sizes (ignore arc_l2c_only) */
1866 if (to_delta && new_state != arc_l2c_only)
1867 atomic_add_64(&new_state->arcs_size, to_delta);
1868 if (from_delta && old_state != arc_l2c_only) {
1869 ASSERT3U(old_state->arcs_size, >=, from_delta);
1870 atomic_add_64(&old_state->arcs_size, -from_delta);
1872 if (HDR_HAS_L1HDR(hdr))
1873 hdr->b_l1hdr.b_state = new_state;
1876 * L2 headers should never be on the L2 state list since they don't
1877 * have L1 headers allocated.
1879 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1880 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1884 arc_space_consume(uint64_t space, arc_space_type_t type)
1886 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1889 case ARC_SPACE_DATA:
1890 ARCSTAT_INCR(arcstat_data_size, space);
1892 case ARC_SPACE_META:
1893 ARCSTAT_INCR(arcstat_metadata_size, space);
1895 case ARC_SPACE_OTHER:
1896 ARCSTAT_INCR(arcstat_other_size, space);
1898 case ARC_SPACE_HDRS:
1899 ARCSTAT_INCR(arcstat_hdr_size, space);
1901 case ARC_SPACE_L2HDRS:
1902 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1906 if (type != ARC_SPACE_DATA)
1907 ARCSTAT_INCR(arcstat_meta_used, space);
1909 atomic_add_64(&arc_size, space);
1913 arc_space_return(uint64_t space, arc_space_type_t type)
1915 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1918 case ARC_SPACE_DATA:
1919 ARCSTAT_INCR(arcstat_data_size, -space);
1921 case ARC_SPACE_META:
1922 ARCSTAT_INCR(arcstat_metadata_size, -space);
1924 case ARC_SPACE_OTHER:
1925 ARCSTAT_INCR(arcstat_other_size, -space);
1927 case ARC_SPACE_HDRS:
1928 ARCSTAT_INCR(arcstat_hdr_size, -space);
1930 case ARC_SPACE_L2HDRS:
1931 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1935 if (type != ARC_SPACE_DATA) {
1936 ASSERT(arc_meta_used >= space);
1937 if (arc_meta_max < arc_meta_used)
1938 arc_meta_max = arc_meta_used;
1939 ARCSTAT_INCR(arcstat_meta_used, -space);
1942 ASSERT(arc_size >= space);
1943 atomic_add_64(&arc_size, -space);
1947 arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
1952 ASSERT3U(size, >, 0);
1953 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
1954 ASSERT(BUF_EMPTY(hdr));
1955 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
1957 hdr->b_spa = spa_load_guid(spa);
1959 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1962 buf->b_efunc = NULL;
1963 buf->b_private = NULL;
1966 hdr->b_flags = arc_bufc_to_flags(type);
1967 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1969 hdr->b_l1hdr.b_buf = buf;
1970 hdr->b_l1hdr.b_state = arc_anon;
1971 hdr->b_l1hdr.b_arc_access = 0;
1972 hdr->b_l1hdr.b_datacnt = 1;
1973 hdr->b_l1hdr.b_tmp_cdata = NULL;
1975 arc_get_data_buf(buf);
1976 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
1977 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1982 static char *arc_onloan_tag = "onloan";
1985 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1986 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1987 * buffers must be returned to the arc before they can be used by the DMU or
1991 arc_loan_buf(spa_t *spa, int size)
1995 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1997 atomic_add_64(&arc_loaned_bytes, size);
2002 * Return a loaned arc buffer to the arc.
2005 arc_return_buf(arc_buf_t *buf, void *tag)
2007 arc_buf_hdr_t *hdr = buf->b_hdr;
2009 ASSERT(buf->b_data != NULL);
2010 ASSERT(HDR_HAS_L1HDR(hdr));
2011 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2012 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2014 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2017 /* Detach an arc_buf from a dbuf (tag) */
2019 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2021 arc_buf_hdr_t *hdr = buf->b_hdr;
2023 ASSERT(buf->b_data != NULL);
2024 ASSERT(HDR_HAS_L1HDR(hdr));
2025 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2026 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2027 buf->b_efunc = NULL;
2028 buf->b_private = NULL;
2030 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2034 arc_buf_clone(arc_buf_t *from)
2037 arc_buf_hdr_t *hdr = from->b_hdr;
2038 uint64_t size = hdr->b_size;
2040 ASSERT(HDR_HAS_L1HDR(hdr));
2041 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2043 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2046 buf->b_efunc = NULL;
2047 buf->b_private = NULL;
2048 buf->b_next = hdr->b_l1hdr.b_buf;
2049 hdr->b_l1hdr.b_buf = buf;
2050 arc_get_data_buf(buf);
2051 bcopy(from->b_data, buf->b_data, size);
2054 * This buffer already exists in the arc so create a duplicate
2055 * copy for the caller. If the buffer is associated with user data
2056 * then track the size and number of duplicates. These stats will be
2057 * updated as duplicate buffers are created and destroyed.
2059 if (HDR_ISTYPE_DATA(hdr)) {
2060 ARCSTAT_BUMP(arcstat_duplicate_buffers);
2061 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2063 hdr->b_l1hdr.b_datacnt += 1;
2068 arc_buf_add_ref(arc_buf_t *buf, void* tag)
2071 kmutex_t *hash_lock;
2074 * Check to see if this buffer is evicted. Callers
2075 * must verify b_data != NULL to know if the add_ref
2078 mutex_enter(&buf->b_evict_lock);
2079 if (buf->b_data == NULL) {
2080 mutex_exit(&buf->b_evict_lock);
2083 hash_lock = HDR_LOCK(buf->b_hdr);
2084 mutex_enter(hash_lock);
2086 ASSERT(HDR_HAS_L1HDR(hdr));
2087 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2088 mutex_exit(&buf->b_evict_lock);
2090 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2091 hdr->b_l1hdr.b_state == arc_mfu);
2093 add_reference(hdr, hash_lock, tag);
2094 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2095 arc_access(hdr, hash_lock);
2096 mutex_exit(hash_lock);
2097 ARCSTAT_BUMP(arcstat_hits);
2098 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2099 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2100 data, metadata, hits);
2104 arc_buf_free_on_write(void *data, size_t size,
2105 void (*free_func)(void *, size_t))
2107 l2arc_data_free_t *df;
2109 df = kmem_alloc(sizeof (*df), KM_SLEEP);
2110 df->l2df_data = data;
2111 df->l2df_size = size;
2112 df->l2df_func = free_func;
2113 mutex_enter(&l2arc_free_on_write_mtx);
2114 list_insert_head(l2arc_free_on_write, df);
2115 mutex_exit(&l2arc_free_on_write_mtx);
2119 * Free the arc data buffer. If it is an l2arc write in progress,
2120 * the buffer is placed on l2arc_free_on_write to be freed later.
2123 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2125 arc_buf_hdr_t *hdr = buf->b_hdr;
2127 if (HDR_L2_WRITING(hdr)) {
2128 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2129 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2131 free_func(buf->b_data, hdr->b_size);
2136 * Free up buf->b_data and if 'remove' is set, then pull the
2137 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2140 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2142 ASSERT(HDR_HAS_L2HDR(hdr));
2143 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2146 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2147 * that doesn't exist, the header is in the arc_l2c_only state,
2148 * and there isn't anything to free (it's already been freed).
2150 if (!HDR_HAS_L1HDR(hdr))
2154 * The header isn't being written to the l2arc device, thus it
2155 * shouldn't have a b_tmp_cdata to free.
2157 if (!HDR_L2_WRITING(hdr)) {
2158 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2163 * The header does not have compression enabled. This can be due
2164 * to the buffer not being compressible, or because we're
2165 * freeing the buffer before the second phase of
2166 * l2arc_write_buffer() has started (which does the compression
2167 * step). In either case, b_tmp_cdata does not point to a
2168 * separately compressed buffer, so there's nothing to free (it
2169 * points to the same buffer as the arc_buf_t's b_data field).
2171 if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) {
2172 hdr->b_l1hdr.b_tmp_cdata = NULL;
2177 * There's nothing to free since the buffer was all zero's and
2178 * compressed to a zero length buffer.
2180 if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_EMPTY) {
2181 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2185 ASSERT(L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)));
2187 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
2188 hdr->b_size, zio_data_buf_free);
2190 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2191 hdr->b_l1hdr.b_tmp_cdata = NULL;
2195 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2199 /* free up data associated with the buf */
2200 if (buf->b_data != NULL) {
2201 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2202 uint64_t size = buf->b_hdr->b_size;
2203 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2205 arc_cksum_verify(buf);
2207 arc_buf_unwatch(buf);
2208 #endif /* illumos */
2210 if (type == ARC_BUFC_METADATA) {
2211 arc_buf_data_free(buf, zio_buf_free);
2212 arc_space_return(size, ARC_SPACE_META);
2214 ASSERT(type == ARC_BUFC_DATA);
2215 arc_buf_data_free(buf, zio_data_buf_free);
2216 arc_space_return(size, ARC_SPACE_DATA);
2219 /* protected by hash lock, if in the hash table */
2220 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2221 uint64_t *cnt = &state->arcs_lsize[type];
2223 ASSERT(refcount_is_zero(
2224 &buf->b_hdr->b_l1hdr.b_refcnt));
2225 ASSERT(state != arc_anon && state != arc_l2c_only);
2227 ASSERT3U(*cnt, >=, size);
2228 atomic_add_64(cnt, -size);
2230 ASSERT3U(state->arcs_size, >=, size);
2231 atomic_add_64(&state->arcs_size, -size);
2235 * If we're destroying a duplicate buffer make sure
2236 * that the appropriate statistics are updated.
2238 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2239 HDR_ISTYPE_DATA(buf->b_hdr)) {
2240 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2241 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2243 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2244 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2247 /* only remove the buf if requested */
2251 /* remove the buf from the hdr list */
2252 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2253 bufp = &(*bufp)->b_next)
2255 *bufp = buf->b_next;
2258 ASSERT(buf->b_efunc == NULL);
2260 /* clean up the buf */
2262 kmem_cache_free(buf_cache, buf);
2266 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2268 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2269 l2arc_dev_t *dev = l2hdr->b_dev;
2271 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2272 ASSERT(HDR_HAS_L2HDR(hdr));
2274 list_remove(&dev->l2ad_buflist, hdr);
2277 * We don't want to leak the b_tmp_cdata buffer that was
2278 * allocated in l2arc_write_buffers()
2280 arc_buf_l2_cdata_free(hdr);
2283 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2284 * this header is being processed by l2arc_write_buffers() (i.e.
2285 * it's in the first stage of l2arc_write_buffers()).
2286 * Re-affirming that truth here, just to serve as a reminder. If
2287 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2288 * may not have its HDR_L2_WRITING flag set. (the write may have
2289 * completed, in which case HDR_L2_WRITING will be false and the
2290 * b_daddr field will point to the address of the buffer on disk).
2292 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2295 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2296 * l2arc_write_buffers(). Since we've just removed this header
2297 * from the l2arc buffer list, this header will never reach the
2298 * second stage of l2arc_write_buffers(), which increments the
2299 * accounting stats for this header. Thus, we must be careful
2300 * not to decrement them for this header either.
2302 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2303 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2304 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2306 vdev_space_update(dev->l2ad_vdev,
2307 -l2hdr->b_asize, 0, 0);
2309 (void) refcount_remove_many(&dev->l2ad_alloc,
2310 l2hdr->b_asize, hdr);
2313 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2317 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2319 if (HDR_HAS_L1HDR(hdr)) {
2320 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2321 hdr->b_l1hdr.b_datacnt > 0);
2322 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2323 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2325 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2326 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2328 if (HDR_HAS_L2HDR(hdr)) {
2329 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2330 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2333 mutex_enter(&dev->l2ad_mtx);
2336 * Even though we checked this conditional above, we
2337 * need to check this again now that we have the
2338 * l2ad_mtx. This is because we could be racing with
2339 * another thread calling l2arc_evict() which might have
2340 * destroyed this header's L2 portion as we were waiting
2341 * to acquire the l2ad_mtx. If that happens, we don't
2342 * want to re-destroy the header's L2 portion.
2344 if (HDR_HAS_L2HDR(hdr)) {
2345 if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
2346 trim_map_free(dev->l2ad_vdev,
2347 hdr->b_l2hdr.b_daddr,
2348 hdr->b_l2hdr.b_asize, 0);
2349 arc_hdr_l2hdr_destroy(hdr);
2353 mutex_exit(&dev->l2ad_mtx);
2356 if (!BUF_EMPTY(hdr))
2357 buf_discard_identity(hdr);
2358 if (hdr->b_freeze_cksum != NULL) {
2359 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2360 hdr->b_freeze_cksum = NULL;
2363 if (HDR_HAS_L1HDR(hdr)) {
2364 while (hdr->b_l1hdr.b_buf) {
2365 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2367 if (buf->b_efunc != NULL) {
2368 mutex_enter(&arc_user_evicts_lock);
2369 mutex_enter(&buf->b_evict_lock);
2370 ASSERT(buf->b_hdr != NULL);
2371 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2372 hdr->b_l1hdr.b_buf = buf->b_next;
2373 buf->b_hdr = &arc_eviction_hdr;
2374 buf->b_next = arc_eviction_list;
2375 arc_eviction_list = buf;
2376 mutex_exit(&buf->b_evict_lock);
2377 cv_signal(&arc_user_evicts_cv);
2378 mutex_exit(&arc_user_evicts_lock);
2380 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2384 if (hdr->b_l1hdr.b_thawed != NULL) {
2385 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2386 hdr->b_l1hdr.b_thawed = NULL;
2391 ASSERT3P(hdr->b_hash_next, ==, NULL);
2392 if (HDR_HAS_L1HDR(hdr)) {
2393 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2394 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2395 kmem_cache_free(hdr_full_cache, hdr);
2397 kmem_cache_free(hdr_l2only_cache, hdr);
2402 arc_buf_free(arc_buf_t *buf, void *tag)
2404 arc_buf_hdr_t *hdr = buf->b_hdr;
2405 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2407 ASSERT(buf->b_efunc == NULL);
2408 ASSERT(buf->b_data != NULL);
2411 kmutex_t *hash_lock = HDR_LOCK(hdr);
2413 mutex_enter(hash_lock);
2415 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2417 (void) remove_reference(hdr, hash_lock, tag);
2418 if (hdr->b_l1hdr.b_datacnt > 1) {
2419 arc_buf_destroy(buf, TRUE);
2421 ASSERT(buf == hdr->b_l1hdr.b_buf);
2422 ASSERT(buf->b_efunc == NULL);
2423 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2425 mutex_exit(hash_lock);
2426 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2429 * We are in the middle of an async write. Don't destroy
2430 * this buffer unless the write completes before we finish
2431 * decrementing the reference count.
2433 mutex_enter(&arc_user_evicts_lock);
2434 (void) remove_reference(hdr, NULL, tag);
2435 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2436 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2437 mutex_exit(&arc_user_evicts_lock);
2439 arc_hdr_destroy(hdr);
2441 if (remove_reference(hdr, NULL, tag) > 0)
2442 arc_buf_destroy(buf, TRUE);
2444 arc_hdr_destroy(hdr);
2449 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2451 arc_buf_hdr_t *hdr = buf->b_hdr;
2452 kmutex_t *hash_lock = HDR_LOCK(hdr);
2453 boolean_t no_callback = (buf->b_efunc == NULL);
2455 if (hdr->b_l1hdr.b_state == arc_anon) {
2456 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2457 arc_buf_free(buf, tag);
2458 return (no_callback);
2461 mutex_enter(hash_lock);
2463 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2464 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2465 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2466 ASSERT(buf->b_data != NULL);
2468 (void) remove_reference(hdr, hash_lock, tag);
2469 if (hdr->b_l1hdr.b_datacnt > 1) {
2471 arc_buf_destroy(buf, TRUE);
2472 } else if (no_callback) {
2473 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2474 ASSERT(buf->b_efunc == NULL);
2475 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2477 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2478 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2479 mutex_exit(hash_lock);
2480 return (no_callback);
2484 arc_buf_size(arc_buf_t *buf)
2486 return (buf->b_hdr->b_size);
2490 * Called from the DMU to determine if the current buffer should be
2491 * evicted. In order to ensure proper locking, the eviction must be initiated
2492 * from the DMU. Return true if the buffer is associated with user data and
2493 * duplicate buffers still exist.
2496 arc_buf_eviction_needed(arc_buf_t *buf)
2499 boolean_t evict_needed = B_FALSE;
2501 if (zfs_disable_dup_eviction)
2504 mutex_enter(&buf->b_evict_lock);
2508 * We are in arc_do_user_evicts(); let that function
2509 * perform the eviction.
2511 ASSERT(buf->b_data == NULL);
2512 mutex_exit(&buf->b_evict_lock);
2514 } else if (buf->b_data == NULL) {
2516 * We have already been added to the arc eviction list;
2517 * recommend eviction.
2519 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2520 mutex_exit(&buf->b_evict_lock);
2524 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2525 evict_needed = B_TRUE;
2527 mutex_exit(&buf->b_evict_lock);
2528 return (evict_needed);
2532 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2533 * state of the header is dependent on it's state prior to entering this
2534 * function. The following transitions are possible:
2536 * - arc_mru -> arc_mru_ghost
2537 * - arc_mfu -> arc_mfu_ghost
2538 * - arc_mru_ghost -> arc_l2c_only
2539 * - arc_mru_ghost -> deleted
2540 * - arc_mfu_ghost -> arc_l2c_only
2541 * - arc_mfu_ghost -> deleted
2544 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2546 arc_state_t *evicted_state, *state;
2547 int64_t bytes_evicted = 0;
2549 ASSERT(MUTEX_HELD(hash_lock));
2550 ASSERT(HDR_HAS_L1HDR(hdr));
2552 state = hdr->b_l1hdr.b_state;
2553 if (GHOST_STATE(state)) {
2554 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2555 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2558 * l2arc_write_buffers() relies on a header's L1 portion
2559 * (i.e. it's b_tmp_cdata field) during it's write phase.
2560 * Thus, we cannot push a header onto the arc_l2c_only
2561 * state (removing it's L1 piece) until the header is
2562 * done being written to the l2arc.
2564 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2565 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2566 return (bytes_evicted);
2569 ARCSTAT_BUMP(arcstat_deleted);
2570 bytes_evicted += hdr->b_size;
2572 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2574 if (HDR_HAS_L2HDR(hdr)) {
2576 * This buffer is cached on the 2nd Level ARC;
2577 * don't destroy the header.
2579 arc_change_state(arc_l2c_only, hdr, hash_lock);
2581 * dropping from L1+L2 cached to L2-only,
2582 * realloc to remove the L1 header.
2584 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2587 arc_change_state(arc_anon, hdr, hash_lock);
2588 arc_hdr_destroy(hdr);
2590 return (bytes_evicted);
2593 ASSERT(state == arc_mru || state == arc_mfu);
2594 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2596 /* prefetch buffers have a minimum lifespan */
2597 if (HDR_IO_IN_PROGRESS(hdr) ||
2598 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2599 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2600 arc_min_prefetch_lifespan)) {
2601 ARCSTAT_BUMP(arcstat_evict_skip);
2602 return (bytes_evicted);
2605 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2606 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2607 while (hdr->b_l1hdr.b_buf) {
2608 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2609 if (!mutex_tryenter(&buf->b_evict_lock)) {
2610 ARCSTAT_BUMP(arcstat_mutex_miss);
2613 if (buf->b_data != NULL)
2614 bytes_evicted += hdr->b_size;
2615 if (buf->b_efunc != NULL) {
2616 mutex_enter(&arc_user_evicts_lock);
2617 arc_buf_destroy(buf, FALSE);
2618 hdr->b_l1hdr.b_buf = buf->b_next;
2619 buf->b_hdr = &arc_eviction_hdr;
2620 buf->b_next = arc_eviction_list;
2621 arc_eviction_list = buf;
2622 cv_signal(&arc_user_evicts_cv);
2623 mutex_exit(&arc_user_evicts_lock);
2624 mutex_exit(&buf->b_evict_lock);
2626 mutex_exit(&buf->b_evict_lock);
2627 arc_buf_destroy(buf, TRUE);
2631 if (HDR_HAS_L2HDR(hdr)) {
2632 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2634 if (l2arc_write_eligible(hdr->b_spa, hdr))
2635 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2637 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2640 if (hdr->b_l1hdr.b_datacnt == 0) {
2641 arc_change_state(evicted_state, hdr, hash_lock);
2642 ASSERT(HDR_IN_HASH_TABLE(hdr));
2643 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2644 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2645 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2648 return (bytes_evicted);
2652 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2653 uint64_t spa, int64_t bytes)
2655 multilist_sublist_t *mls;
2656 uint64_t bytes_evicted = 0;
2658 kmutex_t *hash_lock;
2659 int evict_count = 0;
2661 ASSERT3P(marker, !=, NULL);
2662 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2664 mls = multilist_sublist_lock(ml, idx);
2666 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2667 hdr = multilist_sublist_prev(mls, marker)) {
2668 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2669 (evict_count >= zfs_arc_evict_batch_limit))
2673 * To keep our iteration location, move the marker
2674 * forward. Since we're not holding hdr's hash lock, we
2675 * must be very careful and not remove 'hdr' from the
2676 * sublist. Otherwise, other consumers might mistake the
2677 * 'hdr' as not being on a sublist when they call the
2678 * multilist_link_active() function (they all rely on
2679 * the hash lock protecting concurrent insertions and
2680 * removals). multilist_sublist_move_forward() was
2681 * specifically implemented to ensure this is the case
2682 * (only 'marker' will be removed and re-inserted).
2684 multilist_sublist_move_forward(mls, marker);
2687 * The only case where the b_spa field should ever be
2688 * zero, is the marker headers inserted by
2689 * arc_evict_state(). It's possible for multiple threads
2690 * to be calling arc_evict_state() concurrently (e.g.
2691 * dsl_pool_close() and zio_inject_fault()), so we must
2692 * skip any markers we see from these other threads.
2694 if (hdr->b_spa == 0)
2697 /* we're only interested in evicting buffers of a certain spa */
2698 if (spa != 0 && hdr->b_spa != spa) {
2699 ARCSTAT_BUMP(arcstat_evict_skip);
2703 hash_lock = HDR_LOCK(hdr);
2706 * We aren't calling this function from any code path
2707 * that would already be holding a hash lock, so we're
2708 * asserting on this assumption to be defensive in case
2709 * this ever changes. Without this check, it would be
2710 * possible to incorrectly increment arcstat_mutex_miss
2711 * below (e.g. if the code changed such that we called
2712 * this function with a hash lock held).
2714 ASSERT(!MUTEX_HELD(hash_lock));
2716 if (mutex_tryenter(hash_lock)) {
2717 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2718 mutex_exit(hash_lock);
2720 bytes_evicted += evicted;
2723 * If evicted is zero, arc_evict_hdr() must have
2724 * decided to skip this header, don't increment
2725 * evict_count in this case.
2731 * If arc_size isn't overflowing, signal any
2732 * threads that might happen to be waiting.
2734 * For each header evicted, we wake up a single
2735 * thread. If we used cv_broadcast, we could
2736 * wake up "too many" threads causing arc_size
2737 * to significantly overflow arc_c; since
2738 * arc_get_data_buf() doesn't check for overflow
2739 * when it's woken up (it doesn't because it's
2740 * possible for the ARC to be overflowing while
2741 * full of un-evictable buffers, and the
2742 * function should proceed in this case).
2744 * If threads are left sleeping, due to not
2745 * using cv_broadcast, they will be woken up
2746 * just before arc_reclaim_thread() sleeps.
2748 mutex_enter(&arc_reclaim_lock);
2749 if (!arc_is_overflowing())
2750 cv_signal(&arc_reclaim_waiters_cv);
2751 mutex_exit(&arc_reclaim_lock);
2753 ARCSTAT_BUMP(arcstat_mutex_miss);
2757 multilist_sublist_unlock(mls);
2759 return (bytes_evicted);
2763 * Evict buffers from the given arc state, until we've removed the
2764 * specified number of bytes. Move the removed buffers to the
2765 * appropriate evict state.
2767 * This function makes a "best effort". It skips over any buffers
2768 * it can't get a hash_lock on, and so, may not catch all candidates.
2769 * It may also return without evicting as much space as requested.
2771 * If bytes is specified using the special value ARC_EVICT_ALL, this
2772 * will evict all available (i.e. unlocked and evictable) buffers from
2773 * the given arc state; which is used by arc_flush().
2776 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2777 arc_buf_contents_t type)
2779 uint64_t total_evicted = 0;
2780 multilist_t *ml = &state->arcs_list[type];
2782 arc_buf_hdr_t **markers;
2784 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2786 num_sublists = multilist_get_num_sublists(ml);
2789 * If we've tried to evict from each sublist, made some
2790 * progress, but still have not hit the target number of bytes
2791 * to evict, we want to keep trying. The markers allow us to
2792 * pick up where we left off for each individual sublist, rather
2793 * than starting from the tail each time.
2795 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2796 for (int i = 0; i < num_sublists; i++) {
2797 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2800 * A b_spa of 0 is used to indicate that this header is
2801 * a marker. This fact is used in arc_adjust_type() and
2802 * arc_evict_state_impl().
2804 markers[i]->b_spa = 0;
2806 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2807 multilist_sublist_insert_tail(mls, markers[i]);
2808 multilist_sublist_unlock(mls);
2812 * While we haven't hit our target number of bytes to evict, or
2813 * we're evicting all available buffers.
2815 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2817 * Start eviction using a randomly selected sublist,
2818 * this is to try and evenly balance eviction across all
2819 * sublists. Always starting at the same sublist
2820 * (e.g. index 0) would cause evictions to favor certain
2821 * sublists over others.
2823 int sublist_idx = multilist_get_random_index(ml);
2824 uint64_t scan_evicted = 0;
2826 for (int i = 0; i < num_sublists; i++) {
2827 uint64_t bytes_remaining;
2828 uint64_t bytes_evicted;
2830 if (bytes == ARC_EVICT_ALL)
2831 bytes_remaining = ARC_EVICT_ALL;
2832 else if (total_evicted < bytes)
2833 bytes_remaining = bytes - total_evicted;
2837 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2838 markers[sublist_idx], spa, bytes_remaining);
2840 scan_evicted += bytes_evicted;
2841 total_evicted += bytes_evicted;
2843 /* we've reached the end, wrap to the beginning */
2844 if (++sublist_idx >= num_sublists)
2849 * If we didn't evict anything during this scan, we have
2850 * no reason to believe we'll evict more during another
2851 * scan, so break the loop.
2853 if (scan_evicted == 0) {
2854 /* This isn't possible, let's make that obvious */
2855 ASSERT3S(bytes, !=, 0);
2858 * When bytes is ARC_EVICT_ALL, the only way to
2859 * break the loop is when scan_evicted is zero.
2860 * In that case, we actually have evicted enough,
2861 * so we don't want to increment the kstat.
2863 if (bytes != ARC_EVICT_ALL) {
2864 ASSERT3S(total_evicted, <, bytes);
2865 ARCSTAT_BUMP(arcstat_evict_not_enough);
2872 for (int i = 0; i < num_sublists; i++) {
2873 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2874 multilist_sublist_remove(mls, markers[i]);
2875 multilist_sublist_unlock(mls);
2877 kmem_cache_free(hdr_full_cache, markers[i]);
2879 kmem_free(markers, sizeof (*markers) * num_sublists);
2881 return (total_evicted);
2885 * Flush all "evictable" data of the given type from the arc state
2886 * specified. This will not evict any "active" buffers (i.e. referenced).
2888 * When 'retry' is set to FALSE, the function will make a single pass
2889 * over the state and evict any buffers that it can. Since it doesn't
2890 * continually retry the eviction, it might end up leaving some buffers
2891 * in the ARC due to lock misses.
2893 * When 'retry' is set to TRUE, the function will continually retry the
2894 * eviction until *all* evictable buffers have been removed from the
2895 * state. As a result, if concurrent insertions into the state are
2896 * allowed (e.g. if the ARC isn't shutting down), this function might
2897 * wind up in an infinite loop, continually trying to evict buffers.
2900 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2903 uint64_t evicted = 0;
2905 while (state->arcs_lsize[type] != 0) {
2906 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2916 * Evict the specified number of bytes from the state specified,
2917 * restricting eviction to the spa and type given. This function
2918 * prevents us from trying to evict more from a state's list than
2919 * is "evictable", and to skip evicting altogether when passed a
2920 * negative value for "bytes". In contrast, arc_evict_state() will
2921 * evict everything it can, when passed a negative value for "bytes".
2924 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2925 arc_buf_contents_t type)
2929 if (bytes > 0 && state->arcs_lsize[type] > 0) {
2930 delta = MIN(state->arcs_lsize[type], bytes);
2931 return (arc_evict_state(state, spa, delta, type));
2938 * Evict metadata buffers from the cache, such that arc_meta_used is
2939 * capped by the arc_meta_limit tunable.
2942 arc_adjust_meta(void)
2944 uint64_t total_evicted = 0;
2948 * If we're over the meta limit, we want to evict enough
2949 * metadata to get back under the meta limit. We don't want to
2950 * evict so much that we drop the MRU below arc_p, though. If
2951 * we're over the meta limit more than we're over arc_p, we
2952 * evict some from the MRU here, and some from the MFU below.
2954 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
2955 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size - arc_p));
2957 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
2960 * Similar to the above, we want to evict enough bytes to get us
2961 * below the meta limit, but not so much as to drop us below the
2962 * space alloted to the MFU (which is defined as arc_c - arc_p).
2964 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
2965 (int64_t)(arc_mfu->arcs_size - (arc_c - arc_p)));
2967 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
2969 return (total_evicted);
2973 * Return the type of the oldest buffer in the given arc state
2975 * This function will select a random sublist of type ARC_BUFC_DATA and
2976 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
2977 * is compared, and the type which contains the "older" buffer will be
2980 static arc_buf_contents_t
2981 arc_adjust_type(arc_state_t *state)
2983 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
2984 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
2985 int data_idx = multilist_get_random_index(data_ml);
2986 int meta_idx = multilist_get_random_index(meta_ml);
2987 multilist_sublist_t *data_mls;
2988 multilist_sublist_t *meta_mls;
2989 arc_buf_contents_t type;
2990 arc_buf_hdr_t *data_hdr;
2991 arc_buf_hdr_t *meta_hdr;
2994 * We keep the sublist lock until we're finished, to prevent
2995 * the headers from being destroyed via arc_evict_state().
2997 data_mls = multilist_sublist_lock(data_ml, data_idx);
2998 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3001 * These two loops are to ensure we skip any markers that
3002 * might be at the tail of the lists due to arc_evict_state().
3005 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3006 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3007 if (data_hdr->b_spa != 0)
3011 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3012 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3013 if (meta_hdr->b_spa != 0)
3017 if (data_hdr == NULL && meta_hdr == NULL) {
3018 type = ARC_BUFC_DATA;
3019 } else if (data_hdr == NULL) {
3020 ASSERT3P(meta_hdr, !=, NULL);
3021 type = ARC_BUFC_METADATA;
3022 } else if (meta_hdr == NULL) {
3023 ASSERT3P(data_hdr, !=, NULL);
3024 type = ARC_BUFC_DATA;
3026 ASSERT3P(data_hdr, !=, NULL);
3027 ASSERT3P(meta_hdr, !=, NULL);
3029 /* The headers can't be on the sublist without an L1 header */
3030 ASSERT(HDR_HAS_L1HDR(data_hdr));
3031 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3033 if (data_hdr->b_l1hdr.b_arc_access <
3034 meta_hdr->b_l1hdr.b_arc_access) {
3035 type = ARC_BUFC_DATA;
3037 type = ARC_BUFC_METADATA;
3041 multilist_sublist_unlock(meta_mls);
3042 multilist_sublist_unlock(data_mls);
3048 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3053 uint64_t total_evicted = 0;
3058 * If we're over arc_meta_limit, we want to correct that before
3059 * potentially evicting data buffers below.
3061 total_evicted += arc_adjust_meta();
3066 * If we're over the target cache size, we want to evict enough
3067 * from the list to get back to our target size. We don't want
3068 * to evict too much from the MRU, such that it drops below
3069 * arc_p. So, if we're over our target cache size more than
3070 * the MRU is over arc_p, we'll evict enough to get back to
3071 * arc_p here, and then evict more from the MFU below.
3073 target = MIN((int64_t)(arc_size - arc_c),
3074 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
3078 * If we're below arc_meta_min, always prefer to evict data.
3079 * Otherwise, try to satisfy the requested number of bytes to
3080 * evict from the type which contains older buffers; in an
3081 * effort to keep newer buffers in the cache regardless of their
3082 * type. If we cannot satisfy the number of bytes from this
3083 * type, spill over into the next type.
3085 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3086 arc_meta_used > arc_meta_min) {
3087 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3088 total_evicted += bytes;
3091 * If we couldn't evict our target number of bytes from
3092 * metadata, we try to get the rest from data.
3097 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3099 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3100 total_evicted += bytes;
3103 * If we couldn't evict our target number of bytes from
3104 * data, we try to get the rest from metadata.
3109 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3115 * Now that we've tried to evict enough from the MRU to get its
3116 * size back to arc_p, if we're still above the target cache
3117 * size, we evict the rest from the MFU.
3119 target = arc_size - arc_c;
3121 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3122 arc_meta_used > arc_meta_min) {
3123 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3124 total_evicted += bytes;
3127 * If we couldn't evict our target number of bytes from
3128 * metadata, we try to get the rest from data.
3133 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3135 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3136 total_evicted += bytes;
3139 * If we couldn't evict our target number of bytes from
3140 * data, we try to get the rest from data.
3145 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3149 * Adjust ghost lists
3151 * In addition to the above, the ARC also defines target values
3152 * for the ghost lists. The sum of the mru list and mru ghost
3153 * list should never exceed the target size of the cache, and
3154 * the sum of the mru list, mfu list, mru ghost list, and mfu
3155 * ghost list should never exceed twice the target size of the
3156 * cache. The following logic enforces these limits on the ghost
3157 * caches, and evicts from them as needed.
3159 target = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
3161 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3162 total_evicted += bytes;
3167 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3170 * We assume the sum of the mru list and mfu list is less than
3171 * or equal to arc_c (we enforced this above), which means we
3172 * can use the simpler of the two equations below:
3174 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3175 * mru ghost + mfu ghost <= arc_c
3177 target = arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
3179 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3180 total_evicted += bytes;
3185 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3187 return (total_evicted);
3191 arc_do_user_evicts(void)
3193 mutex_enter(&arc_user_evicts_lock);
3194 while (arc_eviction_list != NULL) {
3195 arc_buf_t *buf = arc_eviction_list;
3196 arc_eviction_list = buf->b_next;
3197 mutex_enter(&buf->b_evict_lock);
3199 mutex_exit(&buf->b_evict_lock);
3200 mutex_exit(&arc_user_evicts_lock);
3202 if (buf->b_efunc != NULL)
3203 VERIFY0(buf->b_efunc(buf->b_private));
3205 buf->b_efunc = NULL;
3206 buf->b_private = NULL;
3207 kmem_cache_free(buf_cache, buf);
3208 mutex_enter(&arc_user_evicts_lock);
3210 mutex_exit(&arc_user_evicts_lock);
3214 arc_flush(spa_t *spa, boolean_t retry)
3219 * If retry is TRUE, a spa must not be specified since we have
3220 * no good way to determine if all of a spa's buffers have been
3221 * evicted from an arc state.
3223 ASSERT(!retry || spa == 0);
3226 guid = spa_load_guid(spa);
3228 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3229 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3231 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3232 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3234 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3235 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3237 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3238 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3240 arc_do_user_evicts();
3241 ASSERT(spa || arc_eviction_list == NULL);
3245 arc_shrink(int64_t to_free)
3247 if (arc_c > arc_c_min) {
3248 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3249 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3250 if (arc_c > arc_c_min + to_free)
3251 atomic_add_64(&arc_c, -to_free);
3255 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3256 if (arc_c > arc_size)
3257 arc_c = MAX(arc_size, arc_c_min);
3259 arc_p = (arc_c >> 1);
3261 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3264 ASSERT(arc_c >= arc_c_min);
3265 ASSERT((int64_t)arc_p >= 0);
3268 if (arc_size > arc_c) {
3269 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3271 (void) arc_adjust();
3275 static long needfree = 0;
3277 typedef enum free_memory_reason_t {
3282 FMR_PAGES_PP_MAXIMUM,
3286 } free_memory_reason_t;
3288 int64_t last_free_memory;
3289 free_memory_reason_t last_free_reason;
3292 * Additional reserve of pages for pp_reserve.
3294 int64_t arc_pages_pp_reserve = 64;
3297 * Additional reserve of pages for swapfs.
3299 int64_t arc_swapfs_reserve = 64;
3302 * Return the amount of memory that can be consumed before reclaim will be
3303 * needed. Positive if there is sufficient free memory, negative indicates
3304 * the amount of memory that needs to be freed up.
3307 arc_available_memory(void)
3309 int64_t lowest = INT64_MAX;
3311 free_memory_reason_t r = FMR_UNKNOWN;
3315 n = PAGESIZE * (-needfree);
3323 * Cooperate with pagedaemon when it's time for it to scan
3324 * and reclaim some pages.
3326 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3334 * check that we're out of range of the pageout scanner. It starts to
3335 * schedule paging if freemem is less than lotsfree and needfree.
3336 * lotsfree is the high-water mark for pageout, and needfree is the
3337 * number of needed free pages. We add extra pages here to make sure
3338 * the scanner doesn't start up while we're freeing memory.
3340 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3347 * check to make sure that swapfs has enough space so that anon
3348 * reservations can still succeed. anon_resvmem() checks that the
3349 * availrmem is greater than swapfs_minfree, and the number of reserved
3350 * swap pages. We also add a bit of extra here just to prevent
3351 * circumstances from getting really dire.
3353 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3354 desfree - arc_swapfs_reserve);
3357 r = FMR_SWAPFS_MINFREE;
3362 * Check that we have enough availrmem that memory locking (e.g., via
3363 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3364 * stores the number of pages that cannot be locked; when availrmem
3365 * drops below pages_pp_maximum, page locking mechanisms such as
3366 * page_pp_lock() will fail.)
3368 n = PAGESIZE * (availrmem - pages_pp_maximum -
3369 arc_pages_pp_reserve);
3372 r = FMR_PAGES_PP_MAXIMUM;
3376 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3378 * If we're on an i386 platform, it's possible that we'll exhaust the
3379 * kernel heap space before we ever run out of available physical
3380 * memory. Most checks of the size of the heap_area compare against
3381 * tune.t_minarmem, which is the minimum available real memory that we
3382 * can have in the system. However, this is generally fixed at 25 pages
3383 * which is so low that it's useless. In this comparison, we seek to
3384 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3385 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3388 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3389 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3394 #define zio_arena NULL
3396 #define zio_arena heap_arena
3400 * If zio data pages are being allocated out of a separate heap segment,
3401 * then enforce that the size of available vmem for this arena remains
3402 * above about 1/16th free.
3404 * Note: The 1/16th arena free requirement was put in place
3405 * to aggressively evict memory from the arc in order to avoid
3406 * memory fragmentation issues.
3408 if (zio_arena != NULL) {
3409 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3410 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3418 * Above limits know nothing about real level of KVA fragmentation.
3419 * Start aggressive reclamation if too little sequential KVA left.
3422 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3423 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3432 /* Every 100 calls, free a small amount */
3433 if (spa_get_random(100) == 0)
3435 #endif /* _KERNEL */
3437 last_free_memory = lowest;
3438 last_free_reason = r;
3439 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3445 * Determine if the system is under memory pressure and is asking
3446 * to reclaim memory. A return value of TRUE indicates that the system
3447 * is under memory pressure and that the arc should adjust accordingly.
3450 arc_reclaim_needed(void)
3452 return (arc_available_memory() < 0);
3455 extern kmem_cache_t *zio_buf_cache[];
3456 extern kmem_cache_t *zio_data_buf_cache[];
3457 extern kmem_cache_t *range_seg_cache;
3459 static __noinline void
3460 arc_kmem_reap_now(void)
3463 kmem_cache_t *prev_cache = NULL;
3464 kmem_cache_t *prev_data_cache = NULL;
3466 DTRACE_PROBE(arc__kmem_reap_start);
3468 if (arc_meta_used >= arc_meta_limit) {
3470 * We are exceeding our meta-data cache limit.
3471 * Purge some DNLC entries to release holds on meta-data.
3473 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3477 * Reclaim unused memory from all kmem caches.
3483 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3484 if (zio_buf_cache[i] != prev_cache) {
3485 prev_cache = zio_buf_cache[i];
3486 kmem_cache_reap_now(zio_buf_cache[i]);
3488 if (zio_data_buf_cache[i] != prev_data_cache) {
3489 prev_data_cache = zio_data_buf_cache[i];
3490 kmem_cache_reap_now(zio_data_buf_cache[i]);
3493 kmem_cache_reap_now(buf_cache);
3494 kmem_cache_reap_now(hdr_full_cache);
3495 kmem_cache_reap_now(hdr_l2only_cache);
3496 kmem_cache_reap_now(range_seg_cache);
3499 if (zio_arena != NULL) {
3501 * Ask the vmem arena to reclaim unused memory from its
3504 vmem_qcache_reap(zio_arena);
3507 DTRACE_PROBE(arc__kmem_reap_end);
3511 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3512 * enough data and signal them to proceed. When this happens, the threads in
3513 * arc_get_data_buf() are sleeping while holding the hash lock for their
3514 * particular arc header. Thus, we must be careful to never sleep on a
3515 * hash lock in this thread. This is to prevent the following deadlock:
3517 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3518 * waiting for the reclaim thread to signal it.
3520 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3521 * fails, and goes to sleep forever.
3523 * This possible deadlock is avoided by always acquiring a hash lock
3524 * using mutex_tryenter() from arc_reclaim_thread().
3527 arc_reclaim_thread(void *dummy __unused)
3529 clock_t growtime = 0;
3532 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3534 mutex_enter(&arc_reclaim_lock);
3535 while (!arc_reclaim_thread_exit) {
3536 int64_t free_memory = arc_available_memory();
3537 uint64_t evicted = 0;
3539 mutex_exit(&arc_reclaim_lock);
3541 if (free_memory < 0) {
3543 arc_no_grow = B_TRUE;
3547 * Wait at least zfs_grow_retry (default 60) seconds
3548 * before considering growing.
3550 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3552 arc_kmem_reap_now();
3555 * If we are still low on memory, shrink the ARC
3556 * so that we have arc_shrink_min free space.
3558 free_memory = arc_available_memory();
3561 (arc_c >> arc_shrink_shift) - free_memory;
3564 to_free = MAX(to_free, ptob(needfree));
3566 arc_shrink(to_free);
3568 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3569 arc_no_grow = B_TRUE;
3570 } else if (ddi_get_lbolt() >= growtime) {
3571 arc_no_grow = B_FALSE;
3574 evicted = arc_adjust();
3576 mutex_enter(&arc_reclaim_lock);
3579 * If evicted is zero, we couldn't evict anything via
3580 * arc_adjust(). This could be due to hash lock
3581 * collisions, but more likely due to the majority of
3582 * arc buffers being unevictable. Therefore, even if
3583 * arc_size is above arc_c, another pass is unlikely to
3584 * be helpful and could potentially cause us to enter an
3587 if (arc_size <= arc_c || evicted == 0) {
3592 * We're either no longer overflowing, or we
3593 * can't evict anything more, so we should wake
3594 * up any threads before we go to sleep.
3596 cv_broadcast(&arc_reclaim_waiters_cv);
3599 * Block until signaled, or after one second (we
3600 * might need to perform arc_kmem_reap_now()
3601 * even if we aren't being signalled)
3603 CALLB_CPR_SAFE_BEGIN(&cpr);
3604 (void) cv_timedwait(&arc_reclaim_thread_cv,
3605 &arc_reclaim_lock, hz);
3606 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3610 arc_reclaim_thread_exit = FALSE;
3611 cv_broadcast(&arc_reclaim_thread_cv);
3612 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3617 arc_user_evicts_thread(void *dummy __unused)
3621 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3623 mutex_enter(&arc_user_evicts_lock);
3624 while (!arc_user_evicts_thread_exit) {
3625 mutex_exit(&arc_user_evicts_lock);
3627 arc_do_user_evicts();
3630 * This is necessary in order for the mdb ::arc dcmd to
3631 * show up to date information. Since the ::arc command
3632 * does not call the kstat's update function, without
3633 * this call, the command may show stale stats for the
3634 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3635 * with this change, the data might be up to 1 second
3636 * out of date; but that should suffice. The arc_state_t
3637 * structures can be queried directly if more accurate
3638 * information is needed.
3640 if (arc_ksp != NULL)
3641 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3643 mutex_enter(&arc_user_evicts_lock);
3646 * Block until signaled, or after one second (we need to
3647 * call the arc's kstat update function regularly).
3649 CALLB_CPR_SAFE_BEGIN(&cpr);
3650 (void) cv_timedwait(&arc_user_evicts_cv,
3651 &arc_user_evicts_lock, hz);
3652 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3655 arc_user_evicts_thread_exit = FALSE;
3656 cv_broadcast(&arc_user_evicts_cv);
3657 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3662 * Adapt arc info given the number of bytes we are trying to add and
3663 * the state that we are comming from. This function is only called
3664 * when we are adding new content to the cache.
3667 arc_adapt(int bytes, arc_state_t *state)
3670 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3672 if (state == arc_l2c_only)
3677 * Adapt the target size of the MRU list:
3678 * - if we just hit in the MRU ghost list, then increase
3679 * the target size of the MRU list.
3680 * - if we just hit in the MFU ghost list, then increase
3681 * the target size of the MFU list by decreasing the
3682 * target size of the MRU list.
3684 if (state == arc_mru_ghost) {
3685 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
3686 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
3687 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3689 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3690 } else if (state == arc_mfu_ghost) {
3693 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
3694 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
3695 mult = MIN(mult, 10);
3697 delta = MIN(bytes * mult, arc_p);
3698 arc_p = MAX(arc_p_min, arc_p - delta);
3700 ASSERT((int64_t)arc_p >= 0);
3702 if (arc_reclaim_needed()) {
3703 cv_signal(&arc_reclaim_thread_cv);
3710 if (arc_c >= arc_c_max)
3714 * If we're within (2 * maxblocksize) bytes of the target
3715 * cache size, increment the target cache size
3717 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3718 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3719 atomic_add_64(&arc_c, (int64_t)bytes);
3720 if (arc_c > arc_c_max)
3722 else if (state == arc_anon)
3723 atomic_add_64(&arc_p, (int64_t)bytes);
3727 ASSERT((int64_t)arc_p >= 0);
3731 * Check if arc_size has grown past our upper threshold, determined by
3732 * zfs_arc_overflow_shift.
3735 arc_is_overflowing(void)
3737 /* Always allow at least one block of overflow */
3738 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3739 arc_c >> zfs_arc_overflow_shift);
3741 return (arc_size >= arc_c + overflow);
3745 * The buffer, supplied as the first argument, needs a data block. If we
3746 * are hitting the hard limit for the cache size, we must sleep, waiting
3747 * for the eviction thread to catch up. If we're past the target size
3748 * but below the hard limit, we'll only signal the reclaim thread and
3752 arc_get_data_buf(arc_buf_t *buf)
3754 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3755 uint64_t size = buf->b_hdr->b_size;
3756 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3758 arc_adapt(size, state);
3761 * If arc_size is currently overflowing, and has grown past our
3762 * upper limit, we must be adding data faster than the evict
3763 * thread can evict. Thus, to ensure we don't compound the
3764 * problem by adding more data and forcing arc_size to grow even
3765 * further past it's target size, we halt and wait for the
3766 * eviction thread to catch up.
3768 * It's also possible that the reclaim thread is unable to evict
3769 * enough buffers to get arc_size below the overflow limit (e.g.
3770 * due to buffers being un-evictable, or hash lock collisions).
3771 * In this case, we want to proceed regardless if we're
3772 * overflowing; thus we don't use a while loop here.
3774 if (arc_is_overflowing()) {
3775 mutex_enter(&arc_reclaim_lock);
3778 * Now that we've acquired the lock, we may no longer be
3779 * over the overflow limit, lets check.
3781 * We're ignoring the case of spurious wake ups. If that
3782 * were to happen, it'd let this thread consume an ARC
3783 * buffer before it should have (i.e. before we're under
3784 * the overflow limit and were signalled by the reclaim
3785 * thread). As long as that is a rare occurrence, it
3786 * shouldn't cause any harm.
3788 if (arc_is_overflowing()) {
3789 cv_signal(&arc_reclaim_thread_cv);
3790 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3793 mutex_exit(&arc_reclaim_lock);
3796 if (type == ARC_BUFC_METADATA) {
3797 buf->b_data = zio_buf_alloc(size);
3798 arc_space_consume(size, ARC_SPACE_META);
3800 ASSERT(type == ARC_BUFC_DATA);
3801 buf->b_data = zio_data_buf_alloc(size);
3802 arc_space_consume(size, ARC_SPACE_DATA);
3806 * Update the state size. Note that ghost states have a
3807 * "ghost size" and so don't need to be updated.
3809 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3810 arc_buf_hdr_t *hdr = buf->b_hdr;
3812 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_size, size);
3815 * If this is reached via arc_read, the link is
3816 * protected by the hash lock. If reached via
3817 * arc_buf_alloc, the header should not be accessed by
3818 * any other thread. And, if reached via arc_read_done,
3819 * the hash lock will protect it if it's found in the
3820 * hash table; otherwise no other thread should be
3821 * trying to [add|remove]_reference it.
3823 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3824 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3825 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3829 * If we are growing the cache, and we are adding anonymous
3830 * data, and we have outgrown arc_p, update arc_p
3832 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3833 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
3834 arc_p = MIN(arc_c, arc_p + size);
3836 ARCSTAT_BUMP(arcstat_allocated);
3840 * This routine is called whenever a buffer is accessed.
3841 * NOTE: the hash lock is dropped in this function.
3844 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3848 ASSERT(MUTEX_HELD(hash_lock));
3849 ASSERT(HDR_HAS_L1HDR(hdr));
3851 if (hdr->b_l1hdr.b_state == arc_anon) {
3853 * This buffer is not in the cache, and does not
3854 * appear in our "ghost" list. Add the new buffer
3858 ASSERT0(hdr->b_l1hdr.b_arc_access);
3859 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3860 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3861 arc_change_state(arc_mru, hdr, hash_lock);
3863 } else if (hdr->b_l1hdr.b_state == arc_mru) {
3864 now = ddi_get_lbolt();
3867 * If this buffer is here because of a prefetch, then either:
3868 * - clear the flag if this is a "referencing" read
3869 * (any subsequent access will bump this into the MFU state).
3871 * - move the buffer to the head of the list if this is
3872 * another prefetch (to make it less likely to be evicted).
3874 if (HDR_PREFETCH(hdr)) {
3875 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3876 /* link protected by hash lock */
3877 ASSERT(multilist_link_active(
3878 &hdr->b_l1hdr.b_arc_node));
3880 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3881 ARCSTAT_BUMP(arcstat_mru_hits);
3883 hdr->b_l1hdr.b_arc_access = now;
3888 * This buffer has been "accessed" only once so far,
3889 * but it is still in the cache. Move it to the MFU
3892 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3894 * More than 125ms have passed since we
3895 * instantiated this buffer. Move it to the
3896 * most frequently used state.
3898 hdr->b_l1hdr.b_arc_access = now;
3899 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3900 arc_change_state(arc_mfu, hdr, hash_lock);
3902 ARCSTAT_BUMP(arcstat_mru_hits);
3903 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3904 arc_state_t *new_state;
3906 * This buffer has been "accessed" recently, but
3907 * was evicted from the cache. Move it to the
3911 if (HDR_PREFETCH(hdr)) {
3912 new_state = arc_mru;
3913 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3914 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3915 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3917 new_state = arc_mfu;
3918 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3921 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3922 arc_change_state(new_state, hdr, hash_lock);
3924 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3925 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
3927 * This buffer has been accessed more than once and is
3928 * still in the cache. Keep it in the MFU state.
3930 * NOTE: an add_reference() that occurred when we did
3931 * the arc_read() will have kicked this off the list.
3932 * If it was a prefetch, we will explicitly move it to
3933 * the head of the list now.
3935 if ((HDR_PREFETCH(hdr)) != 0) {
3936 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3937 /* link protected by hash_lock */
3938 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3940 ARCSTAT_BUMP(arcstat_mfu_hits);
3941 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3942 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
3943 arc_state_t *new_state = arc_mfu;
3945 * This buffer has been accessed more than once but has
3946 * been evicted from the cache. Move it back to the
3950 if (HDR_PREFETCH(hdr)) {
3952 * This is a prefetch access...
3953 * move this block back to the MRU state.
3955 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3956 new_state = arc_mru;
3959 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3960 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3961 arc_change_state(new_state, hdr, hash_lock);
3963 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3964 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
3966 * This buffer is on the 2nd Level ARC.
3969 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3970 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3971 arc_change_state(arc_mfu, hdr, hash_lock);
3973 ASSERT(!"invalid arc state");
3977 /* a generic arc_done_func_t which you can use */
3980 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3982 if (zio == NULL || zio->io_error == 0)
3983 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3984 VERIFY(arc_buf_remove_ref(buf, arg));
3987 /* a generic arc_done_func_t */
3989 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3991 arc_buf_t **bufp = arg;
3992 if (zio && zio->io_error) {
3993 VERIFY(arc_buf_remove_ref(buf, arg));
3997 ASSERT(buf->b_data);
4002 arc_read_done(zio_t *zio)
4006 arc_buf_t *abuf; /* buffer we're assigning to callback */
4007 kmutex_t *hash_lock = NULL;
4008 arc_callback_t *callback_list, *acb;
4009 int freeable = FALSE;
4011 buf = zio->io_private;
4015 * The hdr was inserted into hash-table and removed from lists
4016 * prior to starting I/O. We should find this header, since
4017 * it's in the hash table, and it should be legit since it's
4018 * not possible to evict it during the I/O. The only possible
4019 * reason for it not to be found is if we were freed during the
4022 if (HDR_IN_HASH_TABLE(hdr)) {
4023 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4024 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4025 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4026 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4027 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4029 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4032 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4033 hash_lock == NULL) ||
4035 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4036 (found == hdr && HDR_L2_READING(hdr)));
4039 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4040 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4041 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4043 /* byteswap if necessary */
4044 callback_list = hdr->b_l1hdr.b_acb;
4045 ASSERT(callback_list != NULL);
4046 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4047 dmu_object_byteswap_t bswap =
4048 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4049 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4050 byteswap_uint64_array :
4051 dmu_ot_byteswap[bswap].ob_func;
4052 func(buf->b_data, hdr->b_size);
4055 arc_cksum_compute(buf, B_FALSE);
4058 #endif /* illumos */
4060 if (hash_lock && zio->io_error == 0 &&
4061 hdr->b_l1hdr.b_state == arc_anon) {
4063 * Only call arc_access on anonymous buffers. This is because
4064 * if we've issued an I/O for an evicted buffer, we've already
4065 * called arc_access (to prevent any simultaneous readers from
4066 * getting confused).
4068 arc_access(hdr, hash_lock);
4071 /* create copies of the data buffer for the callers */
4073 for (acb = callback_list; acb; acb = acb->acb_next) {
4074 if (acb->acb_done) {
4076 ARCSTAT_BUMP(arcstat_duplicate_reads);
4077 abuf = arc_buf_clone(buf);
4079 acb->acb_buf = abuf;
4083 hdr->b_l1hdr.b_acb = NULL;
4084 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4085 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4087 ASSERT(buf->b_efunc == NULL);
4088 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4089 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4092 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4093 callback_list != NULL);
4095 if (zio->io_error != 0) {
4096 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4097 if (hdr->b_l1hdr.b_state != arc_anon)
4098 arc_change_state(arc_anon, hdr, hash_lock);
4099 if (HDR_IN_HASH_TABLE(hdr))
4100 buf_hash_remove(hdr);
4101 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4105 * Broadcast before we drop the hash_lock to avoid the possibility
4106 * that the hdr (and hence the cv) might be freed before we get to
4107 * the cv_broadcast().
4109 cv_broadcast(&hdr->b_l1hdr.b_cv);
4111 if (hash_lock != NULL) {
4112 mutex_exit(hash_lock);
4115 * This block was freed while we waited for the read to
4116 * complete. It has been removed from the hash table and
4117 * moved to the anonymous state (so that it won't show up
4120 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4121 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4124 /* execute each callback and free its structure */
4125 while ((acb = callback_list) != NULL) {
4127 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4129 if (acb->acb_zio_dummy != NULL) {
4130 acb->acb_zio_dummy->io_error = zio->io_error;
4131 zio_nowait(acb->acb_zio_dummy);
4134 callback_list = acb->acb_next;
4135 kmem_free(acb, sizeof (arc_callback_t));
4139 arc_hdr_destroy(hdr);
4143 * "Read" the block at the specified DVA (in bp) via the
4144 * cache. If the block is found in the cache, invoke the provided
4145 * callback immediately and return. Note that the `zio' parameter
4146 * in the callback will be NULL in this case, since no IO was
4147 * required. If the block is not in the cache pass the read request
4148 * on to the spa with a substitute callback function, so that the
4149 * requested block will be added to the cache.
4151 * If a read request arrives for a block that has a read in-progress,
4152 * either wait for the in-progress read to complete (and return the
4153 * results); or, if this is a read with a "done" func, add a record
4154 * to the read to invoke the "done" func when the read completes,
4155 * and return; or just return.
4157 * arc_read_done() will invoke all the requested "done" functions
4158 * for readers of this block.
4161 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4162 void *private, zio_priority_t priority, int zio_flags,
4163 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4165 arc_buf_hdr_t *hdr = NULL;
4166 arc_buf_t *buf = NULL;
4167 kmutex_t *hash_lock = NULL;
4169 uint64_t guid = spa_load_guid(spa);
4171 ASSERT(!BP_IS_EMBEDDED(bp) ||
4172 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4175 if (!BP_IS_EMBEDDED(bp)) {
4177 * Embedded BP's have no DVA and require no I/O to "read".
4178 * Create an anonymous arc buf to back it.
4180 hdr = buf_hash_find(guid, bp, &hash_lock);
4183 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4185 *arc_flags |= ARC_FLAG_CACHED;
4187 if (HDR_IO_IN_PROGRESS(hdr)) {
4189 if (*arc_flags & ARC_FLAG_WAIT) {
4190 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4191 mutex_exit(hash_lock);
4194 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4197 arc_callback_t *acb = NULL;
4199 acb = kmem_zalloc(sizeof (arc_callback_t),
4201 acb->acb_done = done;
4202 acb->acb_private = private;
4204 acb->acb_zio_dummy = zio_null(pio,
4205 spa, NULL, NULL, NULL, zio_flags);
4207 ASSERT(acb->acb_done != NULL);
4208 acb->acb_next = hdr->b_l1hdr.b_acb;
4209 hdr->b_l1hdr.b_acb = acb;
4210 add_reference(hdr, hash_lock, private);
4211 mutex_exit(hash_lock);
4214 mutex_exit(hash_lock);
4218 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4219 hdr->b_l1hdr.b_state == arc_mfu);
4222 add_reference(hdr, hash_lock, private);
4224 * If this block is already in use, create a new
4225 * copy of the data so that we will be guaranteed
4226 * that arc_release() will always succeed.
4228 buf = hdr->b_l1hdr.b_buf;
4230 ASSERT(buf->b_data);
4231 if (HDR_BUF_AVAILABLE(hdr)) {
4232 ASSERT(buf->b_efunc == NULL);
4233 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4235 buf = arc_buf_clone(buf);
4238 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4239 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4240 hdr->b_flags |= ARC_FLAG_PREFETCH;
4242 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4243 arc_access(hdr, hash_lock);
4244 if (*arc_flags & ARC_FLAG_L2CACHE)
4245 hdr->b_flags |= ARC_FLAG_L2CACHE;
4246 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4247 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4248 mutex_exit(hash_lock);
4249 ARCSTAT_BUMP(arcstat_hits);
4250 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4251 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4252 data, metadata, hits);
4255 done(NULL, buf, private);
4257 uint64_t size = BP_GET_LSIZE(bp);
4258 arc_callback_t *acb;
4261 boolean_t devw = B_FALSE;
4262 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4263 int32_t b_asize = 0;
4266 /* this block is not in the cache */
4267 arc_buf_hdr_t *exists = NULL;
4268 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4269 buf = arc_buf_alloc(spa, size, private, type);
4271 if (!BP_IS_EMBEDDED(bp)) {
4272 hdr->b_dva = *BP_IDENTITY(bp);
4273 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4274 exists = buf_hash_insert(hdr, &hash_lock);
4276 if (exists != NULL) {
4277 /* somebody beat us to the hash insert */
4278 mutex_exit(hash_lock);
4279 buf_discard_identity(hdr);
4280 (void) arc_buf_remove_ref(buf, private);
4281 goto top; /* restart the IO request */
4284 /* if this is a prefetch, we don't have a reference */
4285 if (*arc_flags & ARC_FLAG_PREFETCH) {
4286 (void) remove_reference(hdr, hash_lock,
4288 hdr->b_flags |= ARC_FLAG_PREFETCH;
4290 if (*arc_flags & ARC_FLAG_L2CACHE)
4291 hdr->b_flags |= ARC_FLAG_L2CACHE;
4292 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4293 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4294 if (BP_GET_LEVEL(bp) > 0)
4295 hdr->b_flags |= ARC_FLAG_INDIRECT;
4298 * This block is in the ghost cache. If it was L2-only
4299 * (and thus didn't have an L1 hdr), we realloc the
4300 * header to add an L1 hdr.
4302 if (!HDR_HAS_L1HDR(hdr)) {
4303 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4307 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4308 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4309 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4310 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4312 /* if this is a prefetch, we don't have a reference */
4313 if (*arc_flags & ARC_FLAG_PREFETCH)
4314 hdr->b_flags |= ARC_FLAG_PREFETCH;
4316 add_reference(hdr, hash_lock, private);
4317 if (*arc_flags & ARC_FLAG_L2CACHE)
4318 hdr->b_flags |= ARC_FLAG_L2CACHE;
4319 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4320 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4321 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4324 buf->b_efunc = NULL;
4325 buf->b_private = NULL;
4327 hdr->b_l1hdr.b_buf = buf;
4328 ASSERT0(hdr->b_l1hdr.b_datacnt);
4329 hdr->b_l1hdr.b_datacnt = 1;
4330 arc_get_data_buf(buf);
4331 arc_access(hdr, hash_lock);
4334 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4336 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4337 acb->acb_done = done;
4338 acb->acb_private = private;
4340 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4341 hdr->b_l1hdr.b_acb = acb;
4342 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4344 if (HDR_HAS_L2HDR(hdr) &&
4345 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4346 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4347 addr = hdr->b_l2hdr.b_daddr;
4348 b_compress = HDR_GET_COMPRESS(hdr);
4349 b_asize = hdr->b_l2hdr.b_asize;
4351 * Lock out device removal.
4353 if (vdev_is_dead(vd) ||
4354 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4358 if (hash_lock != NULL)
4359 mutex_exit(hash_lock);
4362 * At this point, we have a level 1 cache miss. Try again in
4363 * L2ARC if possible.
4365 ASSERT3U(hdr->b_size, ==, size);
4366 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4367 uint64_t, size, zbookmark_phys_t *, zb);
4368 ARCSTAT_BUMP(arcstat_misses);
4369 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4370 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4371 data, metadata, misses);
4373 curthread->td_ru.ru_inblock++;
4376 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4378 * Read from the L2ARC if the following are true:
4379 * 1. The L2ARC vdev was previously cached.
4380 * 2. This buffer still has L2ARC metadata.
4381 * 3. This buffer isn't currently writing to the L2ARC.
4382 * 4. The L2ARC entry wasn't evicted, which may
4383 * also have invalidated the vdev.
4384 * 5. This isn't prefetch and l2arc_noprefetch is set.
4386 if (HDR_HAS_L2HDR(hdr) &&
4387 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4388 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4389 l2arc_read_callback_t *cb;
4391 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4392 ARCSTAT_BUMP(arcstat_l2_hits);
4394 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4396 cb->l2rcb_buf = buf;
4397 cb->l2rcb_spa = spa;
4400 cb->l2rcb_flags = zio_flags;
4401 cb->l2rcb_compress = b_compress;
4403 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4404 addr + size < vd->vdev_psize -
4405 VDEV_LABEL_END_SIZE);
4408 * l2arc read. The SCL_L2ARC lock will be
4409 * released by l2arc_read_done().
4410 * Issue a null zio if the underlying buffer
4411 * was squashed to zero size by compression.
4413 if (b_compress == ZIO_COMPRESS_EMPTY) {
4414 rzio = zio_null(pio, spa, vd,
4415 l2arc_read_done, cb,
4416 zio_flags | ZIO_FLAG_DONT_CACHE |
4418 ZIO_FLAG_DONT_PROPAGATE |
4419 ZIO_FLAG_DONT_RETRY);
4421 rzio = zio_read_phys(pio, vd, addr,
4422 b_asize, buf->b_data,
4424 l2arc_read_done, cb, priority,
4425 zio_flags | ZIO_FLAG_DONT_CACHE |
4427 ZIO_FLAG_DONT_PROPAGATE |
4428 ZIO_FLAG_DONT_RETRY, B_FALSE);
4430 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4432 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4434 if (*arc_flags & ARC_FLAG_NOWAIT) {
4439 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4440 if (zio_wait(rzio) == 0)
4443 /* l2arc read error; goto zio_read() */
4445 DTRACE_PROBE1(l2arc__miss,
4446 arc_buf_hdr_t *, hdr);
4447 ARCSTAT_BUMP(arcstat_l2_misses);
4448 if (HDR_L2_WRITING(hdr))
4449 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4450 spa_config_exit(spa, SCL_L2ARC, vd);
4454 spa_config_exit(spa, SCL_L2ARC, vd);
4455 if (l2arc_ndev != 0) {
4456 DTRACE_PROBE1(l2arc__miss,
4457 arc_buf_hdr_t *, hdr);
4458 ARCSTAT_BUMP(arcstat_l2_misses);
4462 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4463 arc_read_done, buf, priority, zio_flags, zb);
4465 if (*arc_flags & ARC_FLAG_WAIT)
4466 return (zio_wait(rzio));
4468 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4475 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4477 ASSERT(buf->b_hdr != NULL);
4478 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4479 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4481 ASSERT(buf->b_efunc == NULL);
4482 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4484 buf->b_efunc = func;
4485 buf->b_private = private;
4489 * Notify the arc that a block was freed, and thus will never be used again.
4492 arc_freed(spa_t *spa, const blkptr_t *bp)
4495 kmutex_t *hash_lock;
4496 uint64_t guid = spa_load_guid(spa);
4498 ASSERT(!BP_IS_EMBEDDED(bp));
4500 hdr = buf_hash_find(guid, bp, &hash_lock);
4503 if (HDR_BUF_AVAILABLE(hdr)) {
4504 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4505 add_reference(hdr, hash_lock, FTAG);
4506 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4507 mutex_exit(hash_lock);
4509 arc_release(buf, FTAG);
4510 (void) arc_buf_remove_ref(buf, FTAG);
4512 mutex_exit(hash_lock);
4518 * Clear the user eviction callback set by arc_set_callback(), first calling
4519 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4520 * clearing the callback may result in the arc_buf being destroyed. However,
4521 * it will not result in the *last* arc_buf being destroyed, hence the data
4522 * will remain cached in the ARC. We make a copy of the arc buffer here so
4523 * that we can process the callback without holding any locks.
4525 * It's possible that the callback is already in the process of being cleared
4526 * by another thread. In this case we can not clear the callback.
4528 * Returns B_TRUE if the callback was successfully called and cleared.
4531 arc_clear_callback(arc_buf_t *buf)
4534 kmutex_t *hash_lock;
4535 arc_evict_func_t *efunc = buf->b_efunc;
4536 void *private = buf->b_private;
4538 mutex_enter(&buf->b_evict_lock);
4542 * We are in arc_do_user_evicts().
4544 ASSERT(buf->b_data == NULL);
4545 mutex_exit(&buf->b_evict_lock);
4547 } else if (buf->b_data == NULL) {
4549 * We are on the eviction list; process this buffer now
4550 * but let arc_do_user_evicts() do the reaping.
4552 buf->b_efunc = NULL;
4553 mutex_exit(&buf->b_evict_lock);
4554 VERIFY0(efunc(private));
4557 hash_lock = HDR_LOCK(hdr);
4558 mutex_enter(hash_lock);
4560 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4562 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4563 hdr->b_l1hdr.b_datacnt);
4564 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4565 hdr->b_l1hdr.b_state == arc_mfu);
4567 buf->b_efunc = NULL;
4568 buf->b_private = NULL;
4570 if (hdr->b_l1hdr.b_datacnt > 1) {
4571 mutex_exit(&buf->b_evict_lock);
4572 arc_buf_destroy(buf, TRUE);
4574 ASSERT(buf == hdr->b_l1hdr.b_buf);
4575 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4576 mutex_exit(&buf->b_evict_lock);
4579 mutex_exit(hash_lock);
4580 VERIFY0(efunc(private));
4585 * Release this buffer from the cache, making it an anonymous buffer. This
4586 * must be done after a read and prior to modifying the buffer contents.
4587 * If the buffer has more than one reference, we must make
4588 * a new hdr for the buffer.
4591 arc_release(arc_buf_t *buf, void *tag)
4593 arc_buf_hdr_t *hdr = buf->b_hdr;
4595 ASSERT(HDR_HAS_L1HDR(hdr));
4598 * It would be nice to assert that if it's DMU metadata (level >
4599 * 0 || it's the dnode file), then it must be syncing context.
4600 * But we don't know that information at this level.
4603 mutex_enter(&buf->b_evict_lock);
4605 * We don't grab the hash lock prior to this check, because if
4606 * the buffer's header is in the arc_anon state, it won't be
4607 * linked into the hash table.
4609 if (hdr->b_l1hdr.b_state == arc_anon) {
4610 mutex_exit(&buf->b_evict_lock);
4611 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4612 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4613 ASSERT(!HDR_HAS_L2HDR(hdr));
4614 ASSERT(BUF_EMPTY(hdr));
4615 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4616 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4617 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4619 ASSERT3P(buf->b_efunc, ==, NULL);
4620 ASSERT3P(buf->b_private, ==, NULL);
4622 hdr->b_l1hdr.b_arc_access = 0;
4628 kmutex_t *hash_lock = HDR_LOCK(hdr);
4629 mutex_enter(hash_lock);
4632 * This assignment is only valid as long as the hash_lock is
4633 * held, we must be careful not to reference state or the
4634 * b_state field after dropping the lock.
4636 arc_state_t *state = hdr->b_l1hdr.b_state;
4637 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4638 ASSERT3P(state, !=, arc_anon);
4640 /* this buffer is not on any list */
4641 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4643 if (HDR_HAS_L2HDR(hdr)) {
4644 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4647 * We have to recheck this conditional again now that
4648 * we're holding the l2ad_mtx to prevent a race with
4649 * another thread which might be concurrently calling
4650 * l2arc_evict(). In that case, l2arc_evict() might have
4651 * destroyed the header's L2 portion as we were waiting
4652 * to acquire the l2ad_mtx.
4654 if (HDR_HAS_L2HDR(hdr)) {
4655 if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
4656 trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
4657 hdr->b_l2hdr.b_daddr,
4658 hdr->b_l2hdr.b_asize, 0);
4659 arc_hdr_l2hdr_destroy(hdr);
4662 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4666 * Do we have more than one buf?
4668 if (hdr->b_l1hdr.b_datacnt > 1) {
4669 arc_buf_hdr_t *nhdr;
4671 uint64_t blksz = hdr->b_size;
4672 uint64_t spa = hdr->b_spa;
4673 arc_buf_contents_t type = arc_buf_type(hdr);
4674 uint32_t flags = hdr->b_flags;
4676 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4678 * Pull the data off of this hdr and attach it to
4679 * a new anonymous hdr.
4681 (void) remove_reference(hdr, hash_lock, tag);
4682 bufp = &hdr->b_l1hdr.b_buf;
4683 while (*bufp != buf)
4684 bufp = &(*bufp)->b_next;
4685 *bufp = buf->b_next;
4688 ASSERT3P(state, !=, arc_l2c_only);
4689 ASSERT3U(state->arcs_size, >=, hdr->b_size);
4690 atomic_add_64(&state->arcs_size, -hdr->b_size);
4691 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4692 ASSERT3P(state, !=, arc_l2c_only);
4693 uint64_t *size = &state->arcs_lsize[type];
4694 ASSERT3U(*size, >=, hdr->b_size);
4695 atomic_add_64(size, -hdr->b_size);
4699 * We're releasing a duplicate user data buffer, update
4700 * our statistics accordingly.
4702 if (HDR_ISTYPE_DATA(hdr)) {
4703 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4704 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4707 hdr->b_l1hdr.b_datacnt -= 1;
4708 arc_cksum_verify(buf);
4710 arc_buf_unwatch(buf);
4711 #endif /* illumos */
4713 mutex_exit(hash_lock);
4715 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4716 nhdr->b_size = blksz;
4719 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4720 nhdr->b_flags |= arc_bufc_to_flags(type);
4721 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4723 nhdr->b_l1hdr.b_buf = buf;
4724 nhdr->b_l1hdr.b_datacnt = 1;
4725 nhdr->b_l1hdr.b_state = arc_anon;
4726 nhdr->b_l1hdr.b_arc_access = 0;
4727 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4728 nhdr->b_freeze_cksum = NULL;
4730 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4732 mutex_exit(&buf->b_evict_lock);
4733 atomic_add_64(&arc_anon->arcs_size, blksz);
4735 mutex_exit(&buf->b_evict_lock);
4736 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4737 /* protected by hash lock, or hdr is on arc_anon */
4738 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4739 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4740 arc_change_state(arc_anon, hdr, hash_lock);
4741 hdr->b_l1hdr.b_arc_access = 0;
4742 mutex_exit(hash_lock);
4744 buf_discard_identity(hdr);
4747 buf->b_efunc = NULL;
4748 buf->b_private = NULL;
4752 arc_released(arc_buf_t *buf)
4756 mutex_enter(&buf->b_evict_lock);
4757 released = (buf->b_data != NULL &&
4758 buf->b_hdr->b_l1hdr.b_state == arc_anon);
4759 mutex_exit(&buf->b_evict_lock);
4765 arc_referenced(arc_buf_t *buf)
4769 mutex_enter(&buf->b_evict_lock);
4770 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4771 mutex_exit(&buf->b_evict_lock);
4772 return (referenced);
4777 arc_write_ready(zio_t *zio)
4779 arc_write_callback_t *callback = zio->io_private;
4780 arc_buf_t *buf = callback->awcb_buf;
4781 arc_buf_hdr_t *hdr = buf->b_hdr;
4783 ASSERT(HDR_HAS_L1HDR(hdr));
4784 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4785 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4786 callback->awcb_ready(zio, buf, callback->awcb_private);
4789 * If the IO is already in progress, then this is a re-write
4790 * attempt, so we need to thaw and re-compute the cksum.
4791 * It is the responsibility of the callback to handle the
4792 * accounting for any re-write attempt.
4794 if (HDR_IO_IN_PROGRESS(hdr)) {
4795 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4796 if (hdr->b_freeze_cksum != NULL) {
4797 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4798 hdr->b_freeze_cksum = NULL;
4800 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4802 arc_cksum_compute(buf, B_FALSE);
4803 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4807 * The SPA calls this callback for each physical write that happens on behalf
4808 * of a logical write. See the comment in dbuf_write_physdone() for details.
4811 arc_write_physdone(zio_t *zio)
4813 arc_write_callback_t *cb = zio->io_private;
4814 if (cb->awcb_physdone != NULL)
4815 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4819 arc_write_done(zio_t *zio)
4821 arc_write_callback_t *callback = zio->io_private;
4822 arc_buf_t *buf = callback->awcb_buf;
4823 arc_buf_hdr_t *hdr = buf->b_hdr;
4825 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4827 if (zio->io_error == 0) {
4828 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4829 buf_discard_identity(hdr);
4831 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4832 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4835 ASSERT(BUF_EMPTY(hdr));
4839 * If the block to be written was all-zero or compressed enough to be
4840 * embedded in the BP, no write was performed so there will be no
4841 * dva/birth/checksum. The buffer must therefore remain anonymous
4844 if (!BUF_EMPTY(hdr)) {
4845 arc_buf_hdr_t *exists;
4846 kmutex_t *hash_lock;
4848 ASSERT(zio->io_error == 0);
4850 arc_cksum_verify(buf);
4852 exists = buf_hash_insert(hdr, &hash_lock);
4853 if (exists != NULL) {
4855 * This can only happen if we overwrite for
4856 * sync-to-convergence, because we remove
4857 * buffers from the hash table when we arc_free().
4859 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4860 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4861 panic("bad overwrite, hdr=%p exists=%p",
4862 (void *)hdr, (void *)exists);
4863 ASSERT(refcount_is_zero(
4864 &exists->b_l1hdr.b_refcnt));
4865 arc_change_state(arc_anon, exists, hash_lock);
4866 mutex_exit(hash_lock);
4867 arc_hdr_destroy(exists);
4868 exists = buf_hash_insert(hdr, &hash_lock);
4869 ASSERT3P(exists, ==, NULL);
4870 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
4872 ASSERT(zio->io_prop.zp_nopwrite);
4873 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4874 panic("bad nopwrite, hdr=%p exists=%p",
4875 (void *)hdr, (void *)exists);
4878 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4879 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
4880 ASSERT(BP_GET_DEDUP(zio->io_bp));
4881 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
4884 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4885 /* if it's not anon, we are doing a scrub */
4886 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
4887 arc_access(hdr, hash_lock);
4888 mutex_exit(hash_lock);
4890 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4893 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4894 callback->awcb_done(zio, buf, callback->awcb_private);
4896 kmem_free(callback, sizeof (arc_write_callback_t));
4900 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4901 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4902 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4903 arc_done_func_t *done, void *private, zio_priority_t priority,
4904 int zio_flags, const zbookmark_phys_t *zb)
4906 arc_buf_hdr_t *hdr = buf->b_hdr;
4907 arc_write_callback_t *callback;
4910 ASSERT(ready != NULL);
4911 ASSERT(done != NULL);
4912 ASSERT(!HDR_IO_ERROR(hdr));
4913 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4914 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4915 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4917 hdr->b_flags |= ARC_FLAG_L2CACHE;
4919 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4920 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4921 callback->awcb_ready = ready;
4922 callback->awcb_physdone = physdone;
4923 callback->awcb_done = done;
4924 callback->awcb_private = private;
4925 callback->awcb_buf = buf;
4927 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4928 arc_write_ready, arc_write_physdone, arc_write_done, callback,
4929 priority, zio_flags, zb);
4935 arc_memory_throttle(uint64_t reserve, uint64_t txg)
4938 uint64_t available_memory = ptob(freemem);
4939 static uint64_t page_load = 0;
4940 static uint64_t last_txg = 0;
4942 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4944 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4947 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4950 if (txg > last_txg) {
4955 * If we are in pageout, we know that memory is already tight,
4956 * the arc is already going to be evicting, so we just want to
4957 * continue to let page writes occur as quickly as possible.
4959 if (curproc == pageproc) {
4960 if (page_load > MAX(ptob(minfree), available_memory) / 4)
4961 return (SET_ERROR(ERESTART));
4962 /* Note: reserve is inflated, so we deflate */
4963 page_load += reserve / 8;
4965 } else if (page_load > 0 && arc_reclaim_needed()) {
4966 /* memory is low, delay before restarting */
4967 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4968 return (SET_ERROR(EAGAIN));
4976 arc_tempreserve_clear(uint64_t reserve)
4978 atomic_add_64(&arc_tempreserve, -reserve);
4979 ASSERT((int64_t)arc_tempreserve >= 0);
4983 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4988 if (reserve > arc_c/4 && !arc_no_grow) {
4989 arc_c = MIN(arc_c_max, reserve * 4);
4990 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4992 if (reserve > arc_c)
4993 return (SET_ERROR(ENOMEM));
4996 * Don't count loaned bufs as in flight dirty data to prevent long
4997 * network delays from blocking transactions that are ready to be
4998 * assigned to a txg.
5000 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
5003 * Writes will, almost always, require additional memory allocations
5004 * in order to compress/encrypt/etc the data. We therefore need to
5005 * make sure that there is sufficient available memory for this.
5007 error = arc_memory_throttle(reserve, txg);
5012 * Throttle writes when the amount of dirty data in the cache
5013 * gets too large. We try to keep the cache less than half full
5014 * of dirty blocks so that our sync times don't grow too large.
5015 * Note: if two requests come in concurrently, we might let them
5016 * both succeed, when one of them should fail. Not a huge deal.
5019 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5020 anon_size > arc_c / 4) {
5021 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5022 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5023 arc_tempreserve>>10,
5024 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5025 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5026 reserve>>10, arc_c>>10);
5027 return (SET_ERROR(ERESTART));
5029 atomic_add_64(&arc_tempreserve, reserve);
5034 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5035 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5037 size->value.ui64 = state->arcs_size;
5038 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5039 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5043 arc_kstat_update(kstat_t *ksp, int rw)
5045 arc_stats_t *as = ksp->ks_data;
5047 if (rw == KSTAT_WRITE) {
5050 arc_kstat_update_state(arc_anon,
5051 &as->arcstat_anon_size,
5052 &as->arcstat_anon_evictable_data,
5053 &as->arcstat_anon_evictable_metadata);
5054 arc_kstat_update_state(arc_mru,
5055 &as->arcstat_mru_size,
5056 &as->arcstat_mru_evictable_data,
5057 &as->arcstat_mru_evictable_metadata);
5058 arc_kstat_update_state(arc_mru_ghost,
5059 &as->arcstat_mru_ghost_size,
5060 &as->arcstat_mru_ghost_evictable_data,
5061 &as->arcstat_mru_ghost_evictable_metadata);
5062 arc_kstat_update_state(arc_mfu,
5063 &as->arcstat_mfu_size,
5064 &as->arcstat_mfu_evictable_data,
5065 &as->arcstat_mfu_evictable_metadata);
5066 arc_kstat_update_state(arc_mfu_ghost,
5067 &as->arcstat_mfu_ghost_size,
5068 &as->arcstat_mfu_ghost_evictable_data,
5069 &as->arcstat_mfu_ghost_evictable_metadata);
5076 * This function *must* return indices evenly distributed between all
5077 * sublists of the multilist. This is needed due to how the ARC eviction
5078 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5079 * distributed between all sublists and uses this assumption when
5080 * deciding which sublist to evict from and how much to evict from it.
5083 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5085 arc_buf_hdr_t *hdr = obj;
5088 * We rely on b_dva to generate evenly distributed index
5089 * numbers using buf_hash below. So, as an added precaution,
5090 * let's make sure we never add empty buffers to the arc lists.
5092 ASSERT(!BUF_EMPTY(hdr));
5095 * The assumption here, is the hash value for a given
5096 * arc_buf_hdr_t will remain constant throughout it's lifetime
5097 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5098 * Thus, we don't need to store the header's sublist index
5099 * on insertion, as this index can be recalculated on removal.
5101 * Also, the low order bits of the hash value are thought to be
5102 * distributed evenly. Otherwise, in the case that the multilist
5103 * has a power of two number of sublists, each sublists' usage
5104 * would not be evenly distributed.
5106 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5107 multilist_get_num_sublists(ml));
5111 static eventhandler_tag arc_event_lowmem = NULL;
5114 arc_lowmem(void *arg __unused, int howto __unused)
5117 mutex_enter(&arc_reclaim_lock);
5118 /* XXX: Memory deficit should be passed as argument. */
5119 needfree = btoc(arc_c >> arc_shrink_shift);
5120 DTRACE_PROBE(arc__needfree);
5121 cv_signal(&arc_reclaim_thread_cv);
5124 * It is unsafe to block here in arbitrary threads, because we can come
5125 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5126 * with ARC reclaim thread.
5128 if (curproc == pageproc)
5129 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5130 mutex_exit(&arc_reclaim_lock);
5137 int i, prefetch_tunable_set = 0;
5139 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5140 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5141 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5143 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5144 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5146 /* Convert seconds to clock ticks */
5147 arc_min_prefetch_lifespan = 1 * hz;
5149 /* Start out with 1/8 of all memory */
5150 arc_c = kmem_size() / 8;
5155 * On architectures where the physical memory can be larger
5156 * than the addressable space (intel in 32-bit mode), we may
5157 * need to limit the cache to 1/8 of VM size.
5159 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5162 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5163 arc_c_min = MAX(arc_c / 4, 16 << 20);
5164 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5165 if (arc_c * 8 >= 1 << 30)
5166 arc_c_max = (arc_c * 8) - (1 << 30);
5168 arc_c_max = arc_c_min;
5169 arc_c_max = MAX(arc_c * 5, arc_c_max);
5173 * Allow the tunables to override our calculations if they are
5174 * reasonable (ie. over 16MB)
5176 if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5177 arc_c_max = zfs_arc_max;
5178 if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5179 arc_c_min = zfs_arc_min;
5183 arc_p = (arc_c >> 1);
5185 /* limit meta-data to 1/4 of the arc capacity */
5186 arc_meta_limit = arc_c_max / 4;
5188 /* Allow the tunable to override if it is reasonable */
5189 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5190 arc_meta_limit = zfs_arc_meta_limit;
5192 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5193 arc_c_min = arc_meta_limit / 2;
5195 if (zfs_arc_meta_min > 0) {
5196 arc_meta_min = zfs_arc_meta_min;
5198 arc_meta_min = arc_c_min / 2;
5201 if (zfs_arc_grow_retry > 0)
5202 arc_grow_retry = zfs_arc_grow_retry;
5204 if (zfs_arc_shrink_shift > 0)
5205 arc_shrink_shift = zfs_arc_shrink_shift;
5208 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5210 if (arc_no_grow_shift >= arc_shrink_shift)
5211 arc_no_grow_shift = arc_shrink_shift - 1;
5213 if (zfs_arc_p_min_shift > 0)
5214 arc_p_min_shift = zfs_arc_p_min_shift;
5216 if (zfs_arc_num_sublists_per_state < 1)
5217 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5219 /* if kmem_flags are set, lets try to use less memory */
5220 if (kmem_debugging())
5222 if (arc_c < arc_c_min)
5225 zfs_arc_min = arc_c_min;
5226 zfs_arc_max = arc_c_max;
5228 arc_anon = &ARC_anon;
5230 arc_mru_ghost = &ARC_mru_ghost;
5232 arc_mfu_ghost = &ARC_mfu_ghost;
5233 arc_l2c_only = &ARC_l2c_only;
5236 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5237 sizeof (arc_buf_hdr_t),
5238 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5239 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5240 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5241 sizeof (arc_buf_hdr_t),
5242 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5243 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5244 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5245 sizeof (arc_buf_hdr_t),
5246 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5247 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5248 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5249 sizeof (arc_buf_hdr_t),
5250 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5251 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5252 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5253 sizeof (arc_buf_hdr_t),
5254 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5255 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5256 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5257 sizeof (arc_buf_hdr_t),
5258 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5259 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5260 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5261 sizeof (arc_buf_hdr_t),
5262 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5263 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5264 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5265 sizeof (arc_buf_hdr_t),
5266 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5267 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5268 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5269 sizeof (arc_buf_hdr_t),
5270 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5271 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5272 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5273 sizeof (arc_buf_hdr_t),
5274 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5275 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5279 arc_reclaim_thread_exit = FALSE;
5280 arc_user_evicts_thread_exit = FALSE;
5281 arc_eviction_list = NULL;
5282 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5284 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5285 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5287 if (arc_ksp != NULL) {
5288 arc_ksp->ks_data = &arc_stats;
5289 arc_ksp->ks_update = arc_kstat_update;
5290 kstat_install(arc_ksp);
5293 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5294 TS_RUN, minclsyspri);
5297 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5298 EVENTHANDLER_PRI_FIRST);
5301 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5302 TS_RUN, minclsyspri);
5308 * Calculate maximum amount of dirty data per pool.
5310 * If it has been set by /etc/system, take that.
5311 * Otherwise, use a percentage of physical memory defined by
5312 * zfs_dirty_data_max_percent (default 10%) with a cap at
5313 * zfs_dirty_data_max_max (default 4GB).
5315 if (zfs_dirty_data_max == 0) {
5316 zfs_dirty_data_max = ptob(physmem) *
5317 zfs_dirty_data_max_percent / 100;
5318 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5319 zfs_dirty_data_max_max);
5323 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5324 prefetch_tunable_set = 1;
5327 if (prefetch_tunable_set == 0) {
5328 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5330 printf(" add \"vfs.zfs.prefetch_disable=0\" "
5331 "to /boot/loader.conf.\n");
5332 zfs_prefetch_disable = 1;
5335 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5336 prefetch_tunable_set == 0) {
5337 printf("ZFS NOTICE: Prefetch is disabled by default if less "
5338 "than 4GB of RAM is present;\n"
5339 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
5340 "to /boot/loader.conf.\n");
5341 zfs_prefetch_disable = 1;
5344 /* Warn about ZFS memory and address space requirements. */
5345 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5346 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5347 "expect unstable behavior.\n");
5349 if (kmem_size() < 512 * (1 << 20)) {
5350 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5351 "expect unstable behavior.\n");
5352 printf(" Consider tuning vm.kmem_size and "
5353 "vm.kmem_size_max\n");
5354 printf(" in /boot/loader.conf.\n");
5362 mutex_enter(&arc_reclaim_lock);
5363 arc_reclaim_thread_exit = TRUE;
5365 * The reclaim thread will set arc_reclaim_thread_exit back to
5366 * FALSE when it is finished exiting; we're waiting for that.
5368 while (arc_reclaim_thread_exit) {
5369 cv_signal(&arc_reclaim_thread_cv);
5370 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5372 mutex_exit(&arc_reclaim_lock);
5374 mutex_enter(&arc_user_evicts_lock);
5375 arc_user_evicts_thread_exit = TRUE;
5377 * The user evicts thread will set arc_user_evicts_thread_exit
5378 * to FALSE when it is finished exiting; we're waiting for that.
5380 while (arc_user_evicts_thread_exit) {
5381 cv_signal(&arc_user_evicts_cv);
5382 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5384 mutex_exit(&arc_user_evicts_lock);
5386 /* Use TRUE to ensure *all* buffers are evicted */
5387 arc_flush(NULL, TRUE);
5391 if (arc_ksp != NULL) {
5392 kstat_delete(arc_ksp);
5396 mutex_destroy(&arc_reclaim_lock);
5397 cv_destroy(&arc_reclaim_thread_cv);
5398 cv_destroy(&arc_reclaim_waiters_cv);
5400 mutex_destroy(&arc_user_evicts_lock);
5401 cv_destroy(&arc_user_evicts_cv);
5403 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5404 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5405 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5406 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5407 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5408 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5409 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5410 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5414 ASSERT0(arc_loaned_bytes);
5417 if (arc_event_lowmem != NULL)
5418 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5425 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5426 * It uses dedicated storage devices to hold cached data, which are populated
5427 * using large infrequent writes. The main role of this cache is to boost
5428 * the performance of random read workloads. The intended L2ARC devices
5429 * include short-stroked disks, solid state disks, and other media with
5430 * substantially faster read latency than disk.
5432 * +-----------------------+
5434 * +-----------------------+
5437 * l2arc_feed_thread() arc_read()
5441 * +---------------+ |
5443 * +---------------+ |
5448 * +-------+ +-------+
5450 * | cache | | cache |
5451 * +-------+ +-------+
5452 * +=========+ .-----.
5453 * : L2ARC : |-_____-|
5454 * : devices : | Disks |
5455 * +=========+ `-_____-'
5457 * Read requests are satisfied from the following sources, in order:
5460 * 2) vdev cache of L2ARC devices
5462 * 4) vdev cache of disks
5465 * Some L2ARC device types exhibit extremely slow write performance.
5466 * To accommodate for this there are some significant differences between
5467 * the L2ARC and traditional cache design:
5469 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5470 * the ARC behave as usual, freeing buffers and placing headers on ghost
5471 * lists. The ARC does not send buffers to the L2ARC during eviction as
5472 * this would add inflated write latencies for all ARC memory pressure.
5474 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5475 * It does this by periodically scanning buffers from the eviction-end of
5476 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5477 * not already there. It scans until a headroom of buffers is satisfied,
5478 * which itself is a buffer for ARC eviction. If a compressible buffer is
5479 * found during scanning and selected for writing to an L2ARC device, we
5480 * temporarily boost scanning headroom during the next scan cycle to make
5481 * sure we adapt to compression effects (which might significantly reduce
5482 * the data volume we write to L2ARC). The thread that does this is
5483 * l2arc_feed_thread(), illustrated below; example sizes are included to
5484 * provide a better sense of ratio than this diagram:
5487 * +---------------------+----------+
5488 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5489 * +---------------------+----------+ | o L2ARC eligible
5490 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5491 * +---------------------+----------+ |
5492 * 15.9 Gbytes ^ 32 Mbytes |
5494 * l2arc_feed_thread()
5496 * l2arc write hand <--[oooo]--'
5500 * +==============================+
5501 * L2ARC dev |####|#|###|###| |####| ... |
5502 * +==============================+
5505 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5506 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5507 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5508 * safe to say that this is an uncommon case, since buffers at the end of
5509 * the ARC lists have moved there due to inactivity.
5511 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5512 * then the L2ARC simply misses copying some buffers. This serves as a
5513 * pressure valve to prevent heavy read workloads from both stalling the ARC
5514 * with waits and clogging the L2ARC with writes. This also helps prevent
5515 * the potential for the L2ARC to churn if it attempts to cache content too
5516 * quickly, such as during backups of the entire pool.
5518 * 5. After system boot and before the ARC has filled main memory, there are
5519 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5520 * lists can remain mostly static. Instead of searching from tail of these
5521 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5522 * for eligible buffers, greatly increasing its chance of finding them.
5524 * The L2ARC device write speed is also boosted during this time so that
5525 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5526 * there are no L2ARC reads, and no fear of degrading read performance
5527 * through increased writes.
5529 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5530 * the vdev queue can aggregate them into larger and fewer writes. Each
5531 * device is written to in a rotor fashion, sweeping writes through
5532 * available space then repeating.
5534 * 7. The L2ARC does not store dirty content. It never needs to flush
5535 * write buffers back to disk based storage.
5537 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5538 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5540 * The performance of the L2ARC can be tweaked by a number of tunables, which
5541 * may be necessary for different workloads:
5543 * l2arc_write_max max write bytes per interval
5544 * l2arc_write_boost extra write bytes during device warmup
5545 * l2arc_noprefetch skip caching prefetched buffers
5546 * l2arc_headroom number of max device writes to precache
5547 * l2arc_headroom_boost when we find compressed buffers during ARC
5548 * scanning, we multiply headroom by this
5549 * percentage factor for the next scan cycle,
5550 * since more compressed buffers are likely to
5552 * l2arc_feed_secs seconds between L2ARC writing
5554 * Tunables may be removed or added as future performance improvements are
5555 * integrated, and also may become zpool properties.
5557 * There are three key functions that control how the L2ARC warms up:
5559 * l2arc_write_eligible() check if a buffer is eligible to cache
5560 * l2arc_write_size() calculate how much to write
5561 * l2arc_write_interval() calculate sleep delay between writes
5563 * These three functions determine what to write, how much, and how quickly
5568 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5571 * A buffer is *not* eligible for the L2ARC if it:
5572 * 1. belongs to a different spa.
5573 * 2. is already cached on the L2ARC.
5574 * 3. has an I/O in progress (it may be an incomplete read).
5575 * 4. is flagged not eligible (zfs property).
5577 if (hdr->b_spa != spa_guid) {
5578 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5581 if (HDR_HAS_L2HDR(hdr)) {
5582 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5585 if (HDR_IO_IN_PROGRESS(hdr)) {
5586 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5589 if (!HDR_L2CACHE(hdr)) {
5590 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5598 l2arc_write_size(void)
5603 * Make sure our globals have meaningful values in case the user
5606 size = l2arc_write_max;
5608 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5609 "be greater than zero, resetting it to the default (%d)",
5611 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5614 if (arc_warm == B_FALSE)
5615 size += l2arc_write_boost;
5622 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5624 clock_t interval, next, now;
5627 * If the ARC lists are busy, increase our write rate; if the
5628 * lists are stale, idle back. This is achieved by checking
5629 * how much we previously wrote - if it was more than half of
5630 * what we wanted, schedule the next write much sooner.
5632 if (l2arc_feed_again && wrote > (wanted / 2))
5633 interval = (hz * l2arc_feed_min_ms) / 1000;
5635 interval = hz * l2arc_feed_secs;
5637 now = ddi_get_lbolt();
5638 next = MAX(now, MIN(now + interval, began + interval));
5644 * Cycle through L2ARC devices. This is how L2ARC load balances.
5645 * If a device is returned, this also returns holding the spa config lock.
5647 static l2arc_dev_t *
5648 l2arc_dev_get_next(void)
5650 l2arc_dev_t *first, *next = NULL;
5653 * Lock out the removal of spas (spa_namespace_lock), then removal
5654 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5655 * both locks will be dropped and a spa config lock held instead.
5657 mutex_enter(&spa_namespace_lock);
5658 mutex_enter(&l2arc_dev_mtx);
5660 /* if there are no vdevs, there is nothing to do */
5661 if (l2arc_ndev == 0)
5665 next = l2arc_dev_last;
5667 /* loop around the list looking for a non-faulted vdev */
5669 next = list_head(l2arc_dev_list);
5671 next = list_next(l2arc_dev_list, next);
5673 next = list_head(l2arc_dev_list);
5676 /* if we have come back to the start, bail out */
5679 else if (next == first)
5682 } while (vdev_is_dead(next->l2ad_vdev));
5684 /* if we were unable to find any usable vdevs, return NULL */
5685 if (vdev_is_dead(next->l2ad_vdev))
5688 l2arc_dev_last = next;
5691 mutex_exit(&l2arc_dev_mtx);
5694 * Grab the config lock to prevent the 'next' device from being
5695 * removed while we are writing to it.
5698 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5699 mutex_exit(&spa_namespace_lock);
5705 * Free buffers that were tagged for destruction.
5708 l2arc_do_free_on_write()
5711 l2arc_data_free_t *df, *df_prev;
5713 mutex_enter(&l2arc_free_on_write_mtx);
5714 buflist = l2arc_free_on_write;
5716 for (df = list_tail(buflist); df; df = df_prev) {
5717 df_prev = list_prev(buflist, df);
5718 ASSERT(df->l2df_data != NULL);
5719 ASSERT(df->l2df_func != NULL);
5720 df->l2df_func(df->l2df_data, df->l2df_size);
5721 list_remove(buflist, df);
5722 kmem_free(df, sizeof (l2arc_data_free_t));
5725 mutex_exit(&l2arc_free_on_write_mtx);
5729 * A write to a cache device has completed. Update all headers to allow
5730 * reads from these buffers to begin.
5733 l2arc_write_done(zio_t *zio)
5735 l2arc_write_callback_t *cb;
5738 arc_buf_hdr_t *head, *hdr, *hdr_prev;
5739 kmutex_t *hash_lock;
5740 int64_t bytes_dropped = 0;
5742 cb = zio->io_private;
5744 dev = cb->l2wcb_dev;
5745 ASSERT(dev != NULL);
5746 head = cb->l2wcb_head;
5747 ASSERT(head != NULL);
5748 buflist = &dev->l2ad_buflist;
5749 ASSERT(buflist != NULL);
5750 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5751 l2arc_write_callback_t *, cb);
5753 if (zio->io_error != 0)
5754 ARCSTAT_BUMP(arcstat_l2_writes_error);
5757 * All writes completed, or an error was hit.
5760 mutex_enter(&dev->l2ad_mtx);
5761 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5762 hdr_prev = list_prev(buflist, hdr);
5764 hash_lock = HDR_LOCK(hdr);
5767 * We cannot use mutex_enter or else we can deadlock
5768 * with l2arc_write_buffers (due to swapping the order
5769 * the hash lock and l2ad_mtx are taken).
5771 if (!mutex_tryenter(hash_lock)) {
5773 * Missed the hash lock. We must retry so we
5774 * don't leave the ARC_FLAG_L2_WRITING bit set.
5776 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5779 * We don't want to rescan the headers we've
5780 * already marked as having been written out, so
5781 * we reinsert the head node so we can pick up
5782 * where we left off.
5784 list_remove(buflist, head);
5785 list_insert_after(buflist, hdr, head);
5787 mutex_exit(&dev->l2ad_mtx);
5790 * We wait for the hash lock to become available
5791 * to try and prevent busy waiting, and increase
5792 * the chance we'll be able to acquire the lock
5793 * the next time around.
5795 mutex_enter(hash_lock);
5796 mutex_exit(hash_lock);
5801 * We could not have been moved into the arc_l2c_only
5802 * state while in-flight due to our ARC_FLAG_L2_WRITING
5803 * bit being set. Let's just ensure that's being enforced.
5805 ASSERT(HDR_HAS_L1HDR(hdr));
5808 * We may have allocated a buffer for L2ARC compression,
5809 * we must release it to avoid leaking this data.
5811 l2arc_release_cdata_buf(hdr);
5813 if (zio->io_error != 0) {
5815 * Error - drop L2ARC entry.
5817 trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
5818 hdr->b_l2hdr.b_daddr, hdr->b_l2hdr.b_asize, 0);
5819 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5821 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5822 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5824 bytes_dropped += hdr->b_l2hdr.b_asize;
5825 (void) refcount_remove_many(&dev->l2ad_alloc,
5826 hdr->b_l2hdr.b_asize, hdr);
5830 * Allow ARC to begin reads and ghost list evictions to
5833 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5835 mutex_exit(hash_lock);
5838 atomic_inc_64(&l2arc_writes_done);
5839 list_remove(buflist, head);
5840 ASSERT(!HDR_HAS_L1HDR(head));
5841 kmem_cache_free(hdr_l2only_cache, head);
5842 mutex_exit(&dev->l2ad_mtx);
5844 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5846 l2arc_do_free_on_write();
5848 kmem_free(cb, sizeof (l2arc_write_callback_t));
5852 * A read to a cache device completed. Validate buffer contents before
5853 * handing over to the regular ARC routines.
5856 l2arc_read_done(zio_t *zio)
5858 l2arc_read_callback_t *cb;
5861 kmutex_t *hash_lock;
5864 ASSERT(zio->io_vd != NULL);
5865 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
5867 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
5869 cb = zio->io_private;
5871 buf = cb->l2rcb_buf;
5872 ASSERT(buf != NULL);
5874 hash_lock = HDR_LOCK(buf->b_hdr);
5875 mutex_enter(hash_lock);
5877 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5880 * If the buffer was compressed, decompress it first.
5882 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
5883 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
5884 ASSERT(zio->io_data != NULL);
5887 * Check this survived the L2ARC journey.
5889 equal = arc_cksum_equal(buf);
5890 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
5891 mutex_exit(hash_lock);
5892 zio->io_private = buf;
5893 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
5894 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
5897 mutex_exit(hash_lock);
5899 * Buffer didn't survive caching. Increment stats and
5900 * reissue to the original storage device.
5902 if (zio->io_error != 0) {
5903 ARCSTAT_BUMP(arcstat_l2_io_error);
5905 zio->io_error = SET_ERROR(EIO);
5908 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
5911 * If there's no waiter, issue an async i/o to the primary
5912 * storage now. If there *is* a waiter, the caller must
5913 * issue the i/o in a context where it's OK to block.
5915 if (zio->io_waiter == NULL) {
5916 zio_t *pio = zio_unique_parent(zio);
5918 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
5920 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
5921 buf->b_data, zio->io_size, arc_read_done, buf,
5922 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
5926 kmem_free(cb, sizeof (l2arc_read_callback_t));
5930 * This is the list priority from which the L2ARC will search for pages to
5931 * cache. This is used within loops (0..3) to cycle through lists in the
5932 * desired order. This order can have a significant effect on cache
5935 * Currently the metadata lists are hit first, MFU then MRU, followed by
5936 * the data lists. This function returns a locked list, and also returns
5939 static multilist_sublist_t *
5940 l2arc_sublist_lock(int list_num)
5942 multilist_t *ml = NULL;
5945 ASSERT(list_num >= 0 && list_num <= 3);
5949 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
5952 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
5955 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
5958 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
5963 * Return a randomly-selected sublist. This is acceptable
5964 * because the caller feeds only a little bit of data for each
5965 * call (8MB). Subsequent calls will result in different
5966 * sublists being selected.
5968 idx = multilist_get_random_index(ml);
5969 return (multilist_sublist_lock(ml, idx));
5973 * Evict buffers from the device write hand to the distance specified in
5974 * bytes. This distance may span populated buffers, it may span nothing.
5975 * This is clearing a region on the L2ARC device ready for writing.
5976 * If the 'all' boolean is set, every buffer is evicted.
5979 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
5982 arc_buf_hdr_t *hdr, *hdr_prev;
5983 kmutex_t *hash_lock;
5986 buflist = &dev->l2ad_buflist;
5988 if (!all && dev->l2ad_first) {
5990 * This is the first sweep through the device. There is
5996 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
5998 * When nearing the end of the device, evict to the end
5999 * before the device write hand jumps to the start.
6001 taddr = dev->l2ad_end;
6003 taddr = dev->l2ad_hand + distance;
6005 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6006 uint64_t, taddr, boolean_t, all);
6009 mutex_enter(&dev->l2ad_mtx);
6010 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6011 hdr_prev = list_prev(buflist, hdr);
6013 hash_lock = HDR_LOCK(hdr);
6016 * We cannot use mutex_enter or else we can deadlock
6017 * with l2arc_write_buffers (due to swapping the order
6018 * the hash lock and l2ad_mtx are taken).
6020 if (!mutex_tryenter(hash_lock)) {
6022 * Missed the hash lock. Retry.
6024 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6025 mutex_exit(&dev->l2ad_mtx);
6026 mutex_enter(hash_lock);
6027 mutex_exit(hash_lock);
6031 if (HDR_L2_WRITE_HEAD(hdr)) {
6033 * We hit a write head node. Leave it for
6034 * l2arc_write_done().
6036 list_remove(buflist, hdr);
6037 mutex_exit(hash_lock);
6041 if (!all && HDR_HAS_L2HDR(hdr) &&
6042 (hdr->b_l2hdr.b_daddr > taddr ||
6043 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6045 * We've evicted to the target address,
6046 * or the end of the device.
6048 mutex_exit(hash_lock);
6052 ASSERT(HDR_HAS_L2HDR(hdr));
6053 if (!HDR_HAS_L1HDR(hdr)) {
6054 ASSERT(!HDR_L2_READING(hdr));
6056 * This doesn't exist in the ARC. Destroy.
6057 * arc_hdr_destroy() will call list_remove()
6058 * and decrement arcstat_l2_size.
6060 arc_change_state(arc_anon, hdr, hash_lock);
6061 arc_hdr_destroy(hdr);
6063 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6064 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6066 * Invalidate issued or about to be issued
6067 * reads, since we may be about to write
6068 * over this location.
6070 if (HDR_L2_READING(hdr)) {
6071 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6072 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6075 /* Ensure this header has finished being written */
6076 ASSERT(!HDR_L2_WRITING(hdr));
6077 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6079 arc_hdr_l2hdr_destroy(hdr);
6081 mutex_exit(hash_lock);
6083 mutex_exit(&dev->l2ad_mtx);
6087 * Find and write ARC buffers to the L2ARC device.
6089 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6090 * for reading until they have completed writing.
6091 * The headroom_boost is an in-out parameter used to maintain headroom boost
6092 * state between calls to this function.
6094 * Returns the number of bytes actually written (which may be smaller than
6095 * the delta by which the device hand has changed due to alignment).
6098 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6099 boolean_t *headroom_boost)
6101 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6102 uint64_t write_asize, write_sz, headroom, buf_compress_minsz;
6105 l2arc_write_callback_t *cb;
6107 uint64_t guid = spa_load_guid(spa);
6108 const boolean_t do_headroom_boost = *headroom_boost;
6111 ASSERT(dev->l2ad_vdev != NULL);
6113 /* Lower the flag now, we might want to raise it again later. */
6114 *headroom_boost = B_FALSE;
6117 write_sz = write_asize = 0;
6119 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6120 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6121 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6123 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6125 * We will want to try to compress buffers that are at least 2x the
6126 * device sector size.
6128 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6131 * Copy buffers for L2ARC writing.
6133 for (try = 0; try <= 3; try++) {
6134 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6135 uint64_t passed_sz = 0;
6137 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6140 * L2ARC fast warmup.
6142 * Until the ARC is warm and starts to evict, read from the
6143 * head of the ARC lists rather than the tail.
6145 if (arc_warm == B_FALSE)
6146 hdr = multilist_sublist_head(mls);
6148 hdr = multilist_sublist_tail(mls);
6150 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6152 headroom = target_sz * l2arc_headroom;
6153 if (do_headroom_boost)
6154 headroom = (headroom * l2arc_headroom_boost) / 100;
6156 for (; hdr; hdr = hdr_prev) {
6157 kmutex_t *hash_lock;
6161 if (arc_warm == B_FALSE)
6162 hdr_prev = multilist_sublist_next(mls, hdr);
6164 hdr_prev = multilist_sublist_prev(mls, hdr);
6165 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6167 hash_lock = HDR_LOCK(hdr);
6168 if (!mutex_tryenter(hash_lock)) {
6169 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6171 * Skip this buffer rather than waiting.
6176 passed_sz += hdr->b_size;
6177 if (passed_sz > headroom) {
6181 mutex_exit(hash_lock);
6182 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6186 if (!l2arc_write_eligible(guid, hdr)) {
6187 mutex_exit(hash_lock);
6192 * Assume that the buffer is not going to be compressed
6193 * and could take more space on disk because of a larger
6196 buf_sz = hdr->b_size;
6197 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6199 if ((write_asize + buf_a_sz) > target_sz) {
6201 mutex_exit(hash_lock);
6202 ARCSTAT_BUMP(arcstat_l2_write_full);
6208 * Insert a dummy header on the buflist so
6209 * l2arc_write_done() can find where the
6210 * write buffers begin without searching.
6212 mutex_enter(&dev->l2ad_mtx);
6213 list_insert_head(&dev->l2ad_buflist, head);
6214 mutex_exit(&dev->l2ad_mtx);
6217 sizeof (l2arc_write_callback_t), KM_SLEEP);
6218 cb->l2wcb_dev = dev;
6219 cb->l2wcb_head = head;
6220 pio = zio_root(spa, l2arc_write_done, cb,
6222 ARCSTAT_BUMP(arcstat_l2_write_pios);
6226 * Create and add a new L2ARC header.
6228 hdr->b_l2hdr.b_dev = dev;
6229 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6231 * Temporarily stash the data buffer in b_tmp_cdata.
6232 * The subsequent write step will pick it up from
6233 * there. This is because can't access b_l1hdr.b_buf
6234 * without holding the hash_lock, which we in turn
6235 * can't access without holding the ARC list locks
6236 * (which we want to avoid during compression/writing).
6238 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
6239 hdr->b_l2hdr.b_asize = hdr->b_size;
6240 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6243 * Explicitly set the b_daddr field to a known
6244 * value which means "invalid address". This
6245 * enables us to differentiate which stage of
6246 * l2arc_write_buffers() the particular header
6247 * is in (e.g. this loop, or the one below).
6248 * ARC_FLAG_L2_WRITING is not enough to make
6249 * this distinction, and we need to know in
6250 * order to do proper l2arc vdev accounting in
6251 * arc_release() and arc_hdr_destroy().
6253 * Note, we can't use a new flag to distinguish
6254 * the two stages because we don't hold the
6255 * header's hash_lock below, in the second stage
6256 * of this function. Thus, we can't simply
6257 * change the b_flags field to denote that the
6258 * IO has been sent. We can change the b_daddr
6259 * field of the L2 portion, though, since we'll
6260 * be holding the l2ad_mtx; which is why we're
6261 * using it to denote the header's state change.
6263 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6264 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6266 mutex_enter(&dev->l2ad_mtx);
6267 list_insert_head(&dev->l2ad_buflist, hdr);
6268 mutex_exit(&dev->l2ad_mtx);
6271 * Compute and store the buffer cksum before
6272 * writing. On debug the cksum is verified first.
6274 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6275 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6277 mutex_exit(hash_lock);
6280 write_asize += buf_a_sz;
6283 multilist_sublist_unlock(mls);
6289 /* No buffers selected for writing? */
6292 ASSERT(!HDR_HAS_L1HDR(head));
6293 kmem_cache_free(hdr_l2only_cache, head);
6297 mutex_enter(&dev->l2ad_mtx);
6300 * Note that elsewhere in this file arcstat_l2_asize
6301 * and the used space on l2ad_vdev are updated using b_asize,
6302 * which is not necessarily rounded up to the device block size.
6303 * Too keep accounting consistent we do the same here as well:
6304 * stats_size accumulates the sum of b_asize of the written buffers,
6305 * while write_asize accumulates the sum of b_asize rounded up
6306 * to the device block size.
6307 * The latter sum is used only to validate the corectness of the code.
6309 uint64_t stats_size = 0;
6313 * Now start writing the buffers. We're starting at the write head
6314 * and work backwards, retracing the course of the buffer selector
6317 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6318 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6322 * We rely on the L1 portion of the header below, so
6323 * it's invalid for this header to have been evicted out
6324 * of the ghost cache, prior to being written out. The
6325 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6327 ASSERT(HDR_HAS_L1HDR(hdr));
6330 * We shouldn't need to lock the buffer here, since we flagged
6331 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6332 * take care to only access its L2 cache parameters. In
6333 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6336 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6338 if ((HDR_L2COMPRESS(hdr)) &&
6339 hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6340 if (l2arc_compress_buf(hdr)) {
6342 * If compression succeeded, enable headroom
6343 * boost on the next scan cycle.
6345 *headroom_boost = B_TRUE;
6350 * Pick up the buffer data we had previously stashed away
6351 * (and now potentially also compressed).
6353 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6354 buf_sz = hdr->b_l2hdr.b_asize;
6357 * If the data has not been compressed, then clear b_tmp_cdata
6358 * to make sure that it points only to a temporary compression
6361 if (!L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)))
6362 hdr->b_l1hdr.b_tmp_cdata = NULL;
6365 * We need to do this regardless if buf_sz is zero or
6366 * not, otherwise, when this l2hdr is evicted we'll
6367 * remove a reference that was never added.
6369 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6371 /* Compression may have squashed the buffer to zero length. */
6375 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6376 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6377 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6378 ZIO_FLAG_CANFAIL, B_FALSE);
6380 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6382 (void) zio_nowait(wzio);
6384 stats_size += buf_sz;
6387 * Keep the clock hand suitably device-aligned.
6389 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6390 write_asize += buf_a_sz;
6391 dev->l2ad_hand += buf_a_sz;
6395 mutex_exit(&dev->l2ad_mtx);
6397 ASSERT3U(write_asize, <=, target_sz);
6398 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6399 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6400 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6401 ARCSTAT_INCR(arcstat_l2_asize, stats_size);
6402 vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
6405 * Bump device hand to the device start if it is approaching the end.
6406 * l2arc_evict() will already have evicted ahead for this case.
6408 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6409 dev->l2ad_hand = dev->l2ad_start;
6410 dev->l2ad_first = B_FALSE;
6413 dev->l2ad_writing = B_TRUE;
6414 (void) zio_wait(pio);
6415 dev->l2ad_writing = B_FALSE;
6417 return (write_asize);
6421 * Compresses an L2ARC buffer.
6422 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6423 * size in l2hdr->b_asize. This routine tries to compress the data and
6424 * depending on the compression result there are three possible outcomes:
6425 * *) The buffer was incompressible. The original l2hdr contents were left
6426 * untouched and are ready for writing to an L2 device.
6427 * *) The buffer was all-zeros, so there is no need to write it to an L2
6428 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6429 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6430 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6431 * data buffer which holds the compressed data to be written, and b_asize
6432 * tells us how much data there is. b_compress is set to the appropriate
6433 * compression algorithm. Once writing is done, invoke
6434 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6436 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6437 * buffer was incompressible).
6440 l2arc_compress_buf(arc_buf_hdr_t *hdr)
6443 size_t csize, len, rounded;
6444 ASSERT(HDR_HAS_L2HDR(hdr));
6445 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6447 ASSERT(HDR_HAS_L1HDR(hdr));
6448 ASSERT(HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF);
6449 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6451 len = l2hdr->b_asize;
6452 cdata = zio_data_buf_alloc(len);
6453 ASSERT3P(cdata, !=, NULL);
6454 csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6455 cdata, l2hdr->b_asize);
6458 /* zero block, indicate that there's nothing to write */
6459 zio_data_buf_free(cdata, len);
6460 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_EMPTY);
6462 hdr->b_l1hdr.b_tmp_cdata = NULL;
6463 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6467 rounded = P2ROUNDUP(csize,
6468 (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
6469 if (rounded < len) {
6471 * Compression succeeded, we'll keep the cdata around for
6472 * writing and release it afterwards.
6474 if (rounded > csize) {
6475 bzero((char *)cdata + csize, rounded - csize);
6478 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_LZ4);
6479 l2hdr->b_asize = csize;
6480 hdr->b_l1hdr.b_tmp_cdata = cdata;
6481 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6485 * Compression failed, release the compressed buffer.
6486 * l2hdr will be left unmodified.
6488 zio_data_buf_free(cdata, len);
6489 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6495 * Decompresses a zio read back from an l2arc device. On success, the
6496 * underlying zio's io_data buffer is overwritten by the uncompressed
6497 * version. On decompression error (corrupt compressed stream), the
6498 * zio->io_error value is set to signal an I/O error.
6500 * Please note that the compressed data stream is not checksummed, so
6501 * if the underlying device is experiencing data corruption, we may feed
6502 * corrupt data to the decompressor, so the decompressor needs to be
6503 * able to handle this situation (LZ4 does).
6506 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6508 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6510 if (zio->io_error != 0) {
6512 * An io error has occured, just restore the original io
6513 * size in preparation for a main pool read.
6515 zio->io_orig_size = zio->io_size = hdr->b_size;
6519 if (c == ZIO_COMPRESS_EMPTY) {
6521 * An empty buffer results in a null zio, which means we
6522 * need to fill its io_data after we're done restoring the
6523 * buffer's contents.
6525 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6526 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6527 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6529 ASSERT(zio->io_data != NULL);
6531 * We copy the compressed data from the start of the arc buffer
6532 * (the zio_read will have pulled in only what we need, the
6533 * rest is garbage which we will overwrite at decompression)
6534 * and then decompress back to the ARC data buffer. This way we
6535 * can minimize copying by simply decompressing back over the
6536 * original compressed data (rather than decompressing to an
6537 * aux buffer and then copying back the uncompressed buffer,
6538 * which is likely to be much larger).
6543 csize = zio->io_size;
6544 cdata = zio_data_buf_alloc(csize);
6545 bcopy(zio->io_data, cdata, csize);
6546 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6548 zio->io_error = EIO;
6549 zio_data_buf_free(cdata, csize);
6552 /* Restore the expected uncompressed IO size. */
6553 zio->io_orig_size = zio->io_size = hdr->b_size;
6557 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6558 * This buffer serves as a temporary holder of compressed data while
6559 * the buffer entry is being written to an l2arc device. Once that is
6560 * done, we can dispose of it.
6563 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6565 enum zio_compress comp = HDR_GET_COMPRESS(hdr);
6567 ASSERT(HDR_HAS_L1HDR(hdr));
6568 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6570 if (comp == ZIO_COMPRESS_OFF) {
6572 * In this case, b_tmp_cdata points to the same buffer
6573 * as the arc_buf_t's b_data field. We don't want to
6574 * free it, since the arc_buf_t will handle that.
6576 hdr->b_l1hdr.b_tmp_cdata = NULL;
6577 } else if (comp == ZIO_COMPRESS_EMPTY) {
6579 * In this case, b_tmp_cdata was compressed to an empty
6580 * buffer, thus there's nothing to free and b_tmp_cdata
6581 * should have been set to NULL in l2arc_write_buffers().
6583 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6586 * If the data was compressed, then we've allocated a
6587 * temporary buffer for it, so now we need to release it.
6589 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6590 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6592 hdr->b_l1hdr.b_tmp_cdata = NULL;
6597 * This thread feeds the L2ARC at regular intervals. This is the beating
6598 * heart of the L2ARC.
6601 l2arc_feed_thread(void *dummy __unused)
6606 uint64_t size, wrote;
6607 clock_t begin, next = ddi_get_lbolt();
6608 boolean_t headroom_boost = B_FALSE;
6610 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6612 mutex_enter(&l2arc_feed_thr_lock);
6614 while (l2arc_thread_exit == 0) {
6615 CALLB_CPR_SAFE_BEGIN(&cpr);
6616 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6617 next - ddi_get_lbolt());
6618 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6619 next = ddi_get_lbolt() + hz;
6622 * Quick check for L2ARC devices.
6624 mutex_enter(&l2arc_dev_mtx);
6625 if (l2arc_ndev == 0) {
6626 mutex_exit(&l2arc_dev_mtx);
6629 mutex_exit(&l2arc_dev_mtx);
6630 begin = ddi_get_lbolt();
6633 * This selects the next l2arc device to write to, and in
6634 * doing so the next spa to feed from: dev->l2ad_spa. This
6635 * will return NULL if there are now no l2arc devices or if
6636 * they are all faulted.
6638 * If a device is returned, its spa's config lock is also
6639 * held to prevent device removal. l2arc_dev_get_next()
6640 * will grab and release l2arc_dev_mtx.
6642 if ((dev = l2arc_dev_get_next()) == NULL)
6645 spa = dev->l2ad_spa;
6646 ASSERT(spa != NULL);
6649 * If the pool is read-only then force the feed thread to
6650 * sleep a little longer.
6652 if (!spa_writeable(spa)) {
6653 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6654 spa_config_exit(spa, SCL_L2ARC, dev);
6659 * Avoid contributing to memory pressure.
6661 if (arc_reclaim_needed()) {
6662 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6663 spa_config_exit(spa, SCL_L2ARC, dev);
6667 ARCSTAT_BUMP(arcstat_l2_feeds);
6669 size = l2arc_write_size();
6672 * Evict L2ARC buffers that will be overwritten.
6674 l2arc_evict(dev, size, B_FALSE);
6677 * Write ARC buffers.
6679 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6682 * Calculate interval between writes.
6684 next = l2arc_write_interval(begin, size, wrote);
6685 spa_config_exit(spa, SCL_L2ARC, dev);
6688 l2arc_thread_exit = 0;
6689 cv_broadcast(&l2arc_feed_thr_cv);
6690 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6695 l2arc_vdev_present(vdev_t *vd)
6699 mutex_enter(&l2arc_dev_mtx);
6700 for (dev = list_head(l2arc_dev_list); dev != NULL;
6701 dev = list_next(l2arc_dev_list, dev)) {
6702 if (dev->l2ad_vdev == vd)
6705 mutex_exit(&l2arc_dev_mtx);
6707 return (dev != NULL);
6711 * Add a vdev for use by the L2ARC. By this point the spa has already
6712 * validated the vdev and opened it.
6715 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6717 l2arc_dev_t *adddev;
6719 ASSERT(!l2arc_vdev_present(vd));
6721 vdev_ashift_optimize(vd);
6724 * Create a new l2arc device entry.
6726 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6727 adddev->l2ad_spa = spa;
6728 adddev->l2ad_vdev = vd;
6729 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6730 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6731 adddev->l2ad_hand = adddev->l2ad_start;
6732 adddev->l2ad_first = B_TRUE;
6733 adddev->l2ad_writing = B_FALSE;
6735 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6737 * This is a list of all ARC buffers that are still valid on the
6740 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6741 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6743 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6744 refcount_create(&adddev->l2ad_alloc);
6747 * Add device to global list
6749 mutex_enter(&l2arc_dev_mtx);
6750 list_insert_head(l2arc_dev_list, adddev);
6751 atomic_inc_64(&l2arc_ndev);
6752 mutex_exit(&l2arc_dev_mtx);
6756 * Remove a vdev from the L2ARC.
6759 l2arc_remove_vdev(vdev_t *vd)
6761 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6764 * Find the device by vdev
6766 mutex_enter(&l2arc_dev_mtx);
6767 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6768 nextdev = list_next(l2arc_dev_list, dev);
6769 if (vd == dev->l2ad_vdev) {
6774 ASSERT(remdev != NULL);
6777 * Remove device from global list
6779 list_remove(l2arc_dev_list, remdev);
6780 l2arc_dev_last = NULL; /* may have been invalidated */
6781 atomic_dec_64(&l2arc_ndev);
6782 mutex_exit(&l2arc_dev_mtx);
6785 * Clear all buflists and ARC references. L2ARC device flush.
6787 l2arc_evict(remdev, 0, B_TRUE);
6788 list_destroy(&remdev->l2ad_buflist);
6789 mutex_destroy(&remdev->l2ad_mtx);
6790 refcount_destroy(&remdev->l2ad_alloc);
6791 kmem_free(remdev, sizeof (l2arc_dev_t));
6797 l2arc_thread_exit = 0;
6799 l2arc_writes_sent = 0;
6800 l2arc_writes_done = 0;
6802 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6803 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6804 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6805 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6807 l2arc_dev_list = &L2ARC_dev_list;
6808 l2arc_free_on_write = &L2ARC_free_on_write;
6809 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6810 offsetof(l2arc_dev_t, l2ad_node));
6811 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6812 offsetof(l2arc_data_free_t, l2df_list_node));
6819 * This is called from dmu_fini(), which is called from spa_fini();
6820 * Because of this, we can assume that all l2arc devices have
6821 * already been removed when the pools themselves were removed.
6824 l2arc_do_free_on_write();
6826 mutex_destroy(&l2arc_feed_thr_lock);
6827 cv_destroy(&l2arc_feed_thr_cv);
6828 mutex_destroy(&l2arc_dev_mtx);
6829 mutex_destroy(&l2arc_free_on_write_mtx);
6831 list_destroy(l2arc_dev_list);
6832 list_destroy(l2arc_free_on_write);
6838 if (!(spa_mode_global & FWRITE))
6841 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6842 TS_RUN, minclsyspri);
6848 if (!(spa_mode_global & FWRITE))
6851 mutex_enter(&l2arc_feed_thr_lock);
6852 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
6853 l2arc_thread_exit = 1;
6854 while (l2arc_thread_exit != 0)
6855 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6856 mutex_exit(&l2arc_feed_thr_lock);