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) 2018, Joyent, Inc.
24 * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2017 Nexenta Systems, Inc. All rights reserved.
30 * DVA-based Adjustable Replacement Cache
32 * While much of the theory of operation used here is
33 * based on the self-tuning, low overhead replacement cache
34 * presented by Megiddo and Modha at FAST 2003, there are some
35 * significant differences:
37 * 1. The Megiddo and Modha model assumes any page is evictable.
38 * Pages in its cache cannot be "locked" into memory. This makes
39 * the eviction algorithm simple: evict the last page in the list.
40 * This also make the performance characteristics easy to reason
41 * about. Our cache is not so simple. At any given moment, some
42 * subset of the blocks in the cache are un-evictable because we
43 * have handed out a reference to them. Blocks are only evictable
44 * when there are no external references active. This makes
45 * eviction far more problematic: we choose to evict the evictable
46 * blocks that are the "lowest" in the list.
48 * There are times when it is not possible to evict the requested
49 * space. In these circumstances we are unable to adjust the cache
50 * size. To prevent the cache growing unbounded at these times we
51 * implement a "cache throttle" that slows the flow of new data
52 * into the cache until we can make space available.
54 * 2. The Megiddo and Modha model assumes a fixed cache size.
55 * Pages are evicted when the cache is full and there is a cache
56 * miss. Our model has a variable sized cache. It grows with
57 * high use, but also tries to react to memory pressure from the
58 * operating system: decreasing its size when system memory is
61 * 3. The Megiddo and Modha model assumes a fixed page size. All
62 * elements of the cache are therefore exactly the same size. So
63 * when adjusting the cache size following a cache miss, its simply
64 * a matter of choosing a single page to evict. In our model, we
65 * have variable sized cache blocks (rangeing from 512 bytes to
66 * 128K bytes). We therefore choose a set of blocks to evict to make
67 * space for a cache miss that approximates as closely as possible
68 * the space used by the new block.
70 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71 * by N. Megiddo & D. Modha, FAST 2003
77 * A new reference to a cache buffer can be obtained in two
78 * ways: 1) via a hash table lookup using the DVA as a key,
79 * or 2) via one of the ARC lists. The arc_read() interface
80 * uses method 1, while the internal ARC algorithms for
81 * adjusting the cache use method 2. We therefore provide two
82 * types of locks: 1) the hash table lock array, and 2) the
85 * Buffers do not have their own mutexes, rather they rely on the
86 * hash table mutexes for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexes).
89 * buf_hash_find() returns the appropriate mutex (held) when it
90 * locates the requested buffer in the hash table. It returns
91 * NULL for the mutex if the buffer was not in the table.
93 * buf_hash_remove() expects the appropriate hash mutex to be
94 * already held before it is invoked.
96 * Each ARC state also has a mutex which is used to protect the
97 * buffer list associated with the state. When attempting to
98 * obtain a hash table lock while holding an ARC list lock you
99 * must use: mutex_tryenter() to avoid deadlock. Also note that
100 * the active state mutex must be held before the ghost state mutex.
102 * It as also possible to register a callback which is run when the
103 * arc_meta_limit is reached and no buffers can be safely evicted. In
104 * this case the arc user should drop a reference on some arc buffers so
105 * they can be reclaimed and the arc_meta_limit honored. For example,
106 * when using the ZPL each dentry holds a references on a znode. These
107 * dentries must be pruned before the arc buffer holding the znode can
110 * Note that the majority of the performance stats are manipulated
111 * with atomic operations.
113 * The L2ARC uses the l2ad_mtx on each vdev for the following:
115 * - L2ARC buflist creation
116 * - L2ARC buflist eviction
117 * - L2ARC write completion, which walks L2ARC buflists
118 * - ARC header destruction, as it removes from L2ARC buflists
119 * - ARC header release, as it removes from L2ARC buflists
125 * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
126 * This structure can point either to a block that is still in the cache or to
127 * one that is only accessible in an L2 ARC device, or it can provide
128 * information about a block that was recently evicted. If a block is
129 * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
130 * information to retrieve it from the L2ARC device. This information is
131 * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
132 * that is in this state cannot access the data directly.
134 * Blocks that are actively being referenced or have not been evicted
135 * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
136 * the arc_buf_hdr_t that will point to the data block in memory. A block can
137 * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
138 * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
139 * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
141 * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
142 * ability to store the physical data (b_pabd) associated with the DVA of the
143 * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
144 * it will match its on-disk compression characteristics. This behavior can be
145 * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
146 * compressed ARC functionality is disabled, the b_pabd will point to an
147 * uncompressed version of the on-disk data.
149 * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
150 * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
151 * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
152 * consumer. The ARC will provide references to this data and will keep it
153 * cached until it is no longer in use. The ARC caches only the L1ARC's physical
154 * data block and will evict any arc_buf_t that is no longer referenced. The
155 * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
156 * "overhead_size" kstat.
158 * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
159 * compressed form. The typical case is that consumers will want uncompressed
160 * data, and when that happens a new data buffer is allocated where the data is
161 * decompressed for them to use. Currently the only consumer who wants
162 * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
163 * exists on disk. When this happens, the arc_buf_t's data buffer is shared
164 * with the arc_buf_hdr_t.
166 * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
167 * first one is owned by a compressed send consumer (and therefore references
168 * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
169 * used by any other consumer (and has its own uncompressed copy of the data
184 * | b_buf +------------>+-----------+ arc_buf_t
185 * | b_pabd +-+ |b_next +---->+-----------+
186 * +-----------+ | |-----------| |b_next +-->NULL
187 * | |b_comp = T | +-----------+
188 * | |b_data +-+ |b_comp = F |
189 * | +-----------+ | |b_data +-+
190 * +->+------+ | +-----------+ |
192 * data | |<--------------+ | uncompressed
193 * +------+ compressed, | data
194 * shared +-->+------+
199 * When a consumer reads a block, the ARC must first look to see if the
200 * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
201 * arc_buf_t and either copies uncompressed data into a new data buffer from an
202 * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
203 * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
204 * hdr is compressed and the desired compression characteristics of the
205 * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
206 * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
207 * the last buffer in the hdr's b_buf list, however a shared compressed buf can
208 * be anywhere in the hdr's list.
210 * The diagram below shows an example of an uncompressed ARC hdr that is
211 * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
212 * the last element in the buf list):
224 * | | arc_buf_t (shared)
225 * | b_buf +------------>+---------+ arc_buf_t
226 * | | |b_next +---->+---------+
227 * | b_pabd +-+ |---------| |b_next +-->NULL
228 * +-----------+ | | | +---------+
230 * | +---------+ | |b_data +-+
231 * +->+------+ | +---------+ |
233 * uncompressed | | | |
236 * | uncompressed | | |
239 * +---------------------------------+
241 * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
242 * since the physical block is about to be rewritten. The new data contents
243 * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
244 * it may compress the data before writing it to disk. The ARC will be called
245 * with the transformed data and will bcopy the transformed on-disk block into
246 * a newly allocated b_pabd. Writes are always done into buffers which have
247 * either been loaned (and hence are new and don't have other readers) or
248 * buffers which have been released (and hence have their own hdr, if there
249 * were originally other readers of the buf's original hdr). This ensures that
250 * the ARC only needs to update a single buf and its hdr after a write occurs.
252 * When the L2ARC is in use, it will also take advantage of the b_pabd. The
253 * L2ARC will always write the contents of b_pabd to the L2ARC. This means
254 * that when compressed ARC is enabled that the L2ARC blocks are identical
255 * to the on-disk block in the main data pool. This provides a significant
256 * advantage since the ARC can leverage the bp's checksum when reading from the
257 * L2ARC to determine if the contents are valid. However, if the compressed
258 * ARC is disabled, then the L2ARC's block must be transformed to look
259 * like the physical block in the main data pool before comparing the
260 * checksum and determining its validity.
265 #include <sys/spa_impl.h>
266 #include <sys/zio_compress.h>
267 #include <sys/zio_checksum.h>
268 #include <sys/zfs_context.h>
270 #include <sys/refcount.h>
271 #include <sys/vdev.h>
272 #include <sys/vdev_impl.h>
273 #include <sys/dsl_pool.h>
274 #include <sys/zio_checksum.h>
275 #include <sys/multilist.h>
278 #include <sys/dnlc.h>
279 #include <sys/racct.h>
281 #include <sys/callb.h>
282 #include <sys/kstat.h>
283 #include <sys/trim_map.h>
284 #include <sys/zthr.h>
285 #include <zfs_fletcher.h>
287 #include <sys/aggsum.h>
288 #include <sys/cityhash.h>
290 #include <machine/vmparam.h>
294 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
295 boolean_t arc_watch = B_FALSE;
301 * This thread's job is to keep enough free memory in the system, by
302 * calling arc_kmem_reap_now() plus arc_shrink(), which improves
303 * arc_available_memory().
305 static zthr_t *arc_reap_zthr;
308 * This thread's job is to keep arc_size under arc_c, by calling
309 * arc_adjust(), which improves arc_is_overflowing().
311 static zthr_t *arc_adjust_zthr;
313 static kmutex_t arc_adjust_lock;
314 static kcondvar_t arc_adjust_waiters_cv;
315 static boolean_t arc_adjust_needed = B_FALSE;
317 static kmutex_t arc_dnlc_evicts_lock;
318 static kcondvar_t arc_dnlc_evicts_cv;
319 static boolean_t arc_dnlc_evicts_thread_exit;
321 uint_t arc_reduce_dnlc_percent = 3;
324 * The number of headers to evict in arc_evict_state_impl() before
325 * dropping the sublist lock and evicting from another sublist. A lower
326 * value means we're more likely to evict the "correct" header (i.e. the
327 * oldest header in the arc state), but comes with higher overhead
328 * (i.e. more invocations of arc_evict_state_impl()).
330 int zfs_arc_evict_batch_limit = 10;
332 /* number of seconds before growing cache again */
333 int arc_grow_retry = 60;
336 * Minimum time between calls to arc_kmem_reap_soon(). Note that this will
337 * be converted to ticks, so with the default hz=100, a setting of 15 ms
338 * will actually wait 2 ticks, or 20ms.
340 int arc_kmem_cache_reap_retry_ms = 1000;
342 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
343 int zfs_arc_overflow_shift = 8;
345 /* shift of arc_c for calculating both min and max arc_p */
346 int arc_p_min_shift = 4;
348 /* log2(fraction of arc to reclaim) */
349 int arc_shrink_shift = 7;
352 * log2(fraction of ARC which must be free to allow growing).
353 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
354 * when reading a new block into the ARC, we will evict an equal-sized block
357 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
358 * we will still not allow it to grow.
360 int arc_no_grow_shift = 5;
364 * minimum lifespan of a prefetch block in clock ticks
365 * (initialized in arc_init())
367 static int zfs_arc_min_prefetch_ms = 1;
368 static int zfs_arc_min_prescient_prefetch_ms = 6;
371 * If this percent of memory is free, don't throttle.
373 int arc_lotsfree_percent = 10;
375 static boolean_t arc_initialized;
376 extern boolean_t zfs_prefetch_disable;
379 * The arc has filled available memory and has now warmed up.
381 static boolean_t arc_warm;
384 * log2 fraction of the zio arena to keep free.
386 int arc_zio_arena_free_shift = 2;
389 * These tunables are for performance analysis.
391 uint64_t zfs_arc_max;
392 uint64_t zfs_arc_min;
393 uint64_t zfs_arc_meta_limit = 0;
394 uint64_t zfs_arc_meta_min = 0;
395 uint64_t zfs_arc_dnode_limit = 0;
396 uint64_t zfs_arc_dnode_reduce_percent = 10;
397 int zfs_arc_grow_retry = 0;
398 int zfs_arc_shrink_shift = 0;
399 int zfs_arc_no_grow_shift = 0;
400 int zfs_arc_p_min_shift = 0;
401 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
402 u_int zfs_arc_free_target = 0;
404 /* Absolute min for arc min / max is 16MB. */
405 static uint64_t arc_abs_min = 16 << 20;
408 * ARC dirty data constraints for arc_tempreserve_space() throttle
410 uint_t zfs_arc_dirty_limit_percent = 50; /* total dirty data limit */
411 uint_t zfs_arc_anon_limit_percent = 25; /* anon block dirty limit */
412 uint_t zfs_arc_pool_dirty_percent = 20; /* each pool's anon allowance */
414 boolean_t zfs_compressed_arc_enabled = B_TRUE;
416 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
417 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
418 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
419 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
420 static int sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS);
422 #if defined(__FreeBSD__) && defined(_KERNEL)
424 arc_free_target_init(void *unused __unused)
427 zfs_arc_free_target = vm_cnt.v_free_target;
429 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
430 arc_free_target_init, NULL);
432 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
433 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
434 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
435 TUNABLE_INT("vfs.zfs.arc_grow_retry", &zfs_arc_grow_retry);
436 TUNABLE_INT("vfs.zfs.arc_no_grow_shift", &zfs_arc_no_grow_shift);
437 SYSCTL_DECL(_vfs_zfs);
438 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
439 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
440 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
441 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
442 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_no_grow_shift, CTLTYPE_U32 | CTLFLAG_RWTUN,
443 0, sizeof(uint32_t), sysctl_vfs_zfs_arc_no_grow_shift, "U",
444 "log2(fraction of ARC which must be free to allow growing)");
445 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
446 &zfs_arc_average_blocksize, 0,
447 "ARC average blocksize");
448 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
449 &arc_shrink_shift, 0,
450 "log2(fraction of arc to reclaim)");
451 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_grow_retry, CTLFLAG_RW,
453 "Wait in seconds before considering growing ARC");
454 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
455 &zfs_compressed_arc_enabled, 0,
456 "Enable compressed ARC");
457 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_kmem_cache_reap_retry_ms, CTLFLAG_RWTUN,
458 &arc_kmem_cache_reap_retry_ms, 0,
459 "Interval between ARC kmem_cache reapings");
462 * We don't have a tunable for arc_free_target due to the dependency on
463 * pagedaemon initialisation.
465 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
466 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
467 sysctl_vfs_zfs_arc_free_target, "IU",
468 "Desired number of free pages below which ARC triggers reclaim");
471 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
476 val = zfs_arc_free_target;
477 err = sysctl_handle_int(oidp, &val, 0, req);
478 if (err != 0 || req->newptr == NULL)
483 if (val > vm_cnt.v_page_count)
486 zfs_arc_free_target = val;
492 * Must be declared here, before the definition of corresponding kstat
493 * macro which uses the same names will confuse the compiler.
495 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
496 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
497 sysctl_vfs_zfs_arc_meta_limit, "QU",
498 "ARC metadata limit");
502 * Note that buffers can be in one of 6 states:
503 * ARC_anon - anonymous (discussed below)
504 * ARC_mru - recently used, currently cached
505 * ARC_mru_ghost - recentely used, no longer in cache
506 * ARC_mfu - frequently used, currently cached
507 * ARC_mfu_ghost - frequently used, no longer in cache
508 * ARC_l2c_only - exists in L2ARC but not other states
509 * When there are no active references to the buffer, they are
510 * are linked onto a list in one of these arc states. These are
511 * the only buffers that can be evicted or deleted. Within each
512 * state there are multiple lists, one for meta-data and one for
513 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
514 * etc.) is tracked separately so that it can be managed more
515 * explicitly: favored over data, limited explicitly.
517 * Anonymous buffers are buffers that are not associated with
518 * a DVA. These are buffers that hold dirty block copies
519 * before they are written to stable storage. By definition,
520 * they are "ref'd" and are considered part of arc_mru
521 * that cannot be freed. Generally, they will aquire a DVA
522 * as they are written and migrate onto the arc_mru list.
524 * The ARC_l2c_only state is for buffers that are in the second
525 * level ARC but no longer in any of the ARC_m* lists. The second
526 * level ARC itself may also contain buffers that are in any of
527 * the ARC_m* states - meaning that a buffer can exist in two
528 * places. The reason for the ARC_l2c_only state is to keep the
529 * buffer header in the hash table, so that reads that hit the
530 * second level ARC benefit from these fast lookups.
533 typedef struct arc_state {
535 * list of evictable buffers
537 multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
539 * total amount of evictable data in this state
541 zfs_refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
543 * total amount of data in this state; this includes: evictable,
544 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
546 zfs_refcount_t arcs_size;
548 * supports the "dbufs" kstat
550 arc_state_type_t arcs_state;
554 * Percentage that can be consumed by dnodes of ARC meta buffers.
556 int zfs_arc_meta_prune = 10000;
557 unsigned long zfs_arc_dnode_limit_percent = 10;
558 int zfs_arc_meta_strategy = ARC_STRATEGY_META_ONLY;
559 int zfs_arc_meta_adjust_restarts = 4096;
561 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_meta_strategy, CTLFLAG_RWTUN,
562 &zfs_arc_meta_strategy, 0,
563 "ARC metadata reclamation strategy "
564 "(0 = metadata only, 1 = balance data and metadata)");
567 static arc_state_t ARC_anon;
568 static arc_state_t ARC_mru;
569 static arc_state_t ARC_mru_ghost;
570 static arc_state_t ARC_mfu;
571 static arc_state_t ARC_mfu_ghost;
572 static arc_state_t ARC_l2c_only;
574 typedef struct arc_stats {
575 kstat_named_t arcstat_hits;
576 kstat_named_t arcstat_misses;
577 kstat_named_t arcstat_demand_data_hits;
578 kstat_named_t arcstat_demand_data_misses;
579 kstat_named_t arcstat_demand_metadata_hits;
580 kstat_named_t arcstat_demand_metadata_misses;
581 kstat_named_t arcstat_prefetch_data_hits;
582 kstat_named_t arcstat_prefetch_data_misses;
583 kstat_named_t arcstat_prefetch_metadata_hits;
584 kstat_named_t arcstat_prefetch_metadata_misses;
585 kstat_named_t arcstat_mru_hits;
586 kstat_named_t arcstat_mru_ghost_hits;
587 kstat_named_t arcstat_mfu_hits;
588 kstat_named_t arcstat_mfu_ghost_hits;
589 kstat_named_t arcstat_allocated;
590 kstat_named_t arcstat_deleted;
592 * Number of buffers that could not be evicted because the hash lock
593 * was held by another thread. The lock may not necessarily be held
594 * by something using the same buffer, since hash locks are shared
595 * by multiple buffers.
597 kstat_named_t arcstat_mutex_miss;
599 * Number of buffers skipped when updating the access state due to the
600 * header having already been released after acquiring the hash lock.
602 kstat_named_t arcstat_access_skip;
604 * Number of buffers skipped because they have I/O in progress, are
605 * indirect prefetch buffers that have not lived long enough, or are
606 * not from the spa we're trying to evict from.
608 kstat_named_t arcstat_evict_skip;
610 * Number of times arc_evict_state() was unable to evict enough
611 * buffers to reach it's target amount.
613 kstat_named_t arcstat_evict_not_enough;
614 kstat_named_t arcstat_evict_l2_cached;
615 kstat_named_t arcstat_evict_l2_eligible;
616 kstat_named_t arcstat_evict_l2_ineligible;
617 kstat_named_t arcstat_evict_l2_skip;
618 kstat_named_t arcstat_hash_elements;
619 kstat_named_t arcstat_hash_elements_max;
620 kstat_named_t arcstat_hash_collisions;
621 kstat_named_t arcstat_hash_chains;
622 kstat_named_t arcstat_hash_chain_max;
623 kstat_named_t arcstat_p;
624 kstat_named_t arcstat_c;
625 kstat_named_t arcstat_c_min;
626 kstat_named_t arcstat_c_max;
627 /* Not updated directly; only synced in arc_kstat_update. */
628 kstat_named_t arcstat_size;
630 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
631 * Note that the compressed bytes may match the uncompressed bytes
632 * if the block is either not compressed or compressed arc is disabled.
634 kstat_named_t arcstat_compressed_size;
636 * Uncompressed size of the data stored in b_pabd. If compressed
637 * arc is disabled then this value will be identical to the stat
640 kstat_named_t arcstat_uncompressed_size;
642 * Number of bytes stored in all the arc_buf_t's. This is classified
643 * as "overhead" since this data is typically short-lived and will
644 * be evicted from the arc when it becomes unreferenced unless the
645 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
646 * values have been set (see comment in dbuf.c for more information).
648 kstat_named_t arcstat_overhead_size;
650 * Number of bytes consumed by internal ARC structures necessary
651 * for tracking purposes; these structures are not actually
652 * backed by ARC buffers. This includes arc_buf_hdr_t structures
653 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
654 * caches), and arc_buf_t structures (allocated via arc_buf_t
656 * Not updated directly; only synced in arc_kstat_update.
658 kstat_named_t arcstat_hdr_size;
660 * Number of bytes consumed by ARC buffers of type equal to
661 * ARC_BUFC_DATA. This is generally consumed by buffers backing
662 * on disk user data (e.g. plain file contents).
663 * Not updated directly; only synced in arc_kstat_update.
665 kstat_named_t arcstat_data_size;
667 * Number of bytes consumed by ARC buffers of type equal to
668 * ARC_BUFC_METADATA. This is generally consumed by buffers
669 * backing on disk data that is used for internal ZFS
670 * structures (e.g. ZAP, dnode, indirect blocks, etc).
671 * Not updated directly; only synced in arc_kstat_update.
673 kstat_named_t arcstat_metadata_size;
675 * Number of bytes consumed by dmu_buf_impl_t objects.
677 kstat_named_t arcstat_dbuf_size;
679 * Number of bytes consumed by dnode_t objects.
681 kstat_named_t arcstat_dnode_size;
683 * Number of bytes consumed by bonus buffers.
685 kstat_named_t arcstat_bonus_size;
686 #if defined(__FreeBSD__) && defined(COMPAT_FREEBSD11)
688 * Sum of the previous three counters, provided for compatibility.
690 kstat_named_t arcstat_other_size;
693 * Total number of bytes consumed by ARC buffers residing in the
694 * arc_anon state. This includes *all* buffers in the arc_anon
695 * state; e.g. data, metadata, evictable, and unevictable buffers
696 * are all included in this value.
697 * Not updated directly; only synced in arc_kstat_update.
699 kstat_named_t arcstat_anon_size;
701 * Number of bytes consumed by ARC buffers that meet the
702 * following criteria: backing buffers of type ARC_BUFC_DATA,
703 * residing in the arc_anon state, and are eligible for eviction
704 * (e.g. have no outstanding holds on the buffer).
705 * Not updated directly; only synced in arc_kstat_update.
707 kstat_named_t arcstat_anon_evictable_data;
709 * Number of bytes consumed by ARC buffers that meet the
710 * following criteria: backing buffers of type ARC_BUFC_METADATA,
711 * residing in the arc_anon state, and are eligible for eviction
712 * (e.g. have no outstanding holds on the buffer).
713 * Not updated directly; only synced in arc_kstat_update.
715 kstat_named_t arcstat_anon_evictable_metadata;
717 * Total number of bytes consumed by ARC buffers residing in the
718 * arc_mru state. This includes *all* buffers in the arc_mru
719 * state; e.g. data, metadata, evictable, and unevictable buffers
720 * are all included in this value.
721 * Not updated directly; only synced in arc_kstat_update.
723 kstat_named_t arcstat_mru_size;
725 * Number of bytes consumed by ARC buffers that meet the
726 * following criteria: backing buffers of type ARC_BUFC_DATA,
727 * residing in the arc_mru state, and are eligible for eviction
728 * (e.g. have no outstanding holds on the buffer).
729 * Not updated directly; only synced in arc_kstat_update.
731 kstat_named_t arcstat_mru_evictable_data;
733 * Number of bytes consumed by ARC buffers that meet the
734 * following criteria: backing buffers of type ARC_BUFC_METADATA,
735 * residing in the arc_mru state, and are eligible for eviction
736 * (e.g. have no outstanding holds on the buffer).
737 * Not updated directly; only synced in arc_kstat_update.
739 kstat_named_t arcstat_mru_evictable_metadata;
741 * Total number of bytes that *would have been* consumed by ARC
742 * buffers in the arc_mru_ghost state. The key thing to note
743 * here, is the fact that this size doesn't actually indicate
744 * RAM consumption. The ghost lists only consist of headers and
745 * don't actually have ARC buffers linked off of these headers.
746 * Thus, *if* the headers had associated ARC buffers, these
747 * buffers *would have* consumed this number of bytes.
748 * Not updated directly; only synced in arc_kstat_update.
750 kstat_named_t arcstat_mru_ghost_size;
752 * Number of bytes that *would have been* consumed by ARC
753 * buffers that are eligible for eviction, of type
754 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
755 * Not updated directly; only synced in arc_kstat_update.
757 kstat_named_t arcstat_mru_ghost_evictable_data;
759 * Number of bytes that *would have been* consumed by ARC
760 * buffers that are eligible for eviction, of type
761 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
762 * Not updated directly; only synced in arc_kstat_update.
764 kstat_named_t arcstat_mru_ghost_evictable_metadata;
766 * Total number of bytes consumed by ARC buffers residing in the
767 * arc_mfu state. This includes *all* buffers in the arc_mfu
768 * state; e.g. data, metadata, evictable, and unevictable buffers
769 * are all included in this value.
770 * Not updated directly; only synced in arc_kstat_update.
772 kstat_named_t arcstat_mfu_size;
774 * Number of bytes consumed by ARC buffers that are eligible for
775 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
777 * Not updated directly; only synced in arc_kstat_update.
779 kstat_named_t arcstat_mfu_evictable_data;
781 * Number of bytes consumed by ARC buffers that are eligible for
782 * eviction, of type ARC_BUFC_METADATA, and reside in the
784 * Not updated directly; only synced in arc_kstat_update.
786 kstat_named_t arcstat_mfu_evictable_metadata;
788 * Total number of bytes that *would have been* consumed by ARC
789 * buffers in the arc_mfu_ghost state. See the comment above
790 * arcstat_mru_ghost_size for more details.
791 * Not updated directly; only synced in arc_kstat_update.
793 kstat_named_t arcstat_mfu_ghost_size;
795 * Number of bytes that *would have been* consumed by ARC
796 * buffers that are eligible for eviction, of type
797 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
798 * Not updated directly; only synced in arc_kstat_update.
800 kstat_named_t arcstat_mfu_ghost_evictable_data;
802 * Number of bytes that *would have been* consumed by ARC
803 * buffers that are eligible for eviction, of type
804 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
805 * Not updated directly; only synced in arc_kstat_update.
807 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
808 kstat_named_t arcstat_l2_hits;
809 kstat_named_t arcstat_l2_misses;
810 kstat_named_t arcstat_l2_feeds;
811 kstat_named_t arcstat_l2_rw_clash;
812 kstat_named_t arcstat_l2_read_bytes;
813 kstat_named_t arcstat_l2_write_bytes;
814 kstat_named_t arcstat_l2_writes_sent;
815 kstat_named_t arcstat_l2_writes_done;
816 kstat_named_t arcstat_l2_writes_error;
817 kstat_named_t arcstat_l2_writes_lock_retry;
818 kstat_named_t arcstat_l2_evict_lock_retry;
819 kstat_named_t arcstat_l2_evict_reading;
820 kstat_named_t arcstat_l2_evict_l1cached;
821 kstat_named_t arcstat_l2_free_on_write;
822 kstat_named_t arcstat_l2_abort_lowmem;
823 kstat_named_t arcstat_l2_cksum_bad;
824 kstat_named_t arcstat_l2_io_error;
825 kstat_named_t arcstat_l2_lsize;
826 kstat_named_t arcstat_l2_psize;
827 /* Not updated directly; only synced in arc_kstat_update. */
828 kstat_named_t arcstat_l2_hdr_size;
829 kstat_named_t arcstat_l2_write_trylock_fail;
830 kstat_named_t arcstat_l2_write_passed_headroom;
831 kstat_named_t arcstat_l2_write_spa_mismatch;
832 kstat_named_t arcstat_l2_write_in_l2;
833 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
834 kstat_named_t arcstat_l2_write_not_cacheable;
835 kstat_named_t arcstat_l2_write_full;
836 kstat_named_t arcstat_l2_write_buffer_iter;
837 kstat_named_t arcstat_l2_write_pios;
838 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
839 kstat_named_t arcstat_l2_write_buffer_list_iter;
840 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
841 kstat_named_t arcstat_memory_throttle_count;
842 kstat_named_t arcstat_memory_direct_count;
843 kstat_named_t arcstat_memory_indirect_count;
844 kstat_named_t arcstat_memory_all_bytes;
845 kstat_named_t arcstat_memory_free_bytes;
846 kstat_named_t arcstat_memory_available_bytes;
847 kstat_named_t arcstat_no_grow;
848 kstat_named_t arcstat_tempreserve;
849 kstat_named_t arcstat_loaned_bytes;
850 kstat_named_t arcstat_prune;
851 /* Not updated directly; only synced in arc_kstat_update. */
852 kstat_named_t arcstat_meta_used;
853 kstat_named_t arcstat_meta_limit;
854 kstat_named_t arcstat_dnode_limit;
855 kstat_named_t arcstat_meta_max;
856 kstat_named_t arcstat_meta_min;
857 kstat_named_t arcstat_async_upgrade_sync;
858 kstat_named_t arcstat_demand_hit_predictive_prefetch;
859 kstat_named_t arcstat_demand_hit_prescient_prefetch;
862 static arc_stats_t arc_stats = {
863 { "hits", KSTAT_DATA_UINT64 },
864 { "misses", KSTAT_DATA_UINT64 },
865 { "demand_data_hits", KSTAT_DATA_UINT64 },
866 { "demand_data_misses", KSTAT_DATA_UINT64 },
867 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
868 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
869 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
870 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
871 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
872 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
873 { "mru_hits", KSTAT_DATA_UINT64 },
874 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
875 { "mfu_hits", KSTAT_DATA_UINT64 },
876 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
877 { "allocated", KSTAT_DATA_UINT64 },
878 { "deleted", KSTAT_DATA_UINT64 },
879 { "mutex_miss", KSTAT_DATA_UINT64 },
880 { "access_skip", KSTAT_DATA_UINT64 },
881 { "evict_skip", KSTAT_DATA_UINT64 },
882 { "evict_not_enough", KSTAT_DATA_UINT64 },
883 { "evict_l2_cached", KSTAT_DATA_UINT64 },
884 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
885 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
886 { "evict_l2_skip", KSTAT_DATA_UINT64 },
887 { "hash_elements", KSTAT_DATA_UINT64 },
888 { "hash_elements_max", KSTAT_DATA_UINT64 },
889 { "hash_collisions", KSTAT_DATA_UINT64 },
890 { "hash_chains", KSTAT_DATA_UINT64 },
891 { "hash_chain_max", KSTAT_DATA_UINT64 },
892 { "p", KSTAT_DATA_UINT64 },
893 { "c", KSTAT_DATA_UINT64 },
894 { "c_min", KSTAT_DATA_UINT64 },
895 { "c_max", KSTAT_DATA_UINT64 },
896 { "size", KSTAT_DATA_UINT64 },
897 { "compressed_size", KSTAT_DATA_UINT64 },
898 { "uncompressed_size", KSTAT_DATA_UINT64 },
899 { "overhead_size", KSTAT_DATA_UINT64 },
900 { "hdr_size", KSTAT_DATA_UINT64 },
901 { "data_size", KSTAT_DATA_UINT64 },
902 { "metadata_size", KSTAT_DATA_UINT64 },
903 { "dbuf_size", KSTAT_DATA_UINT64 },
904 { "dnode_size", KSTAT_DATA_UINT64 },
905 { "bonus_size", KSTAT_DATA_UINT64 },
906 #if defined(__FreeBSD__) && defined(COMPAT_FREEBSD11)
907 { "other_size", KSTAT_DATA_UINT64 },
909 { "anon_size", KSTAT_DATA_UINT64 },
910 { "anon_evictable_data", KSTAT_DATA_UINT64 },
911 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
912 { "mru_size", KSTAT_DATA_UINT64 },
913 { "mru_evictable_data", KSTAT_DATA_UINT64 },
914 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
915 { "mru_ghost_size", KSTAT_DATA_UINT64 },
916 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
917 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
918 { "mfu_size", KSTAT_DATA_UINT64 },
919 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
920 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
921 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
922 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
923 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
924 { "l2_hits", KSTAT_DATA_UINT64 },
925 { "l2_misses", KSTAT_DATA_UINT64 },
926 { "l2_feeds", KSTAT_DATA_UINT64 },
927 { "l2_rw_clash", KSTAT_DATA_UINT64 },
928 { "l2_read_bytes", KSTAT_DATA_UINT64 },
929 { "l2_write_bytes", KSTAT_DATA_UINT64 },
930 { "l2_writes_sent", KSTAT_DATA_UINT64 },
931 { "l2_writes_done", KSTAT_DATA_UINT64 },
932 { "l2_writes_error", KSTAT_DATA_UINT64 },
933 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
934 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
935 { "l2_evict_reading", KSTAT_DATA_UINT64 },
936 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
937 { "l2_free_on_write", KSTAT_DATA_UINT64 },
938 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
939 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
940 { "l2_io_error", KSTAT_DATA_UINT64 },
941 { "l2_size", KSTAT_DATA_UINT64 },
942 { "l2_asize", KSTAT_DATA_UINT64 },
943 { "l2_hdr_size", KSTAT_DATA_UINT64 },
944 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
945 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
946 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
947 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
948 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
949 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
950 { "l2_write_full", KSTAT_DATA_UINT64 },
951 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
952 { "l2_write_pios", KSTAT_DATA_UINT64 },
953 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
954 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
955 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
956 { "memory_throttle_count", KSTAT_DATA_UINT64 },
957 { "memory_direct_count", KSTAT_DATA_UINT64 },
958 { "memory_indirect_count", KSTAT_DATA_UINT64 },
959 { "memory_all_bytes", KSTAT_DATA_UINT64 },
960 { "memory_free_bytes", KSTAT_DATA_UINT64 },
961 { "memory_available_bytes", KSTAT_DATA_UINT64 },
962 { "arc_no_grow", KSTAT_DATA_UINT64 },
963 { "arc_tempreserve", KSTAT_DATA_UINT64 },
964 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
965 { "arc_prune", KSTAT_DATA_UINT64 },
966 { "arc_meta_used", KSTAT_DATA_UINT64 },
967 { "arc_meta_limit", KSTAT_DATA_UINT64 },
968 { "arc_dnode_limit", KSTAT_DATA_UINT64 },
969 { "arc_meta_max", KSTAT_DATA_UINT64 },
970 { "arc_meta_min", KSTAT_DATA_UINT64 },
971 { "async_upgrade_sync", KSTAT_DATA_UINT64 },
972 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
973 { "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
976 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
978 #define ARCSTAT_INCR(stat, val) \
979 atomic_add_64(&arc_stats.stat.value.ui64, (val))
981 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
982 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
984 #define ARCSTAT_MAX(stat, val) { \
986 while ((val) > (m = arc_stats.stat.value.ui64) && \
987 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
991 #define ARCSTAT_MAXSTAT(stat) \
992 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
995 * We define a macro to allow ARC hits/misses to be easily broken down by
996 * two separate conditions, giving a total of four different subtypes for
997 * each of hits and misses (so eight statistics total).
999 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
1002 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
1004 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
1008 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
1010 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
1015 static arc_state_t *arc_anon;
1016 static arc_state_t *arc_mru;
1017 static arc_state_t *arc_mru_ghost;
1018 static arc_state_t *arc_mfu;
1019 static arc_state_t *arc_mfu_ghost;
1020 static arc_state_t *arc_l2c_only;
1023 * There are several ARC variables that are critical to export as kstats --
1024 * but we don't want to have to grovel around in the kstat whenever we wish to
1025 * manipulate them. For these variables, we therefore define them to be in
1026 * terms of the statistic variable. This assures that we are not introducing
1027 * the possibility of inconsistency by having shadow copies of the variables,
1028 * while still allowing the code to be readable.
1030 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
1031 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
1032 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
1033 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
1034 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
1035 #define arc_dnode_limit ARCSTAT(arcstat_dnode_limit) /* max size for dnodes */
1036 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
1037 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
1038 #define arc_dbuf_size ARCSTAT(arcstat_dbuf_size) /* dbuf metadata */
1039 #define arc_dnode_size ARCSTAT(arcstat_dnode_size) /* dnode metadata */
1040 #define arc_bonus_size ARCSTAT(arcstat_bonus_size) /* bonus buffer metadata */
1042 /* compressed size of entire arc */
1043 #define arc_compressed_size ARCSTAT(arcstat_compressed_size)
1044 /* uncompressed size of entire arc */
1045 #define arc_uncompressed_size ARCSTAT(arcstat_uncompressed_size)
1046 /* number of bytes in the arc from arc_buf_t's */
1047 #define arc_overhead_size ARCSTAT(arcstat_overhead_size)
1050 * There are also some ARC variables that we want to export, but that are
1051 * updated so often that having the canonical representation be the statistic
1052 * variable causes a performance bottleneck. We want to use aggsum_t's for these
1053 * instead, but still be able to export the kstat in the same way as before.
1054 * The solution is to always use the aggsum version, except in the kstat update
1058 aggsum_t arc_meta_used;
1059 aggsum_t astat_data_size;
1060 aggsum_t astat_metadata_size;
1061 aggsum_t astat_hdr_size;
1062 aggsum_t astat_bonus_size;
1063 aggsum_t astat_dnode_size;
1064 aggsum_t astat_dbuf_size;
1065 aggsum_t astat_l2_hdr_size;
1067 static list_t arc_prune_list;
1068 static kmutex_t arc_prune_mtx;
1069 static taskq_t *arc_prune_taskq;
1071 static int arc_no_grow; /* Don't try to grow cache size */
1072 static hrtime_t arc_growtime;
1073 static uint64_t arc_tempreserve;
1074 static uint64_t arc_loaned_bytes;
1076 typedef struct arc_callback arc_callback_t;
1078 struct arc_callback {
1080 arc_read_done_func_t *acb_done;
1082 boolean_t acb_compressed;
1083 zio_t *acb_zio_dummy;
1084 zio_t *acb_zio_head;
1085 arc_callback_t *acb_next;
1088 typedef struct arc_write_callback arc_write_callback_t;
1090 struct arc_write_callback {
1092 arc_write_done_func_t *awcb_ready;
1093 arc_write_done_func_t *awcb_children_ready;
1094 arc_write_done_func_t *awcb_physdone;
1095 arc_write_done_func_t *awcb_done;
1096 arc_buf_t *awcb_buf;
1100 * ARC buffers are separated into multiple structs as a memory saving measure:
1101 * - Common fields struct, always defined, and embedded within it:
1102 * - L2-only fields, always allocated but undefined when not in L2ARC
1103 * - L1-only fields, only allocated when in L1ARC
1105 * Buffer in L1 Buffer only in L2
1106 * +------------------------+ +------------------------+
1107 * | arc_buf_hdr_t | | arc_buf_hdr_t |
1111 * +------------------------+ +------------------------+
1112 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
1113 * | (undefined if L1-only) | | |
1114 * +------------------------+ +------------------------+
1115 * | l1arc_buf_hdr_t |
1120 * +------------------------+
1122 * Because it's possible for the L2ARC to become extremely large, we can wind
1123 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
1124 * is minimized by only allocating the fields necessary for an L1-cached buffer
1125 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
1126 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
1127 * words in pointers. arc_hdr_realloc() is used to switch a header between
1128 * these two allocation states.
1130 typedef struct l1arc_buf_hdr {
1131 kmutex_t b_freeze_lock;
1132 zio_cksum_t *b_freeze_cksum;
1135 * Used for debugging with kmem_flags - by allocating and freeing
1136 * b_thawed when the buffer is thawed, we get a record of the stack
1137 * trace that thawed it.
1144 /* for waiting on writes to complete */
1148 /* protected by arc state mutex */
1149 arc_state_t *b_state;
1150 multilist_node_t b_arc_node;
1152 /* updated atomically */
1153 clock_t b_arc_access;
1154 uint32_t b_mru_hits;
1155 uint32_t b_mru_ghost_hits;
1156 uint32_t b_mfu_hits;
1157 uint32_t b_mfu_ghost_hits;
1160 /* self protecting */
1161 zfs_refcount_t b_refcnt;
1163 arc_callback_t *b_acb;
1167 typedef struct l2arc_dev l2arc_dev_t;
1169 typedef struct l2arc_buf_hdr {
1170 /* protected by arc_buf_hdr mutex */
1171 l2arc_dev_t *b_dev; /* L2ARC device */
1172 uint64_t b_daddr; /* disk address, offset byte */
1175 list_node_t b_l2node;
1178 struct arc_buf_hdr {
1179 /* protected by hash lock */
1183 arc_buf_contents_t b_type;
1184 arc_buf_hdr_t *b_hash_next;
1185 arc_flags_t b_flags;
1188 * This field stores the size of the data buffer after
1189 * compression, and is set in the arc's zio completion handlers.
1190 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1192 * While the block pointers can store up to 32MB in their psize
1193 * field, we can only store up to 32MB minus 512B. This is due
1194 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1195 * a field of zeros represents 512B in the bp). We can't use a
1196 * bias of 1 since we need to reserve a psize of zero, here, to
1197 * represent holes and embedded blocks.
1199 * This isn't a problem in practice, since the maximum size of a
1200 * buffer is limited to 16MB, so we never need to store 32MB in
1201 * this field. Even in the upstream illumos code base, the
1202 * maximum size of a buffer is limited to 16MB.
1207 * This field stores the size of the data buffer before
1208 * compression, and cannot change once set. It is in units
1209 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1211 uint16_t b_lsize; /* immutable */
1212 uint64_t b_spa; /* immutable */
1214 /* L2ARC fields. Undefined when not in L2ARC. */
1215 l2arc_buf_hdr_t b_l2hdr;
1216 /* L1ARC fields. Undefined when in l2arc_only state */
1217 l1arc_buf_hdr_t b_l1hdr;
1220 #if defined(__FreeBSD__) && defined(_KERNEL)
1222 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1227 val = arc_meta_limit;
1228 err = sysctl_handle_64(oidp, &val, 0, req);
1229 if (err != 0 || req->newptr == NULL)
1232 if (val <= 0 || val > arc_c_max)
1235 arc_meta_limit = val;
1237 mutex_enter(&arc_adjust_lock);
1238 arc_adjust_needed = B_TRUE;
1239 mutex_exit(&arc_adjust_lock);
1240 zthr_wakeup(arc_adjust_zthr);
1246 sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS)
1251 val = arc_no_grow_shift;
1252 err = sysctl_handle_32(oidp, &val, 0, req);
1253 if (err != 0 || req->newptr == NULL)
1256 if (val >= arc_shrink_shift)
1259 arc_no_grow_shift = val;
1264 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1270 err = sysctl_handle_64(oidp, &val, 0, req);
1271 if (err != 0 || req->newptr == NULL)
1274 if (zfs_arc_max == 0) {
1275 /* Loader tunable so blindly set */
1280 if (val < arc_abs_min || val > kmem_size())
1282 if (val < arc_c_min)
1284 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1290 arc_p = (arc_c >> 1);
1292 if (zfs_arc_meta_limit == 0) {
1293 /* limit meta-data to 1/4 of the arc capacity */
1294 arc_meta_limit = arc_c_max / 4;
1297 /* if kmem_flags are set, lets try to use less memory */
1298 if (kmem_debugging())
1301 zfs_arc_max = arc_c;
1303 mutex_enter(&arc_adjust_lock);
1304 arc_adjust_needed = B_TRUE;
1305 mutex_exit(&arc_adjust_lock);
1306 zthr_wakeup(arc_adjust_zthr);
1312 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1318 err = sysctl_handle_64(oidp, &val, 0, req);
1319 if (err != 0 || req->newptr == NULL)
1322 if (zfs_arc_min == 0) {
1323 /* Loader tunable so blindly set */
1328 if (val < arc_abs_min || val > arc_c_max)
1333 if (zfs_arc_meta_min == 0)
1334 arc_meta_min = arc_c_min / 2;
1336 if (arc_c < arc_c_min)
1339 zfs_arc_min = arc_c_min;
1345 #define GHOST_STATE(state) \
1346 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
1347 (state) == arc_l2c_only)
1349 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1350 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1351 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1352 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1353 #define HDR_PRESCIENT_PREFETCH(hdr) \
1354 ((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
1355 #define HDR_COMPRESSION_ENABLED(hdr) \
1356 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1358 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1359 #define HDR_L2_READING(hdr) \
1360 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1361 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1362 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1363 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1364 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1365 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1367 #define HDR_ISTYPE_METADATA(hdr) \
1368 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1369 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1371 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1372 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1374 /* For storing compression mode in b_flags */
1375 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1377 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1378 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1379 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1380 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1382 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
1383 #define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1384 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1390 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1391 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1394 * Hash table routines
1397 #define HT_LOCK_PAD CACHE_LINE_SIZE
1402 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1406 #define BUF_LOCKS 256
1407 typedef struct buf_hash_table {
1409 arc_buf_hdr_t **ht_table;
1410 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1413 static buf_hash_table_t buf_hash_table;
1415 #define BUF_HASH_INDEX(spa, dva, birth) \
1416 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1417 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1418 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1419 #define HDR_LOCK(hdr) \
1420 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1422 uint64_t zfs_crc64_table[256];
1428 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1429 #define L2ARC_HEADROOM 2 /* num of writes */
1431 * If we discover during ARC scan any buffers to be compressed, we boost
1432 * our headroom for the next scanning cycle by this percentage multiple.
1434 #define L2ARC_HEADROOM_BOOST 200
1435 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1436 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1438 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1439 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1441 /* L2ARC Performance Tunables */
1442 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1443 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1444 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1445 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1446 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1447 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1448 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1449 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1450 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1452 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RWTUN,
1453 &l2arc_write_max, 0, "max write size");
1454 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RWTUN,
1455 &l2arc_write_boost, 0, "extra write during warmup");
1456 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RWTUN,
1457 &l2arc_headroom, 0, "number of dev writes");
1458 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RWTUN,
1459 &l2arc_feed_secs, 0, "interval seconds");
1460 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RWTUN,
1461 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1463 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RWTUN,
1464 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1465 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RWTUN,
1466 &l2arc_feed_again, 0, "turbo warmup");
1467 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RWTUN,
1468 &l2arc_norw, 0, "no reads during writes");
1470 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1471 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1472 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1473 &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1474 "size of anonymous state");
1475 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1476 &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1477 "size of anonymous state");
1479 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1480 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1481 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1482 &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1483 "size of metadata in mru state");
1484 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1485 &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1486 "size of data in mru state");
1488 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1489 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1490 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1491 &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1492 "size of metadata in mru ghost state");
1493 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1494 &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1495 "size of data in mru ghost state");
1497 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1498 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1499 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1500 &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1501 "size of metadata in mfu state");
1502 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1503 &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1504 "size of data in mfu state");
1506 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1507 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1508 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1509 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1510 "size of metadata in mfu ghost state");
1511 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1512 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1513 "size of data in mfu ghost state");
1515 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1516 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1518 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prefetch_ms, CTLFLAG_RW,
1519 &zfs_arc_min_prefetch_ms, 0, "Min life of prefetch block in ms");
1520 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prescient_prefetch_ms, CTLFLAG_RW,
1521 &zfs_arc_min_prescient_prefetch_ms, 0, "Min life of prescient prefetched block in ms");
1527 vdev_t *l2ad_vdev; /* vdev */
1528 spa_t *l2ad_spa; /* spa */
1529 uint64_t l2ad_hand; /* next write location */
1530 uint64_t l2ad_start; /* first addr on device */
1531 uint64_t l2ad_end; /* last addr on device */
1532 boolean_t l2ad_first; /* first sweep through */
1533 boolean_t l2ad_writing; /* currently writing */
1534 kmutex_t l2ad_mtx; /* lock for buffer list */
1535 list_t l2ad_buflist; /* buffer list */
1536 list_node_t l2ad_node; /* device list node */
1537 zfs_refcount_t l2ad_alloc; /* allocated bytes */
1540 static list_t L2ARC_dev_list; /* device list */
1541 static list_t *l2arc_dev_list; /* device list pointer */
1542 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1543 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1544 static list_t L2ARC_free_on_write; /* free after write buf list */
1545 static list_t *l2arc_free_on_write; /* free after write list ptr */
1546 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1547 static uint64_t l2arc_ndev; /* number of devices */
1549 typedef struct l2arc_read_callback {
1550 arc_buf_hdr_t *l2rcb_hdr; /* read header */
1551 blkptr_t l2rcb_bp; /* original blkptr */
1552 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1553 int l2rcb_flags; /* original flags */
1554 abd_t *l2rcb_abd; /* temporary buffer */
1555 } l2arc_read_callback_t;
1557 typedef struct l2arc_write_callback {
1558 l2arc_dev_t *l2wcb_dev; /* device info */
1559 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1560 } l2arc_write_callback_t;
1562 typedef struct l2arc_data_free {
1563 /* protected by l2arc_free_on_write_mtx */
1566 arc_buf_contents_t l2df_type;
1567 list_node_t l2df_list_node;
1568 } l2arc_data_free_t;
1570 static kmutex_t l2arc_feed_thr_lock;
1571 static kcondvar_t l2arc_feed_thr_cv;
1572 static uint8_t l2arc_thread_exit;
1574 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *, boolean_t);
1575 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1576 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *, boolean_t);
1577 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1578 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1579 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1580 static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1581 static void arc_hdr_alloc_pabd(arc_buf_hdr_t *, boolean_t);
1582 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1583 static boolean_t arc_is_overflowing();
1584 static void arc_buf_watch(arc_buf_t *);
1585 static void arc_prune_async(int64_t);
1587 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1588 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1589 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1590 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1592 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1593 static void l2arc_read_done(zio_t *);
1596 l2arc_trim(const arc_buf_hdr_t *hdr)
1598 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1600 ASSERT(HDR_HAS_L2HDR(hdr));
1601 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1603 if (HDR_GET_PSIZE(hdr) != 0) {
1604 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1605 HDR_GET_PSIZE(hdr), 0);
1610 * We use Cityhash for this. It's fast, and has good hash properties without
1611 * requiring any large static buffers.
1614 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1616 return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1619 #define HDR_EMPTY(hdr) \
1620 ((hdr)->b_dva.dva_word[0] == 0 && \
1621 (hdr)->b_dva.dva_word[1] == 0)
1623 #define HDR_EQUAL(spa, dva, birth, hdr) \
1624 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1625 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1626 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1629 buf_discard_identity(arc_buf_hdr_t *hdr)
1631 hdr->b_dva.dva_word[0] = 0;
1632 hdr->b_dva.dva_word[1] = 0;
1636 static arc_buf_hdr_t *
1637 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1639 const dva_t *dva = BP_IDENTITY(bp);
1640 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1641 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1642 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1645 mutex_enter(hash_lock);
1646 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1647 hdr = hdr->b_hash_next) {
1648 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1653 mutex_exit(hash_lock);
1659 * Insert an entry into the hash table. If there is already an element
1660 * equal to elem in the hash table, then the already existing element
1661 * will be returned and the new element will not be inserted.
1662 * Otherwise returns NULL.
1663 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1665 static arc_buf_hdr_t *
1666 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1668 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1669 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1670 arc_buf_hdr_t *fhdr;
1673 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1674 ASSERT(hdr->b_birth != 0);
1675 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1677 if (lockp != NULL) {
1679 mutex_enter(hash_lock);
1681 ASSERT(MUTEX_HELD(hash_lock));
1684 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1685 fhdr = fhdr->b_hash_next, i++) {
1686 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1690 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1691 buf_hash_table.ht_table[idx] = hdr;
1692 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1694 /* collect some hash table performance data */
1696 ARCSTAT_BUMP(arcstat_hash_collisions);
1698 ARCSTAT_BUMP(arcstat_hash_chains);
1700 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1703 ARCSTAT_BUMP(arcstat_hash_elements);
1704 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1710 buf_hash_remove(arc_buf_hdr_t *hdr)
1712 arc_buf_hdr_t *fhdr, **hdrp;
1713 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1715 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1716 ASSERT(HDR_IN_HASH_TABLE(hdr));
1718 hdrp = &buf_hash_table.ht_table[idx];
1719 while ((fhdr = *hdrp) != hdr) {
1720 ASSERT3P(fhdr, !=, NULL);
1721 hdrp = &fhdr->b_hash_next;
1723 *hdrp = hdr->b_hash_next;
1724 hdr->b_hash_next = NULL;
1725 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1727 /* collect some hash table performance data */
1728 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1730 if (buf_hash_table.ht_table[idx] &&
1731 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1732 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1736 * Global data structures and functions for the buf kmem cache.
1738 static kmem_cache_t *hdr_full_cache;
1739 static kmem_cache_t *hdr_l2only_cache;
1740 static kmem_cache_t *buf_cache;
1747 kmem_free(buf_hash_table.ht_table,
1748 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1749 for (i = 0; i < BUF_LOCKS; i++)
1750 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1751 kmem_cache_destroy(hdr_full_cache);
1752 kmem_cache_destroy(hdr_l2only_cache);
1753 kmem_cache_destroy(buf_cache);
1757 * Constructor callback - called when the cache is empty
1758 * and a new buf is requested.
1762 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1764 arc_buf_hdr_t *hdr = vbuf;
1766 bzero(hdr, HDR_FULL_SIZE);
1767 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1768 zfs_refcount_create(&hdr->b_l1hdr.b_refcnt);
1769 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1770 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1771 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1778 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1780 arc_buf_hdr_t *hdr = vbuf;
1782 bzero(hdr, HDR_L2ONLY_SIZE);
1783 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1790 buf_cons(void *vbuf, void *unused, int kmflag)
1792 arc_buf_t *buf = vbuf;
1794 bzero(buf, sizeof (arc_buf_t));
1795 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1796 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1802 * Destructor callback - called when a cached buf is
1803 * no longer required.
1807 hdr_full_dest(void *vbuf, void *unused)
1809 arc_buf_hdr_t *hdr = vbuf;
1811 ASSERT(HDR_EMPTY(hdr));
1812 cv_destroy(&hdr->b_l1hdr.b_cv);
1813 zfs_refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1814 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1815 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1816 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1821 hdr_l2only_dest(void *vbuf, void *unused)
1823 arc_buf_hdr_t *hdr = vbuf;
1825 ASSERT(HDR_EMPTY(hdr));
1826 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1831 buf_dest(void *vbuf, void *unused)
1833 arc_buf_t *buf = vbuf;
1835 mutex_destroy(&buf->b_evict_lock);
1836 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1840 * Reclaim callback -- invoked when memory is low.
1844 hdr_recl(void *unused)
1846 dprintf("hdr_recl called\n");
1848 * umem calls the reclaim func when we destroy the buf cache,
1849 * which is after we do arc_fini().
1851 if (arc_initialized)
1852 zthr_wakeup(arc_reap_zthr);
1859 uint64_t hsize = 1ULL << 12;
1863 * The hash table is big enough to fill all of physical memory
1864 * with an average block size of zfs_arc_average_blocksize (default 8K).
1865 * By default, the table will take up
1866 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1868 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1871 buf_hash_table.ht_mask = hsize - 1;
1872 buf_hash_table.ht_table =
1873 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1874 if (buf_hash_table.ht_table == NULL) {
1875 ASSERT(hsize > (1ULL << 8));
1880 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1881 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1882 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1883 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1885 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1886 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1888 for (i = 0; i < 256; i++)
1889 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1890 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1892 for (i = 0; i < BUF_LOCKS; i++) {
1893 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1894 NULL, MUTEX_DEFAULT, NULL);
1899 * This is the size that the buf occupies in memory. If the buf is compressed,
1900 * it will correspond to the compressed size. You should use this method of
1901 * getting the buf size unless you explicitly need the logical size.
1904 arc_buf_size(arc_buf_t *buf)
1906 return (ARC_BUF_COMPRESSED(buf) ?
1907 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1911 arc_buf_lsize(arc_buf_t *buf)
1913 return (HDR_GET_LSIZE(buf->b_hdr));
1917 arc_get_compression(arc_buf_t *buf)
1919 return (ARC_BUF_COMPRESSED(buf) ?
1920 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1923 #define ARC_MINTIME (hz>>4) /* 62 ms */
1925 static inline boolean_t
1926 arc_buf_is_shared(arc_buf_t *buf)
1928 boolean_t shared = (buf->b_data != NULL &&
1929 buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1930 abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1931 buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1932 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1933 IMPLY(shared, ARC_BUF_SHARED(buf));
1934 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1937 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1938 * already being shared" requirement prevents us from doing that.
1945 * Free the checksum associated with this header. If there is no checksum, this
1949 arc_cksum_free(arc_buf_hdr_t *hdr)
1951 ASSERT(HDR_HAS_L1HDR(hdr));
1952 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1953 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1954 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1955 hdr->b_l1hdr.b_freeze_cksum = NULL;
1957 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1961 * Return true iff at least one of the bufs on hdr is not compressed.
1964 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1966 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1967 if (!ARC_BUF_COMPRESSED(b)) {
1975 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1976 * matches the checksum that is stored in the hdr. If there is no checksum,
1977 * or if the buf is compressed, this is a no-op.
1980 arc_cksum_verify(arc_buf_t *buf)
1982 arc_buf_hdr_t *hdr = buf->b_hdr;
1985 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1988 if (ARC_BUF_COMPRESSED(buf)) {
1989 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1990 arc_hdr_has_uncompressed_buf(hdr));
1994 ASSERT(HDR_HAS_L1HDR(hdr));
1996 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1997 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1998 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2002 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
2003 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
2004 panic("buffer modified while frozen!");
2005 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2009 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
2011 enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
2012 boolean_t valid_cksum;
2014 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
2015 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
2018 * We rely on the blkptr's checksum to determine if the block
2019 * is valid or not. When compressed arc is enabled, the l2arc
2020 * writes the block to the l2arc just as it appears in the pool.
2021 * This allows us to use the blkptr's checksum to validate the
2022 * data that we just read off of the l2arc without having to store
2023 * a separate checksum in the arc_buf_hdr_t. However, if compressed
2024 * arc is disabled, then the data written to the l2arc is always
2025 * uncompressed and won't match the block as it exists in the main
2026 * pool. When this is the case, we must first compress it if it is
2027 * compressed on the main pool before we can validate the checksum.
2029 if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
2030 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2031 uint64_t lsize = HDR_GET_LSIZE(hdr);
2034 abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
2035 csize = zio_compress_data(compress, zio->io_abd,
2036 abd_to_buf(cdata), lsize);
2038 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
2039 if (csize < HDR_GET_PSIZE(hdr)) {
2041 * Compressed blocks are always a multiple of the
2042 * smallest ashift in the pool. Ideally, we would
2043 * like to round up the csize to the next
2044 * spa_min_ashift but that value may have changed
2045 * since the block was last written. Instead,
2046 * we rely on the fact that the hdr's psize
2047 * was set to the psize of the block when it was
2048 * last written. We set the csize to that value
2049 * and zero out any part that should not contain
2052 abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
2053 csize = HDR_GET_PSIZE(hdr);
2055 zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
2059 * Block pointers always store the checksum for the logical data.
2060 * If the block pointer has the gang bit set, then the checksum
2061 * it represents is for the reconstituted data and not for an
2062 * individual gang member. The zio pipeline, however, must be able to
2063 * determine the checksum of each of the gang constituents so it
2064 * treats the checksum comparison differently than what we need
2065 * for l2arc blocks. This prevents us from using the
2066 * zio_checksum_error() interface directly. Instead we must call the
2067 * zio_checksum_error_impl() so that we can ensure the checksum is
2068 * generated using the correct checksum algorithm and accounts for the
2069 * logical I/O size and not just a gang fragment.
2071 valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
2072 BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
2073 zio->io_offset, NULL) == 0);
2074 zio_pop_transforms(zio);
2075 return (valid_cksum);
2079 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
2080 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
2081 * isn't modified later on. If buf is compressed or there is already a checksum
2082 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
2085 arc_cksum_compute(arc_buf_t *buf)
2087 arc_buf_hdr_t *hdr = buf->b_hdr;
2089 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2092 ASSERT(HDR_HAS_L1HDR(hdr));
2094 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
2095 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
2096 ASSERT(arc_hdr_has_uncompressed_buf(hdr));
2097 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2099 } else if (ARC_BUF_COMPRESSED(buf)) {
2100 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2104 ASSERT(!ARC_BUF_COMPRESSED(buf));
2105 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
2107 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
2108 hdr->b_l1hdr.b_freeze_cksum);
2109 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2117 typedef struct procctl {
2125 arc_buf_unwatch(arc_buf_t *buf)
2132 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2133 ctl.prwatch.pr_size = 0;
2134 ctl.prwatch.pr_wflags = 0;
2135 result = write(arc_procfd, &ctl, sizeof (ctl));
2136 ASSERT3U(result, ==, sizeof (ctl));
2143 arc_buf_watch(arc_buf_t *buf)
2150 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2151 ctl.prwatch.pr_size = arc_buf_size(buf);
2152 ctl.prwatch.pr_wflags = WA_WRITE;
2153 result = write(arc_procfd, &ctl, sizeof (ctl));
2154 ASSERT3U(result, ==, sizeof (ctl));
2158 #endif /* illumos */
2160 static arc_buf_contents_t
2161 arc_buf_type(arc_buf_hdr_t *hdr)
2163 arc_buf_contents_t type;
2164 if (HDR_ISTYPE_METADATA(hdr)) {
2165 type = ARC_BUFC_METADATA;
2167 type = ARC_BUFC_DATA;
2169 VERIFY3U(hdr->b_type, ==, type);
2174 arc_is_metadata(arc_buf_t *buf)
2176 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
2180 arc_bufc_to_flags(arc_buf_contents_t type)
2184 /* metadata field is 0 if buffer contains normal data */
2186 case ARC_BUFC_METADATA:
2187 return (ARC_FLAG_BUFC_METADATA);
2191 panic("undefined ARC buffer type!");
2192 return ((uint32_t)-1);
2196 arc_buf_thaw(arc_buf_t *buf)
2198 arc_buf_hdr_t *hdr = buf->b_hdr;
2200 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2201 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2203 arc_cksum_verify(buf);
2206 * Compressed buffers do not manipulate the b_freeze_cksum or
2207 * allocate b_thawed.
2209 if (ARC_BUF_COMPRESSED(buf)) {
2210 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2211 arc_hdr_has_uncompressed_buf(hdr));
2215 ASSERT(HDR_HAS_L1HDR(hdr));
2216 arc_cksum_free(hdr);
2218 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
2220 if (zfs_flags & ZFS_DEBUG_MODIFY) {
2221 if (hdr->b_l1hdr.b_thawed != NULL)
2222 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2223 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
2227 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2230 arc_buf_unwatch(buf);
2235 arc_buf_freeze(arc_buf_t *buf)
2237 arc_buf_hdr_t *hdr = buf->b_hdr;
2238 kmutex_t *hash_lock;
2240 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2243 if (ARC_BUF_COMPRESSED(buf)) {
2244 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2245 arc_hdr_has_uncompressed_buf(hdr));
2249 hash_lock = HDR_LOCK(hdr);
2250 mutex_enter(hash_lock);
2252 ASSERT(HDR_HAS_L1HDR(hdr));
2253 ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2254 hdr->b_l1hdr.b_state == arc_anon);
2255 arc_cksum_compute(buf);
2256 mutex_exit(hash_lock);
2260 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2261 * the following functions should be used to ensure that the flags are
2262 * updated in a thread-safe way. When manipulating the flags either
2263 * the hash_lock must be held or the hdr must be undiscoverable. This
2264 * ensures that we're not racing with any other threads when updating
2268 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2270 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2271 hdr->b_flags |= flags;
2275 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2277 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2278 hdr->b_flags &= ~flags;
2282 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2283 * done in a special way since we have to clear and set bits
2284 * at the same time. Consumers that wish to set the compression bits
2285 * must use this function to ensure that the flags are updated in
2286 * thread-safe manner.
2289 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2291 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2294 * Holes and embedded blocks will always have a psize = 0 so
2295 * we ignore the compression of the blkptr and set the
2296 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2297 * Holes and embedded blocks remain anonymous so we don't
2298 * want to uncompress them. Mark them as uncompressed.
2300 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2301 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2302 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
2303 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2304 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2306 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2307 HDR_SET_COMPRESS(hdr, cmp);
2308 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2309 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2314 * Looks for another buf on the same hdr which has the data decompressed, copies
2315 * from it, and returns true. If no such buf exists, returns false.
2318 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
2320 arc_buf_hdr_t *hdr = buf->b_hdr;
2321 boolean_t copied = B_FALSE;
2323 ASSERT(HDR_HAS_L1HDR(hdr));
2324 ASSERT3P(buf->b_data, !=, NULL);
2325 ASSERT(!ARC_BUF_COMPRESSED(buf));
2327 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
2328 from = from->b_next) {
2329 /* can't use our own data buffer */
2334 if (!ARC_BUF_COMPRESSED(from)) {
2335 bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
2342 * There were no decompressed bufs, so there should not be a
2343 * checksum on the hdr either.
2345 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
2351 * Given a buf that has a data buffer attached to it, this function will
2352 * efficiently fill the buf with data of the specified compression setting from
2353 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2354 * are already sharing a data buf, no copy is performed.
2356 * If the buf is marked as compressed but uncompressed data was requested, this
2357 * will allocate a new data buffer for the buf, remove that flag, and fill the
2358 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2359 * uncompressed data, and (since we haven't added support for it yet) if you
2360 * want compressed data your buf must already be marked as compressed and have
2361 * the correct-sized data buffer.
2364 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
2366 arc_buf_hdr_t *hdr = buf->b_hdr;
2367 boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2368 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2370 ASSERT3P(buf->b_data, !=, NULL);
2371 IMPLY(compressed, hdr_compressed);
2372 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2374 if (hdr_compressed == compressed) {
2375 if (!arc_buf_is_shared(buf)) {
2376 abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
2380 ASSERT(hdr_compressed);
2381 ASSERT(!compressed);
2382 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2385 * If the buf is sharing its data with the hdr, unlink it and
2386 * allocate a new data buffer for the buf.
2388 if (arc_buf_is_shared(buf)) {
2389 ASSERT(ARC_BUF_COMPRESSED(buf));
2391 /* We need to give the buf it's own b_data */
2392 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2394 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2395 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2397 /* Previously overhead was 0; just add new overhead */
2398 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2399 } else if (ARC_BUF_COMPRESSED(buf)) {
2400 /* We need to reallocate the buf's b_data */
2401 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2404 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2406 /* We increased the size of b_data; update overhead */
2407 ARCSTAT_INCR(arcstat_overhead_size,
2408 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2412 * Regardless of the buf's previous compression settings, it
2413 * should not be compressed at the end of this function.
2415 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2418 * Try copying the data from another buf which already has a
2419 * decompressed version. If that's not possible, it's time to
2420 * bite the bullet and decompress the data from the hdr.
2422 if (arc_buf_try_copy_decompressed_data(buf)) {
2423 /* Skip byteswapping and checksumming (already done) */
2424 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
2427 int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2428 hdr->b_l1hdr.b_pabd, buf->b_data,
2429 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2432 * Absent hardware errors or software bugs, this should
2433 * be impossible, but log it anyway so we can debug it.
2437 "hdr %p, compress %d, psize %d, lsize %d",
2438 hdr, HDR_GET_COMPRESS(hdr),
2439 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2440 return (SET_ERROR(EIO));
2445 /* Byteswap the buf's data if necessary */
2446 if (bswap != DMU_BSWAP_NUMFUNCS) {
2447 ASSERT(!HDR_SHARED_DATA(hdr));
2448 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2449 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2452 /* Compute the hdr's checksum if necessary */
2453 arc_cksum_compute(buf);
2459 arc_decompress(arc_buf_t *buf)
2461 return (arc_buf_fill(buf, B_FALSE));
2465 * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2468 arc_hdr_size(arc_buf_hdr_t *hdr)
2472 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2473 HDR_GET_PSIZE(hdr) > 0) {
2474 size = HDR_GET_PSIZE(hdr);
2476 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2477 size = HDR_GET_LSIZE(hdr);
2483 * Increment the amount of evictable space in the arc_state_t's refcount.
2484 * We account for the space used by the hdr and the arc buf individually
2485 * so that we can add and remove them from the refcount individually.
2488 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2490 arc_buf_contents_t type = arc_buf_type(hdr);
2492 ASSERT(HDR_HAS_L1HDR(hdr));
2494 if (GHOST_STATE(state)) {
2495 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2496 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2497 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2498 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2499 HDR_GET_LSIZE(hdr), hdr);
2503 ASSERT(!GHOST_STATE(state));
2504 if (hdr->b_l1hdr.b_pabd != NULL) {
2505 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2506 arc_hdr_size(hdr), hdr);
2508 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2509 buf = buf->b_next) {
2510 if (arc_buf_is_shared(buf))
2512 (void) zfs_refcount_add_many(&state->arcs_esize[type],
2513 arc_buf_size(buf), buf);
2518 * Decrement the amount of evictable space in the arc_state_t's refcount.
2519 * We account for the space used by the hdr and the arc buf individually
2520 * so that we can add and remove them from the refcount individually.
2523 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2525 arc_buf_contents_t type = arc_buf_type(hdr);
2527 ASSERT(HDR_HAS_L1HDR(hdr));
2529 if (GHOST_STATE(state)) {
2530 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2531 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2532 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2533 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2534 HDR_GET_LSIZE(hdr), hdr);
2538 ASSERT(!GHOST_STATE(state));
2539 if (hdr->b_l1hdr.b_pabd != NULL) {
2540 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2541 arc_hdr_size(hdr), hdr);
2543 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2544 buf = buf->b_next) {
2545 if (arc_buf_is_shared(buf))
2547 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
2548 arc_buf_size(buf), buf);
2553 * Add a reference to this hdr indicating that someone is actively
2554 * referencing that memory. When the refcount transitions from 0 to 1,
2555 * we remove it from the respective arc_state_t list to indicate that
2556 * it is not evictable.
2559 add_reference(arc_buf_hdr_t *hdr, void *tag)
2561 ASSERT(HDR_HAS_L1HDR(hdr));
2562 if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2563 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2564 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2565 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2568 arc_state_t *state = hdr->b_l1hdr.b_state;
2570 if ((zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2571 (state != arc_anon)) {
2572 /* We don't use the L2-only state list. */
2573 if (state != arc_l2c_only) {
2574 multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2576 arc_evictable_space_decrement(hdr, state);
2578 /* remove the prefetch flag if we get a reference */
2579 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2584 * Remove a reference from this hdr. When the reference transitions from
2585 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2586 * list making it eligible for eviction.
2589 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2592 arc_state_t *state = hdr->b_l1hdr.b_state;
2594 ASSERT(HDR_HAS_L1HDR(hdr));
2595 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2596 ASSERT(!GHOST_STATE(state));
2599 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2600 * check to prevent usage of the arc_l2c_only list.
2602 if (((cnt = zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2603 (state != arc_anon)) {
2604 multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2605 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2606 arc_evictable_space_increment(hdr, state);
2612 * Returns detailed information about a specific arc buffer. When the
2613 * state_index argument is set the function will calculate the arc header
2614 * list position for its arc state. Since this requires a linear traversal
2615 * callers are strongly encourage not to do this. However, it can be helpful
2616 * for targeted analysis so the functionality is provided.
2619 arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
2621 arc_buf_hdr_t *hdr = ab->b_hdr;
2622 l1arc_buf_hdr_t *l1hdr = NULL;
2623 l2arc_buf_hdr_t *l2hdr = NULL;
2624 arc_state_t *state = NULL;
2626 memset(abi, 0, sizeof (arc_buf_info_t));
2631 abi->abi_flags = hdr->b_flags;
2633 if (HDR_HAS_L1HDR(hdr)) {
2634 l1hdr = &hdr->b_l1hdr;
2635 state = l1hdr->b_state;
2637 if (HDR_HAS_L2HDR(hdr))
2638 l2hdr = &hdr->b_l2hdr;
2641 abi->abi_bufcnt = l1hdr->b_bufcnt;
2642 abi->abi_access = l1hdr->b_arc_access;
2643 abi->abi_mru_hits = l1hdr->b_mru_hits;
2644 abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
2645 abi->abi_mfu_hits = l1hdr->b_mfu_hits;
2646 abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
2647 abi->abi_holds = zfs_refcount_count(&l1hdr->b_refcnt);
2651 abi->abi_l2arc_dattr = l2hdr->b_daddr;
2652 abi->abi_l2arc_hits = l2hdr->b_hits;
2655 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
2656 abi->abi_state_contents = arc_buf_type(hdr);
2657 abi->abi_size = arc_hdr_size(hdr);
2661 * Move the supplied buffer to the indicated state. The hash lock
2662 * for the buffer must be held by the caller.
2665 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2666 kmutex_t *hash_lock)
2668 arc_state_t *old_state;
2671 boolean_t update_old, update_new;
2672 arc_buf_contents_t buftype = arc_buf_type(hdr);
2675 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2676 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2677 * L1 hdr doesn't always exist when we change state to arc_anon before
2678 * destroying a header, in which case reallocating to add the L1 hdr is
2681 if (HDR_HAS_L1HDR(hdr)) {
2682 old_state = hdr->b_l1hdr.b_state;
2683 refcnt = zfs_refcount_count(&hdr->b_l1hdr.b_refcnt);
2684 bufcnt = hdr->b_l1hdr.b_bufcnt;
2685 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
2687 old_state = arc_l2c_only;
2690 update_old = B_FALSE;
2692 update_new = update_old;
2694 ASSERT(MUTEX_HELD(hash_lock));
2695 ASSERT3P(new_state, !=, old_state);
2696 ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2697 ASSERT(old_state != arc_anon || bufcnt <= 1);
2700 * If this buffer is evictable, transfer it from the
2701 * old state list to the new state list.
2704 if (old_state != arc_anon && old_state != arc_l2c_only) {
2705 ASSERT(HDR_HAS_L1HDR(hdr));
2706 multilist_remove(old_state->arcs_list[buftype], hdr);
2708 if (GHOST_STATE(old_state)) {
2710 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2711 update_old = B_TRUE;
2713 arc_evictable_space_decrement(hdr, old_state);
2715 if (new_state != arc_anon && new_state != arc_l2c_only) {
2718 * An L1 header always exists here, since if we're
2719 * moving to some L1-cached state (i.e. not l2c_only or
2720 * anonymous), we realloc the header to add an L1hdr
2723 ASSERT(HDR_HAS_L1HDR(hdr));
2724 multilist_insert(new_state->arcs_list[buftype], hdr);
2726 if (GHOST_STATE(new_state)) {
2728 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2729 update_new = B_TRUE;
2731 arc_evictable_space_increment(hdr, new_state);
2735 ASSERT(!HDR_EMPTY(hdr));
2736 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2737 buf_hash_remove(hdr);
2739 /* adjust state sizes (ignore arc_l2c_only) */
2741 if (update_new && new_state != arc_l2c_only) {
2742 ASSERT(HDR_HAS_L1HDR(hdr));
2743 if (GHOST_STATE(new_state)) {
2747 * When moving a header to a ghost state, we first
2748 * remove all arc buffers. Thus, we'll have a
2749 * bufcnt of zero, and no arc buffer to use for
2750 * the reference. As a result, we use the arc
2751 * header pointer for the reference.
2753 (void) zfs_refcount_add_many(&new_state->arcs_size,
2754 HDR_GET_LSIZE(hdr), hdr);
2755 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2757 uint32_t buffers = 0;
2760 * Each individual buffer holds a unique reference,
2761 * thus we must remove each of these references one
2764 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2765 buf = buf->b_next) {
2766 ASSERT3U(bufcnt, !=, 0);
2770 * When the arc_buf_t is sharing the data
2771 * block with the hdr, the owner of the
2772 * reference belongs to the hdr. Only
2773 * add to the refcount if the arc_buf_t is
2776 if (arc_buf_is_shared(buf))
2779 (void) zfs_refcount_add_many(
2780 &new_state->arcs_size,
2781 arc_buf_size(buf), buf);
2783 ASSERT3U(bufcnt, ==, buffers);
2785 if (hdr->b_l1hdr.b_pabd != NULL) {
2786 (void) zfs_refcount_add_many(
2787 &new_state->arcs_size,
2788 arc_hdr_size(hdr), hdr);
2790 ASSERT(GHOST_STATE(old_state));
2795 if (update_old && old_state != arc_l2c_only) {
2796 ASSERT(HDR_HAS_L1HDR(hdr));
2797 if (GHOST_STATE(old_state)) {
2799 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2802 * When moving a header off of a ghost state,
2803 * the header will not contain any arc buffers.
2804 * We use the arc header pointer for the reference
2805 * which is exactly what we did when we put the
2806 * header on the ghost state.
2809 (void) zfs_refcount_remove_many(&old_state->arcs_size,
2810 HDR_GET_LSIZE(hdr), hdr);
2812 uint32_t buffers = 0;
2815 * Each individual buffer holds a unique reference,
2816 * thus we must remove each of these references one
2819 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2820 buf = buf->b_next) {
2821 ASSERT3U(bufcnt, !=, 0);
2825 * When the arc_buf_t is sharing the data
2826 * block with the hdr, the owner of the
2827 * reference belongs to the hdr. Only
2828 * add to the refcount if the arc_buf_t is
2831 if (arc_buf_is_shared(buf))
2834 (void) zfs_refcount_remove_many(
2835 &old_state->arcs_size, arc_buf_size(buf),
2838 ASSERT3U(bufcnt, ==, buffers);
2839 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2840 (void) zfs_refcount_remove_many(
2841 &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2845 if (HDR_HAS_L1HDR(hdr))
2846 hdr->b_l1hdr.b_state = new_state;
2849 * L2 headers should never be on the L2 state list since they don't
2850 * have L1 headers allocated.
2852 ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2853 multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2857 arc_space_consume(uint64_t space, arc_space_type_t type)
2859 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2862 case ARC_SPACE_DATA:
2863 aggsum_add(&astat_data_size, space);
2865 case ARC_SPACE_META:
2866 aggsum_add(&astat_metadata_size, space);
2868 case ARC_SPACE_BONUS:
2869 aggsum_add(&astat_bonus_size, space);
2871 case ARC_SPACE_DNODE:
2872 aggsum_add(&astat_dnode_size, space);
2874 case ARC_SPACE_DBUF:
2875 aggsum_add(&astat_dbuf_size, space);
2877 case ARC_SPACE_HDRS:
2878 aggsum_add(&astat_hdr_size, space);
2880 case ARC_SPACE_L2HDRS:
2881 aggsum_add(&astat_l2_hdr_size, space);
2885 if (type != ARC_SPACE_DATA)
2886 aggsum_add(&arc_meta_used, space);
2888 aggsum_add(&arc_size, space);
2892 arc_space_return(uint64_t space, arc_space_type_t type)
2894 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2897 case ARC_SPACE_DATA:
2898 aggsum_add(&astat_data_size, -space);
2900 case ARC_SPACE_META:
2901 aggsum_add(&astat_metadata_size, -space);
2903 case ARC_SPACE_BONUS:
2904 aggsum_add(&astat_bonus_size, -space);
2906 case ARC_SPACE_DNODE:
2907 aggsum_add(&astat_dnode_size, -space);
2909 case ARC_SPACE_DBUF:
2910 aggsum_add(&astat_dbuf_size, -space);
2912 case ARC_SPACE_HDRS:
2913 aggsum_add(&astat_hdr_size, -space);
2915 case ARC_SPACE_L2HDRS:
2916 aggsum_add(&astat_l2_hdr_size, -space);
2920 if (type != ARC_SPACE_DATA) {
2921 ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
2923 * We use the upper bound here rather than the precise value
2924 * because the arc_meta_max value doesn't need to be
2925 * precise. It's only consumed by humans via arcstats.
2927 if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
2928 arc_meta_max = aggsum_upper_bound(&arc_meta_used);
2929 aggsum_add(&arc_meta_used, -space);
2932 ASSERT(aggsum_compare(&arc_size, space) >= 0);
2933 aggsum_add(&arc_size, -space);
2937 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2938 * with the hdr's b_pabd.
2941 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2944 * The criteria for sharing a hdr's data are:
2945 * 1. the hdr's compression matches the buf's compression
2946 * 2. the hdr doesn't need to be byteswapped
2947 * 3. the hdr isn't already being shared
2948 * 4. the buf is either compressed or it is the last buf in the hdr list
2950 * Criterion #4 maintains the invariant that shared uncompressed
2951 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2952 * might ask, "if a compressed buf is allocated first, won't that be the
2953 * last thing in the list?", but in that case it's impossible to create
2954 * a shared uncompressed buf anyway (because the hdr must be compressed
2955 * to have the compressed buf). You might also think that #3 is
2956 * sufficient to make this guarantee, however it's possible
2957 * (specifically in the rare L2ARC write race mentioned in
2958 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2959 * is sharable, but wasn't at the time of its allocation. Rather than
2960 * allow a new shared uncompressed buf to be created and then shuffle
2961 * the list around to make it the last element, this simply disallows
2962 * sharing if the new buf isn't the first to be added.
2964 ASSERT3P(buf->b_hdr, ==, hdr);
2965 boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2966 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2967 return (buf_compressed == hdr_compressed &&
2968 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2969 !HDR_SHARED_DATA(hdr) &&
2970 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2974 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2975 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2976 * copy was made successfully, or an error code otherwise.
2979 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2980 boolean_t fill, arc_buf_t **ret)
2984 ASSERT(HDR_HAS_L1HDR(hdr));
2985 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2986 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2987 hdr->b_type == ARC_BUFC_METADATA);
2988 ASSERT3P(ret, !=, NULL);
2989 ASSERT3P(*ret, ==, NULL);
2991 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2994 buf->b_next = hdr->b_l1hdr.b_buf;
2997 add_reference(hdr, tag);
3000 * We're about to change the hdr's b_flags. We must either
3001 * hold the hash_lock or be undiscoverable.
3003 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3006 * Only honor requests for compressed bufs if the hdr is actually
3009 if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
3010 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
3013 * If the hdr's data can be shared then we share the data buffer and
3014 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
3015 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
3016 * buffer to store the buf's data.
3018 * There are two additional restrictions here because we're sharing
3019 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
3020 * actively involved in an L2ARC write, because if this buf is used by
3021 * an arc_write() then the hdr's data buffer will be released when the
3022 * write completes, even though the L2ARC write might still be using it.
3023 * Second, the hdr's ABD must be linear so that the buf's user doesn't
3024 * need to be ABD-aware.
3026 boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
3027 abd_is_linear(hdr->b_l1hdr.b_pabd);
3029 /* Set up b_data and sharing */
3031 buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
3032 buf->b_flags |= ARC_BUF_FLAG_SHARED;
3033 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3036 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
3037 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3039 VERIFY3P(buf->b_data, !=, NULL);
3041 hdr->b_l1hdr.b_buf = buf;
3042 hdr->b_l1hdr.b_bufcnt += 1;
3045 * If the user wants the data from the hdr, we need to either copy or
3046 * decompress the data.
3049 return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
3055 static char *arc_onloan_tag = "onloan";
3058 arc_loaned_bytes_update(int64_t delta)
3060 atomic_add_64(&arc_loaned_bytes, delta);
3062 /* assert that it did not wrap around */
3063 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
3067 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
3068 * flight data by arc_tempreserve_space() until they are "returned". Loaned
3069 * buffers must be returned to the arc before they can be used by the DMU or
3073 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
3075 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
3076 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
3078 arc_loaned_bytes_update(arc_buf_size(buf));
3084 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
3085 enum zio_compress compression_type)
3087 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
3088 psize, lsize, compression_type);
3090 arc_loaned_bytes_update(arc_buf_size(buf));
3097 * Return a loaned arc buffer to the arc.
3100 arc_return_buf(arc_buf_t *buf, void *tag)
3102 arc_buf_hdr_t *hdr = buf->b_hdr;
3104 ASSERT3P(buf->b_data, !=, NULL);
3105 ASSERT(HDR_HAS_L1HDR(hdr));
3106 (void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
3107 (void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
3109 arc_loaned_bytes_update(-arc_buf_size(buf));
3112 /* Detach an arc_buf from a dbuf (tag) */
3114 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
3116 arc_buf_hdr_t *hdr = buf->b_hdr;
3118 ASSERT3P(buf->b_data, !=, NULL);
3119 ASSERT(HDR_HAS_L1HDR(hdr));
3120 (void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
3121 (void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
3123 arc_loaned_bytes_update(arc_buf_size(buf));
3127 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
3129 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
3132 df->l2df_size = size;
3133 df->l2df_type = type;
3134 mutex_enter(&l2arc_free_on_write_mtx);
3135 list_insert_head(l2arc_free_on_write, df);
3136 mutex_exit(&l2arc_free_on_write_mtx);
3140 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
3142 arc_state_t *state = hdr->b_l1hdr.b_state;
3143 arc_buf_contents_t type = arc_buf_type(hdr);
3144 uint64_t size = arc_hdr_size(hdr);
3146 /* protected by hash lock, if in the hash table */
3147 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3148 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3149 ASSERT(state != arc_anon && state != arc_l2c_only);
3151 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
3154 (void) zfs_refcount_remove_many(&state->arcs_size, size, hdr);
3155 if (type == ARC_BUFC_METADATA) {
3156 arc_space_return(size, ARC_SPACE_META);
3158 ASSERT(type == ARC_BUFC_DATA);
3159 arc_space_return(size, ARC_SPACE_DATA);
3162 l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
3166 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
3167 * data buffer, we transfer the refcount ownership to the hdr and update
3168 * the appropriate kstats.
3171 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3173 arc_state_t *state = hdr->b_l1hdr.b_state;
3175 ASSERT(arc_can_share(hdr, buf));
3176 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3177 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3180 * Start sharing the data buffer. We transfer the
3181 * refcount ownership to the hdr since it always owns
3182 * the refcount whenever an arc_buf_t is shared.
3184 zfs_refcount_transfer_ownership(&state->arcs_size, buf, hdr);
3185 hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3186 abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3187 HDR_ISTYPE_METADATA(hdr));
3188 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3189 buf->b_flags |= ARC_BUF_FLAG_SHARED;
3192 * Since we've transferred ownership to the hdr we need
3193 * to increment its compressed and uncompressed kstats and
3194 * decrement the overhead size.
3196 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3197 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3198 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3202 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3204 arc_state_t *state = hdr->b_l1hdr.b_state;
3206 ASSERT(arc_buf_is_shared(buf));
3207 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3208 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3211 * We are no longer sharing this buffer so we need
3212 * to transfer its ownership to the rightful owner.
3214 zfs_refcount_transfer_ownership(&state->arcs_size, hdr, buf);
3215 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3216 abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3217 abd_put(hdr->b_l1hdr.b_pabd);
3218 hdr->b_l1hdr.b_pabd = NULL;
3219 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3222 * Since the buffer is no longer shared between
3223 * the arc buf and the hdr, count it as overhead.
3225 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3226 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3227 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3231 * Remove an arc_buf_t from the hdr's buf list and return the last
3232 * arc_buf_t on the list. If no buffers remain on the list then return
3236 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3238 ASSERT(HDR_HAS_L1HDR(hdr));
3239 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3241 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3242 arc_buf_t *lastbuf = NULL;
3245 * Remove the buf from the hdr list and locate the last
3246 * remaining buffer on the list.
3248 while (*bufp != NULL) {
3250 *bufp = buf->b_next;
3253 * If we've removed a buffer in the middle of
3254 * the list then update the lastbuf and update
3257 if (*bufp != NULL) {
3259 bufp = &(*bufp)->b_next;
3263 ASSERT3P(lastbuf, !=, buf);
3264 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
3265 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
3266 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3272 * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
3276 arc_buf_destroy_impl(arc_buf_t *buf)
3278 arc_buf_hdr_t *hdr = buf->b_hdr;
3281 * Free up the data associated with the buf but only if we're not
3282 * sharing this with the hdr. If we are sharing it with the hdr, the
3283 * hdr is responsible for doing the free.
3285 if (buf->b_data != NULL) {
3287 * We're about to change the hdr's b_flags. We must either
3288 * hold the hash_lock or be undiscoverable.
3290 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3292 arc_cksum_verify(buf);
3294 arc_buf_unwatch(buf);
3297 if (arc_buf_is_shared(buf)) {
3298 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3300 uint64_t size = arc_buf_size(buf);
3301 arc_free_data_buf(hdr, buf->b_data, size, buf);
3302 ARCSTAT_INCR(arcstat_overhead_size, -size);
3306 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3307 hdr->b_l1hdr.b_bufcnt -= 1;
3310 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3312 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3314 * If the current arc_buf_t is sharing its data buffer with the
3315 * hdr, then reassign the hdr's b_pabd to share it with the new
3316 * buffer at the end of the list. The shared buffer is always
3317 * the last one on the hdr's buffer list.
3319 * There is an equivalent case for compressed bufs, but since
3320 * they aren't guaranteed to be the last buf in the list and
3321 * that is an exceedingly rare case, we just allow that space be
3322 * wasted temporarily.
3324 if (lastbuf != NULL) {
3325 /* Only one buf can be shared at once */
3326 VERIFY(!arc_buf_is_shared(lastbuf));
3327 /* hdr is uncompressed so can't have compressed buf */
3328 VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3330 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3331 arc_hdr_free_pabd(hdr);
3334 * We must setup a new shared block between the
3335 * last buffer and the hdr. The data would have
3336 * been allocated by the arc buf so we need to transfer
3337 * ownership to the hdr since it's now being shared.
3339 arc_share_buf(hdr, lastbuf);
3341 } else if (HDR_SHARED_DATA(hdr)) {
3343 * Uncompressed shared buffers are always at the end
3344 * of the list. Compressed buffers don't have the
3345 * same requirements. This makes it hard to
3346 * simply assert that the lastbuf is shared so
3347 * we rely on the hdr's compression flags to determine
3348 * if we have a compressed, shared buffer.
3350 ASSERT3P(lastbuf, !=, NULL);
3351 ASSERT(arc_buf_is_shared(lastbuf) ||
3352 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
3356 * Free the checksum if we're removing the last uncompressed buf from
3359 if (!arc_hdr_has_uncompressed_buf(hdr)) {
3360 arc_cksum_free(hdr);
3363 /* clean up the buf */
3365 kmem_cache_free(buf_cache, buf);
3369 arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr, boolean_t do_adapt)
3371 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3372 ASSERT(HDR_HAS_L1HDR(hdr));
3373 ASSERT(!HDR_SHARED_DATA(hdr));
3375 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3376 hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr, do_adapt);
3377 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3378 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3380 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3381 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3385 arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
3387 ASSERT(HDR_HAS_L1HDR(hdr));
3388 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3391 * If the hdr is currently being written to the l2arc then
3392 * we defer freeing the data by adding it to the l2arc_free_on_write
3393 * list. The l2arc will free the data once it's finished
3394 * writing it to the l2arc device.
3396 if (HDR_L2_WRITING(hdr)) {
3397 arc_hdr_free_on_write(hdr);
3398 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3400 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
3401 arc_hdr_size(hdr), hdr);
3403 hdr->b_l1hdr.b_pabd = NULL;
3404 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3406 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3407 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3410 static arc_buf_hdr_t *
3411 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3412 enum zio_compress compression_type, arc_buf_contents_t type)
3416 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3418 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3419 ASSERT(HDR_EMPTY(hdr));
3420 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3421 ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3422 HDR_SET_PSIZE(hdr, psize);
3423 HDR_SET_LSIZE(hdr, lsize);
3427 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3428 arc_hdr_set_compress(hdr, compression_type);
3430 hdr->b_l1hdr.b_state = arc_anon;
3431 hdr->b_l1hdr.b_arc_access = 0;
3432 hdr->b_l1hdr.b_bufcnt = 0;
3433 hdr->b_l1hdr.b_buf = NULL;
3436 * Allocate the hdr's buffer. This will contain either
3437 * the compressed or uncompressed data depending on the block
3438 * it references and compressed arc enablement.
3440 arc_hdr_alloc_pabd(hdr, B_TRUE);
3441 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3447 * Transition between the two allocation states for the arc_buf_hdr struct.
3448 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3449 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3450 * version is used when a cache buffer is only in the L2ARC in order to reduce
3453 static arc_buf_hdr_t *
3454 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3456 ASSERT(HDR_HAS_L2HDR(hdr));
3458 arc_buf_hdr_t *nhdr;
3459 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3461 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3462 (old == hdr_l2only_cache && new == hdr_full_cache));
3464 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3466 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3467 buf_hash_remove(hdr);
3469 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3471 if (new == hdr_full_cache) {
3472 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3474 * arc_access and arc_change_state need to be aware that a
3475 * header has just come out of L2ARC, so we set its state to
3476 * l2c_only even though it's about to change.
3478 nhdr->b_l1hdr.b_state = arc_l2c_only;
3480 /* Verify previous threads set to NULL before freeing */
3481 ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
3483 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3484 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3485 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3488 * If we've reached here, We must have been called from
3489 * arc_evict_hdr(), as such we should have already been
3490 * removed from any ghost list we were previously on
3491 * (which protects us from racing with arc_evict_state),
3492 * thus no locking is needed during this check.
3494 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3497 * A buffer must not be moved into the arc_l2c_only
3498 * state if it's not finished being written out to the
3499 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3500 * might try to be accessed, even though it was removed.
3502 VERIFY(!HDR_L2_WRITING(hdr));
3503 VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3506 if (hdr->b_l1hdr.b_thawed != NULL) {
3507 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3508 hdr->b_l1hdr.b_thawed = NULL;
3512 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3515 * The header has been reallocated so we need to re-insert it into any
3518 (void) buf_hash_insert(nhdr, NULL);
3520 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3522 mutex_enter(&dev->l2ad_mtx);
3525 * We must place the realloc'ed header back into the list at
3526 * the same spot. Otherwise, if it's placed earlier in the list,
3527 * l2arc_write_buffers() could find it during the function's
3528 * write phase, and try to write it out to the l2arc.
3530 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3531 list_remove(&dev->l2ad_buflist, hdr);
3533 mutex_exit(&dev->l2ad_mtx);
3536 * Since we're using the pointer address as the tag when
3537 * incrementing and decrementing the l2ad_alloc refcount, we
3538 * must remove the old pointer (that we're about to destroy) and
3539 * add the new pointer to the refcount. Otherwise we'd remove
3540 * the wrong pointer address when calling arc_hdr_destroy() later.
3543 (void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3545 (void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr),
3548 buf_discard_identity(hdr);
3549 kmem_cache_free(old, hdr);
3555 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3556 * The buf is returned thawed since we expect the consumer to modify it.
3559 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3561 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3562 ZIO_COMPRESS_OFF, type);
3563 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3565 arc_buf_t *buf = NULL;
3566 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3573 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3574 * for bufs containing metadata.
3577 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3578 enum zio_compress compression_type)
3580 ASSERT3U(lsize, >, 0);
3581 ASSERT3U(lsize, >=, psize);
3582 ASSERT(compression_type > ZIO_COMPRESS_OFF);
3583 ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3585 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3586 compression_type, ARC_BUFC_DATA);
3587 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3589 arc_buf_t *buf = NULL;
3590 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3592 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3594 if (!arc_buf_is_shared(buf)) {
3596 * To ensure that the hdr has the correct data in it if we call
3597 * arc_decompress() on this buf before it's been written to
3598 * disk, it's easiest if we just set up sharing between the
3601 ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3602 arc_hdr_free_pabd(hdr);
3603 arc_share_buf(hdr, buf);
3610 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3612 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3613 l2arc_dev_t *dev = l2hdr->b_dev;
3614 uint64_t psize = arc_hdr_size(hdr);
3616 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3617 ASSERT(HDR_HAS_L2HDR(hdr));
3619 list_remove(&dev->l2ad_buflist, hdr);
3621 ARCSTAT_INCR(arcstat_l2_psize, -psize);
3622 ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3624 vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3626 (void) zfs_refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3627 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3631 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3633 if (HDR_HAS_L1HDR(hdr)) {
3634 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3635 hdr->b_l1hdr.b_bufcnt > 0);
3636 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3637 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3639 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3640 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3642 if (!HDR_EMPTY(hdr))
3643 buf_discard_identity(hdr);
3645 if (HDR_HAS_L2HDR(hdr)) {
3646 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3647 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3650 mutex_enter(&dev->l2ad_mtx);
3653 * Even though we checked this conditional above, we
3654 * need to check this again now that we have the
3655 * l2ad_mtx. This is because we could be racing with
3656 * another thread calling l2arc_evict() which might have
3657 * destroyed this header's L2 portion as we were waiting
3658 * to acquire the l2ad_mtx. If that happens, we don't
3659 * want to re-destroy the header's L2 portion.
3661 if (HDR_HAS_L2HDR(hdr)) {
3663 arc_hdr_l2hdr_destroy(hdr);
3667 mutex_exit(&dev->l2ad_mtx);
3670 if (HDR_HAS_L1HDR(hdr)) {
3671 arc_cksum_free(hdr);
3673 while (hdr->b_l1hdr.b_buf != NULL)
3674 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3677 if (hdr->b_l1hdr.b_thawed != NULL) {
3678 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3679 hdr->b_l1hdr.b_thawed = NULL;
3683 if (hdr->b_l1hdr.b_pabd != NULL) {
3684 arc_hdr_free_pabd(hdr);
3688 ASSERT3P(hdr->b_hash_next, ==, NULL);
3689 if (HDR_HAS_L1HDR(hdr)) {
3690 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3691 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3692 kmem_cache_free(hdr_full_cache, hdr);
3694 kmem_cache_free(hdr_l2only_cache, hdr);
3699 arc_buf_destroy(arc_buf_t *buf, void* tag)
3701 arc_buf_hdr_t *hdr = buf->b_hdr;
3702 kmutex_t *hash_lock = HDR_LOCK(hdr);
3704 if (hdr->b_l1hdr.b_state == arc_anon) {
3705 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3706 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3707 VERIFY0(remove_reference(hdr, NULL, tag));
3708 arc_hdr_destroy(hdr);
3712 mutex_enter(hash_lock);
3713 ASSERT3P(hdr, ==, buf->b_hdr);
3714 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3715 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3716 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3717 ASSERT3P(buf->b_data, !=, NULL);
3719 (void) remove_reference(hdr, hash_lock, tag);
3720 arc_buf_destroy_impl(buf);
3721 mutex_exit(hash_lock);
3725 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3726 * state of the header is dependent on its state prior to entering this
3727 * function. The following transitions are possible:
3729 * - arc_mru -> arc_mru_ghost
3730 * - arc_mfu -> arc_mfu_ghost
3731 * - arc_mru_ghost -> arc_l2c_only
3732 * - arc_mru_ghost -> deleted
3733 * - arc_mfu_ghost -> arc_l2c_only
3734 * - arc_mfu_ghost -> deleted
3737 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3739 arc_state_t *evicted_state, *state;
3740 int64_t bytes_evicted = 0;
3741 int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3742 zfs_arc_min_prescient_prefetch_ms : zfs_arc_min_prefetch_ms;
3744 ASSERT(MUTEX_HELD(hash_lock));
3745 ASSERT(HDR_HAS_L1HDR(hdr));
3747 state = hdr->b_l1hdr.b_state;
3748 if (GHOST_STATE(state)) {
3749 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3750 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3753 * l2arc_write_buffers() relies on a header's L1 portion
3754 * (i.e. its b_pabd field) during it's write phase.
3755 * Thus, we cannot push a header onto the arc_l2c_only
3756 * state (removing it's L1 piece) until the header is
3757 * done being written to the l2arc.
3759 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3760 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3761 return (bytes_evicted);
3764 ARCSTAT_BUMP(arcstat_deleted);
3765 bytes_evicted += HDR_GET_LSIZE(hdr);
3767 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3769 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3770 if (HDR_HAS_L2HDR(hdr)) {
3772 * This buffer is cached on the 2nd Level ARC;
3773 * don't destroy the header.
3775 arc_change_state(arc_l2c_only, hdr, hash_lock);
3777 * dropping from L1+L2 cached to L2-only,
3778 * realloc to remove the L1 header.
3780 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3783 arc_change_state(arc_anon, hdr, hash_lock);
3784 arc_hdr_destroy(hdr);
3786 return (bytes_evicted);
3789 ASSERT(state == arc_mru || state == arc_mfu);
3790 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3792 /* prefetch buffers have a minimum lifespan */
3793 if (HDR_IO_IN_PROGRESS(hdr) ||
3794 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3795 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access < min_lifetime * hz)) {
3796 ARCSTAT_BUMP(arcstat_evict_skip);
3797 return (bytes_evicted);
3800 ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3801 while (hdr->b_l1hdr.b_buf) {
3802 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3803 if (!mutex_tryenter(&buf->b_evict_lock)) {
3804 ARCSTAT_BUMP(arcstat_mutex_miss);
3807 if (buf->b_data != NULL)
3808 bytes_evicted += HDR_GET_LSIZE(hdr);
3809 mutex_exit(&buf->b_evict_lock);
3810 arc_buf_destroy_impl(buf);
3813 if (HDR_HAS_L2HDR(hdr)) {
3814 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3816 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3817 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3818 HDR_GET_LSIZE(hdr));
3820 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3821 HDR_GET_LSIZE(hdr));
3825 if (hdr->b_l1hdr.b_bufcnt == 0) {
3826 arc_cksum_free(hdr);
3828 bytes_evicted += arc_hdr_size(hdr);
3831 * If this hdr is being evicted and has a compressed
3832 * buffer then we discard it here before we change states.
3833 * This ensures that the accounting is updated correctly
3834 * in arc_free_data_impl().
3836 arc_hdr_free_pabd(hdr);
3838 arc_change_state(evicted_state, hdr, hash_lock);
3839 ASSERT(HDR_IN_HASH_TABLE(hdr));
3840 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3841 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3844 return (bytes_evicted);
3848 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3849 uint64_t spa, int64_t bytes)
3851 multilist_sublist_t *mls;
3852 uint64_t bytes_evicted = 0;
3854 kmutex_t *hash_lock;
3855 int evict_count = 0;
3857 ASSERT3P(marker, !=, NULL);
3858 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3860 mls = multilist_sublist_lock(ml, idx);
3862 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3863 hdr = multilist_sublist_prev(mls, marker)) {
3864 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3865 (evict_count >= zfs_arc_evict_batch_limit))
3869 * To keep our iteration location, move the marker
3870 * forward. Since we're not holding hdr's hash lock, we
3871 * must be very careful and not remove 'hdr' from the
3872 * sublist. Otherwise, other consumers might mistake the
3873 * 'hdr' as not being on a sublist when they call the
3874 * multilist_link_active() function (they all rely on
3875 * the hash lock protecting concurrent insertions and
3876 * removals). multilist_sublist_move_forward() was
3877 * specifically implemented to ensure this is the case
3878 * (only 'marker' will be removed and re-inserted).
3880 multilist_sublist_move_forward(mls, marker);
3883 * The only case where the b_spa field should ever be
3884 * zero, is the marker headers inserted by
3885 * arc_evict_state(). It's possible for multiple threads
3886 * to be calling arc_evict_state() concurrently (e.g.
3887 * dsl_pool_close() and zio_inject_fault()), so we must
3888 * skip any markers we see from these other threads.
3890 if (hdr->b_spa == 0)
3893 /* we're only interested in evicting buffers of a certain spa */
3894 if (spa != 0 && hdr->b_spa != spa) {
3895 ARCSTAT_BUMP(arcstat_evict_skip);
3899 hash_lock = HDR_LOCK(hdr);
3902 * We aren't calling this function from any code path
3903 * that would already be holding a hash lock, so we're
3904 * asserting on this assumption to be defensive in case
3905 * this ever changes. Without this check, it would be
3906 * possible to incorrectly increment arcstat_mutex_miss
3907 * below (e.g. if the code changed such that we called
3908 * this function with a hash lock held).
3910 ASSERT(!MUTEX_HELD(hash_lock));
3912 if (mutex_tryenter(hash_lock)) {
3913 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3914 mutex_exit(hash_lock);
3916 bytes_evicted += evicted;
3919 * If evicted is zero, arc_evict_hdr() must have
3920 * decided to skip this header, don't increment
3921 * evict_count in this case.
3927 * If arc_size isn't overflowing, signal any
3928 * threads that might happen to be waiting.
3930 * For each header evicted, we wake up a single
3931 * thread. If we used cv_broadcast, we could
3932 * wake up "too many" threads causing arc_size
3933 * to significantly overflow arc_c; since
3934 * arc_get_data_impl() doesn't check for overflow
3935 * when it's woken up (it doesn't because it's
3936 * possible for the ARC to be overflowing while
3937 * full of un-evictable buffers, and the
3938 * function should proceed in this case).
3940 * If threads are left sleeping, due to not
3941 * using cv_broadcast here, they will be woken
3942 * up via cv_broadcast in arc_adjust_cb() just
3943 * before arc_adjust_zthr sleeps.
3945 mutex_enter(&arc_adjust_lock);
3946 if (!arc_is_overflowing())
3947 cv_signal(&arc_adjust_waiters_cv);
3948 mutex_exit(&arc_adjust_lock);
3950 ARCSTAT_BUMP(arcstat_mutex_miss);
3954 multilist_sublist_unlock(mls);
3956 return (bytes_evicted);
3960 * Evict buffers from the given arc state, until we've removed the
3961 * specified number of bytes. Move the removed buffers to the
3962 * appropriate evict state.
3964 * This function makes a "best effort". It skips over any buffers
3965 * it can't get a hash_lock on, and so, may not catch all candidates.
3966 * It may also return without evicting as much space as requested.
3968 * If bytes is specified using the special value ARC_EVICT_ALL, this
3969 * will evict all available (i.e. unlocked and evictable) buffers from
3970 * the given arc state; which is used by arc_flush().
3973 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3974 arc_buf_contents_t type)
3976 uint64_t total_evicted = 0;
3977 multilist_t *ml = state->arcs_list[type];
3979 arc_buf_hdr_t **markers;
3981 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3983 num_sublists = multilist_get_num_sublists(ml);
3986 * If we've tried to evict from each sublist, made some
3987 * progress, but still have not hit the target number of bytes
3988 * to evict, we want to keep trying. The markers allow us to
3989 * pick up where we left off for each individual sublist, rather
3990 * than starting from the tail each time.
3992 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3993 for (int i = 0; i < num_sublists; i++) {
3994 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3997 * A b_spa of 0 is used to indicate that this header is
3998 * a marker. This fact is used in arc_adjust_type() and
3999 * arc_evict_state_impl().
4001 markers[i]->b_spa = 0;
4003 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4004 multilist_sublist_insert_tail(mls, markers[i]);
4005 multilist_sublist_unlock(mls);
4009 * While we haven't hit our target number of bytes to evict, or
4010 * we're evicting all available buffers.
4012 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
4013 int sublist_idx = multilist_get_random_index(ml);
4014 uint64_t scan_evicted = 0;
4017 * Try to reduce pinned dnodes with a floor of arc_dnode_limit.
4018 * Request that 10% of the LRUs be scanned by the superblock
4021 if (type == ARC_BUFC_DATA && aggsum_compare(&astat_dnode_size,
4022 arc_dnode_limit) > 0) {
4023 arc_prune_async((aggsum_upper_bound(&astat_dnode_size) -
4024 arc_dnode_limit) / sizeof (dnode_t) /
4025 zfs_arc_dnode_reduce_percent);
4029 * Start eviction using a randomly selected sublist,
4030 * this is to try and evenly balance eviction across all
4031 * sublists. Always starting at the same sublist
4032 * (e.g. index 0) would cause evictions to favor certain
4033 * sublists over others.
4035 for (int i = 0; i < num_sublists; i++) {
4036 uint64_t bytes_remaining;
4037 uint64_t bytes_evicted;
4039 if (bytes == ARC_EVICT_ALL)
4040 bytes_remaining = ARC_EVICT_ALL;
4041 else if (total_evicted < bytes)
4042 bytes_remaining = bytes - total_evicted;
4046 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
4047 markers[sublist_idx], spa, bytes_remaining);
4049 scan_evicted += bytes_evicted;
4050 total_evicted += bytes_evicted;
4052 /* we've reached the end, wrap to the beginning */
4053 if (++sublist_idx >= num_sublists)
4058 * If we didn't evict anything during this scan, we have
4059 * no reason to believe we'll evict more during another
4060 * scan, so break the loop.
4062 if (scan_evicted == 0) {
4063 /* This isn't possible, let's make that obvious */
4064 ASSERT3S(bytes, !=, 0);
4067 * When bytes is ARC_EVICT_ALL, the only way to
4068 * break the loop is when scan_evicted is zero.
4069 * In that case, we actually have evicted enough,
4070 * so we don't want to increment the kstat.
4072 if (bytes != ARC_EVICT_ALL) {
4073 ASSERT3S(total_evicted, <, bytes);
4074 ARCSTAT_BUMP(arcstat_evict_not_enough);
4081 for (int i = 0; i < num_sublists; i++) {
4082 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4083 multilist_sublist_remove(mls, markers[i]);
4084 multilist_sublist_unlock(mls);
4086 kmem_cache_free(hdr_full_cache, markers[i]);
4088 kmem_free(markers, sizeof (*markers) * num_sublists);
4090 return (total_evicted);
4094 * Flush all "evictable" data of the given type from the arc state
4095 * specified. This will not evict any "active" buffers (i.e. referenced).
4097 * When 'retry' is set to B_FALSE, the function will make a single pass
4098 * over the state and evict any buffers that it can. Since it doesn't
4099 * continually retry the eviction, it might end up leaving some buffers
4100 * in the ARC due to lock misses.
4102 * When 'retry' is set to B_TRUE, the function will continually retry the
4103 * eviction until *all* evictable buffers have been removed from the
4104 * state. As a result, if concurrent insertions into the state are
4105 * allowed (e.g. if the ARC isn't shutting down), this function might
4106 * wind up in an infinite loop, continually trying to evict buffers.
4109 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4112 uint64_t evicted = 0;
4114 while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
4115 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
4125 * Helper function for arc_prune_async() it is responsible for safely
4126 * handling the execution of a registered arc_prune_func_t.
4129 arc_prune_task(void *ptr)
4131 arc_prune_t *ap = (arc_prune_t *)ptr;
4132 arc_prune_func_t *func = ap->p_pfunc;
4135 func(ap->p_adjust, ap->p_private);
4137 zfs_refcount_remove(&ap->p_refcnt, func);
4141 * Notify registered consumers they must drop holds on a portion of the ARC
4142 * buffered they reference. This provides a mechanism to ensure the ARC can
4143 * honor the arc_meta_limit and reclaim otherwise pinned ARC buffers. This
4144 * is analogous to dnlc_reduce_cache() but more generic.
4146 * This operation is performed asynchronously so it may be safely called
4147 * in the context of the arc_reclaim_thread(). A reference is taken here
4148 * for each registered arc_prune_t and the arc_prune_task() is responsible
4149 * for releasing it once the registered arc_prune_func_t has completed.
4152 arc_prune_async(int64_t adjust)
4156 mutex_enter(&arc_prune_mtx);
4157 for (ap = list_head(&arc_prune_list); ap != NULL;
4158 ap = list_next(&arc_prune_list, ap)) {
4160 if (zfs_refcount_count(&ap->p_refcnt) >= 2)
4163 zfs_refcount_add(&ap->p_refcnt, ap->p_pfunc);
4164 ap->p_adjust = adjust;
4165 if (taskq_dispatch(arc_prune_taskq, arc_prune_task,
4166 ap, TQ_SLEEP) == TASKQID_INVALID) {
4167 zfs_refcount_remove(&ap->p_refcnt, ap->p_pfunc);
4170 ARCSTAT_BUMP(arcstat_prune);
4172 mutex_exit(&arc_prune_mtx);
4176 * Evict the specified number of bytes from the state specified,
4177 * restricting eviction to the spa and type given. This function
4178 * prevents us from trying to evict more from a state's list than
4179 * is "evictable", and to skip evicting altogether when passed a
4180 * negative value for "bytes". In contrast, arc_evict_state() will
4181 * evict everything it can, when passed a negative value for "bytes".
4184 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
4185 arc_buf_contents_t type)
4189 if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
4190 delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
4192 return (arc_evict_state(state, spa, delta, type));
4199 * The goal of this function is to evict enough meta data buffers from the
4200 * ARC in order to enforce the arc_meta_limit. Achieving this is slightly
4201 * more complicated than it appears because it is common for data buffers
4202 * to have holds on meta data buffers. In addition, dnode meta data buffers
4203 * will be held by the dnodes in the block preventing them from being freed.
4204 * This means we can't simply traverse the ARC and expect to always find
4205 * enough unheld meta data buffer to release.
4207 * Therefore, this function has been updated to make alternating passes
4208 * over the ARC releasing data buffers and then newly unheld meta data
4209 * buffers. This ensures forward progress is maintained and meta_used
4210 * will decrease. Normally this is sufficient, but if required the ARC
4211 * will call the registered prune callbacks causing dentry and inodes to
4212 * be dropped from the VFS cache. This will make dnode meta data buffers
4213 * available for reclaim.
4216 arc_adjust_meta_balanced(uint64_t meta_used)
4218 int64_t delta, prune = 0, adjustmnt;
4219 uint64_t total_evicted = 0;
4220 arc_buf_contents_t type = ARC_BUFC_DATA;
4221 int restarts = MAX(zfs_arc_meta_adjust_restarts, 0);
4225 * This slightly differs than the way we evict from the mru in
4226 * arc_adjust because we don't have a "target" value (i.e. no
4227 * "meta" arc_p). As a result, I think we can completely
4228 * cannibalize the metadata in the MRU before we evict the
4229 * metadata from the MFU. I think we probably need to implement a
4230 * "metadata arc_p" value to do this properly.
4232 adjustmnt = meta_used - arc_meta_limit;
4234 if (adjustmnt > 0 &&
4235 zfs_refcount_count(&arc_mru->arcs_esize[type]) > 0) {
4236 delta = MIN(zfs_refcount_count(&arc_mru->arcs_esize[type]),
4238 total_evicted += arc_adjust_impl(arc_mru, 0, delta, type);
4243 * We can't afford to recalculate adjustmnt here. If we do,
4244 * new metadata buffers can sneak into the MRU or ANON lists,
4245 * thus penalize the MFU metadata. Although the fudge factor is
4246 * small, it has been empirically shown to be significant for
4247 * certain workloads (e.g. creating many empty directories). As
4248 * such, we use the original calculation for adjustmnt, and
4249 * simply decrement the amount of data evicted from the MRU.
4252 if (adjustmnt > 0 &&
4253 zfs_refcount_count(&arc_mfu->arcs_esize[type]) > 0) {
4254 delta = MIN(zfs_refcount_count(&arc_mfu->arcs_esize[type]),
4256 total_evicted += arc_adjust_impl(arc_mfu, 0, delta, type);
4259 adjustmnt = meta_used - arc_meta_limit;
4261 if (adjustmnt > 0 &&
4262 zfs_refcount_count(&arc_mru_ghost->arcs_esize[type]) > 0) {
4263 delta = MIN(adjustmnt,
4264 zfs_refcount_count(&arc_mru_ghost->arcs_esize[type]));
4265 total_evicted += arc_adjust_impl(arc_mru_ghost, 0, delta, type);
4269 if (adjustmnt > 0 &&
4270 zfs_refcount_count(&arc_mfu_ghost->arcs_esize[type]) > 0) {
4271 delta = MIN(adjustmnt,
4272 zfs_refcount_count(&arc_mfu_ghost->arcs_esize[type]));
4273 total_evicted += arc_adjust_impl(arc_mfu_ghost, 0, delta, type);
4277 * If after attempting to make the requested adjustment to the ARC
4278 * the meta limit is still being exceeded then request that the
4279 * higher layers drop some cached objects which have holds on ARC
4280 * meta buffers. Requests to the upper layers will be made with
4281 * increasingly large scan sizes until the ARC is below the limit.
4283 if (meta_used > arc_meta_limit) {
4284 if (type == ARC_BUFC_DATA) {
4285 type = ARC_BUFC_METADATA;
4287 type = ARC_BUFC_DATA;
4289 if (zfs_arc_meta_prune) {
4290 prune += zfs_arc_meta_prune;
4291 arc_prune_async(prune);
4300 return (total_evicted);
4304 * Evict metadata buffers from the cache, such that arc_meta_used is
4305 * capped by the arc_meta_limit tunable.
4308 arc_adjust_meta_only(uint64_t meta_used)
4310 uint64_t total_evicted = 0;
4314 * If we're over the meta limit, we want to evict enough
4315 * metadata to get back under the meta limit. We don't want to
4316 * evict so much that we drop the MRU below arc_p, though. If
4317 * we're over the meta limit more than we're over arc_p, we
4318 * evict some from the MRU here, and some from the MFU below.
4320 target = MIN((int64_t)(meta_used - arc_meta_limit),
4321 (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4322 zfs_refcount_count(&arc_mru->arcs_size) - arc_p));
4324 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4327 * Similar to the above, we want to evict enough bytes to get us
4328 * below the meta limit, but not so much as to drop us below the
4329 * space allotted to the MFU (which is defined as arc_c - arc_p).
4331 target = MIN((int64_t)(meta_used - arc_meta_limit),
4332 (int64_t)(zfs_refcount_count(&arc_mfu->arcs_size) -
4335 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4337 return (total_evicted);
4341 arc_adjust_meta(uint64_t meta_used)
4343 if (zfs_arc_meta_strategy == ARC_STRATEGY_META_ONLY)
4344 return (arc_adjust_meta_only(meta_used));
4346 return (arc_adjust_meta_balanced(meta_used));
4350 * Return the type of the oldest buffer in the given arc state
4352 * This function will select a random sublist of type ARC_BUFC_DATA and
4353 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
4354 * is compared, and the type which contains the "older" buffer will be
4357 static arc_buf_contents_t
4358 arc_adjust_type(arc_state_t *state)
4360 multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
4361 multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
4362 int data_idx = multilist_get_random_index(data_ml);
4363 int meta_idx = multilist_get_random_index(meta_ml);
4364 multilist_sublist_t *data_mls;
4365 multilist_sublist_t *meta_mls;
4366 arc_buf_contents_t type;
4367 arc_buf_hdr_t *data_hdr;
4368 arc_buf_hdr_t *meta_hdr;
4371 * We keep the sublist lock until we're finished, to prevent
4372 * the headers from being destroyed via arc_evict_state().
4374 data_mls = multilist_sublist_lock(data_ml, data_idx);
4375 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4378 * These two loops are to ensure we skip any markers that
4379 * might be at the tail of the lists due to arc_evict_state().
4382 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4383 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4384 if (data_hdr->b_spa != 0)
4388 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4389 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4390 if (meta_hdr->b_spa != 0)
4394 if (data_hdr == NULL && meta_hdr == NULL) {
4395 type = ARC_BUFC_DATA;
4396 } else if (data_hdr == NULL) {
4397 ASSERT3P(meta_hdr, !=, NULL);
4398 type = ARC_BUFC_METADATA;
4399 } else if (meta_hdr == NULL) {
4400 ASSERT3P(data_hdr, !=, NULL);
4401 type = ARC_BUFC_DATA;
4403 ASSERT3P(data_hdr, !=, NULL);
4404 ASSERT3P(meta_hdr, !=, NULL);
4406 /* The headers can't be on the sublist without an L1 header */
4407 ASSERT(HDR_HAS_L1HDR(data_hdr));
4408 ASSERT(HDR_HAS_L1HDR(meta_hdr));
4410 if (data_hdr->b_l1hdr.b_arc_access <
4411 meta_hdr->b_l1hdr.b_arc_access) {
4412 type = ARC_BUFC_DATA;
4414 type = ARC_BUFC_METADATA;
4418 multilist_sublist_unlock(meta_mls);
4419 multilist_sublist_unlock(data_mls);
4425 * Evict buffers from the cache, such that arc_size is capped by arc_c.
4430 uint64_t total_evicted = 0;
4433 uint64_t asize = aggsum_value(&arc_size);
4434 uint64_t ameta = aggsum_value(&arc_meta_used);
4437 * If we're over arc_meta_limit, we want to correct that before
4438 * potentially evicting data buffers below.
4440 total_evicted += arc_adjust_meta(ameta);
4445 * If we're over the target cache size, we want to evict enough
4446 * from the list to get back to our target size. We don't want
4447 * to evict too much from the MRU, such that it drops below
4448 * arc_p. So, if we're over our target cache size more than
4449 * the MRU is over arc_p, we'll evict enough to get back to
4450 * arc_p here, and then evict more from the MFU below.
4452 target = MIN((int64_t)(asize - arc_c),
4453 (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4454 zfs_refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4457 * If we're below arc_meta_min, always prefer to evict data.
4458 * Otherwise, try to satisfy the requested number of bytes to
4459 * evict from the type which contains older buffers; in an
4460 * effort to keep newer buffers in the cache regardless of their
4461 * type. If we cannot satisfy the number of bytes from this
4462 * type, spill over into the next type.
4464 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
4465 ameta > arc_meta_min) {
4466 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4467 total_evicted += bytes;
4470 * If we couldn't evict our target number of bytes from
4471 * metadata, we try to get the rest from data.
4476 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4478 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4479 total_evicted += bytes;
4482 * If we couldn't evict our target number of bytes from
4483 * data, we try to get the rest from metadata.
4488 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4492 * Re-sum ARC stats after the first round of evictions.
4494 asize = aggsum_value(&arc_size);
4495 ameta = aggsum_value(&arc_meta_used);
4500 * Now that we've tried to evict enough from the MRU to get its
4501 * size back to arc_p, if we're still above the target cache
4502 * size, we evict the rest from the MFU.
4504 target = asize - arc_c;
4506 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4507 ameta > arc_meta_min) {
4508 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4509 total_evicted += bytes;
4512 * If we couldn't evict our target number of bytes from
4513 * metadata, we try to get the rest from data.
4518 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4520 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4521 total_evicted += bytes;
4524 * If we couldn't evict our target number of bytes from
4525 * data, we try to get the rest from data.
4530 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4534 * Adjust ghost lists
4536 * In addition to the above, the ARC also defines target values
4537 * for the ghost lists. The sum of the mru list and mru ghost
4538 * list should never exceed the target size of the cache, and
4539 * the sum of the mru list, mfu list, mru ghost list, and mfu
4540 * ghost list should never exceed twice the target size of the
4541 * cache. The following logic enforces these limits on the ghost
4542 * caches, and evicts from them as needed.
4544 target = zfs_refcount_count(&arc_mru->arcs_size) +
4545 zfs_refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4547 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4548 total_evicted += bytes;
4553 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4556 * We assume the sum of the mru list and mfu list is less than
4557 * or equal to arc_c (we enforced this above), which means we
4558 * can use the simpler of the two equations below:
4560 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4561 * mru ghost + mfu ghost <= arc_c
4563 target = zfs_refcount_count(&arc_mru_ghost->arcs_size) +
4564 zfs_refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4566 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4567 total_evicted += bytes;
4572 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4574 return (total_evicted);
4578 arc_flush(spa_t *spa, boolean_t retry)
4583 * If retry is B_TRUE, a spa must not be specified since we have
4584 * no good way to determine if all of a spa's buffers have been
4585 * evicted from an arc state.
4587 ASSERT(!retry || spa == 0);
4590 guid = spa_load_guid(spa);
4592 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4593 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4595 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4596 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4598 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4599 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4601 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4602 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4606 arc_reduce_target_size(int64_t to_free)
4608 uint64_t asize = aggsum_value(&arc_size);
4609 if (arc_c > arc_c_min) {
4610 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4611 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4612 if (arc_c > arc_c_min + to_free)
4613 atomic_add_64(&arc_c, -to_free);
4617 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4619 arc_c = MAX(asize, arc_c_min);
4621 arc_p = (arc_c >> 1);
4623 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4626 ASSERT(arc_c >= arc_c_min);
4627 ASSERT((int64_t)arc_p >= 0);
4630 if (asize > arc_c) {
4631 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, asize,
4633 /* See comment in arc_adjust_cb_check() on why lock+flag */
4634 mutex_enter(&arc_adjust_lock);
4635 arc_adjust_needed = B_TRUE;
4636 mutex_exit(&arc_adjust_lock);
4637 zthr_wakeup(arc_adjust_zthr);
4641 typedef enum free_memory_reason_t {
4646 FMR_PAGES_PP_MAXIMUM,
4649 } free_memory_reason_t;
4651 int64_t last_free_memory;
4652 free_memory_reason_t last_free_reason;
4655 * Additional reserve of pages for pp_reserve.
4657 int64_t arc_pages_pp_reserve = 64;
4660 * Additional reserve of pages for swapfs.
4662 int64_t arc_swapfs_reserve = 64;
4665 * Return the amount of memory that can be consumed before reclaim will be
4666 * needed. Positive if there is sufficient free memory, negative indicates
4667 * the amount of memory that needs to be freed up.
4670 arc_available_memory(void)
4672 int64_t lowest = INT64_MAX;
4674 free_memory_reason_t r = FMR_UNKNOWN;
4679 * Cooperate with pagedaemon when it's time for it to scan
4680 * and reclaim some pages.
4682 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4690 n = PAGESIZE * (-needfree);
4698 * check that we're out of range of the pageout scanner. It starts to
4699 * schedule paging if freemem is less than lotsfree and needfree.
4700 * lotsfree is the high-water mark for pageout, and needfree is the
4701 * number of needed free pages. We add extra pages here to make sure
4702 * the scanner doesn't start up while we're freeing memory.
4704 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4711 * check to make sure that swapfs has enough space so that anon
4712 * reservations can still succeed. anon_resvmem() checks that the
4713 * availrmem is greater than swapfs_minfree, and the number of reserved
4714 * swap pages. We also add a bit of extra here just to prevent
4715 * circumstances from getting really dire.
4717 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4718 desfree - arc_swapfs_reserve);
4721 r = FMR_SWAPFS_MINFREE;
4726 * Check that we have enough availrmem that memory locking (e.g., via
4727 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
4728 * stores the number of pages that cannot be locked; when availrmem
4729 * drops below pages_pp_maximum, page locking mechanisms such as
4730 * page_pp_lock() will fail.)
4732 n = PAGESIZE * (availrmem - pages_pp_maximum -
4733 arc_pages_pp_reserve);
4736 r = FMR_PAGES_PP_MAXIMUM;
4739 #endif /* __FreeBSD__ */
4740 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4742 * If we're on an i386 platform, it's possible that we'll exhaust the
4743 * kernel heap space before we ever run out of available physical
4744 * memory. Most checks of the size of the heap_area compare against
4745 * tune.t_minarmem, which is the minimum available real memory that we
4746 * can have in the system. However, this is generally fixed at 25 pages
4747 * which is so low that it's useless. In this comparison, we seek to
4748 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4749 * heap is allocated. (Or, in the calculation, if less than 1/4th is
4752 n = uma_avail() - (long)(uma_limit() / 4);
4760 * If zio data pages are being allocated out of a separate heap segment,
4761 * then enforce that the size of available vmem for this arena remains
4762 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4764 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4765 * memory (in the zio_arena) free, which can avoid memory
4766 * fragmentation issues.
4768 if (zio_arena != NULL) {
4769 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4770 (vmem_size(zio_arena, VMEM_ALLOC) >>
4771 arc_zio_arena_free_shift);
4779 /* Every 100 calls, free a small amount */
4780 if (spa_get_random(100) == 0)
4782 #endif /* _KERNEL */
4784 last_free_memory = lowest;
4785 last_free_reason = r;
4786 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4792 * Determine if the system is under memory pressure and is asking
4793 * to reclaim memory. A return value of B_TRUE indicates that the system
4794 * is under memory pressure and that the arc should adjust accordingly.
4797 arc_reclaim_needed(void)
4799 return (arc_available_memory() < 0);
4802 extern kmem_cache_t *zio_buf_cache[];
4803 extern kmem_cache_t *zio_data_buf_cache[];
4804 extern kmem_cache_t *range_seg_cache;
4805 extern kmem_cache_t *abd_chunk_cache;
4807 static __noinline void
4808 arc_kmem_reap_soon(void)
4811 kmem_cache_t *prev_cache = NULL;
4812 kmem_cache_t *prev_data_cache = NULL;
4814 DTRACE_PROBE(arc__kmem_reap_start);
4816 if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4818 * We are exceeding our meta-data cache limit.
4819 * Purge some DNLC entries to release holds on meta-data.
4821 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4825 * Reclaim unused memory from all kmem caches.
4831 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4832 if (zio_buf_cache[i] != prev_cache) {
4833 prev_cache = zio_buf_cache[i];
4834 kmem_cache_reap_soon(zio_buf_cache[i]);
4836 if (zio_data_buf_cache[i] != prev_data_cache) {
4837 prev_data_cache = zio_data_buf_cache[i];
4838 kmem_cache_reap_soon(zio_data_buf_cache[i]);
4841 kmem_cache_reap_soon(abd_chunk_cache);
4842 kmem_cache_reap_soon(buf_cache);
4843 kmem_cache_reap_soon(hdr_full_cache);
4844 kmem_cache_reap_soon(hdr_l2only_cache);
4845 kmem_cache_reap_soon(range_seg_cache);
4848 if (zio_arena != NULL) {
4850 * Ask the vmem arena to reclaim unused memory from its
4853 vmem_qcache_reap(zio_arena);
4856 DTRACE_PROBE(arc__kmem_reap_end);
4861 arc_adjust_cb_check(void *arg, zthr_t *zthr)
4864 * This is necessary in order for the mdb ::arc dcmd to
4865 * show up to date information. Since the ::arc command
4866 * does not call the kstat's update function, without
4867 * this call, the command may show stale stats for the
4868 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4869 * with this change, the data might be up to 1 second
4870 * out of date(the arc_adjust_zthr has a maximum sleep
4871 * time of 1 second); but that should suffice. The
4872 * arc_state_t structures can be queried directly if more
4873 * accurate information is needed.
4875 if (arc_ksp != NULL)
4876 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4879 * We have to rely on arc_get_data_impl() to tell us when to adjust,
4880 * rather than checking if we are overflowing here, so that we are
4881 * sure to not leave arc_get_data_impl() waiting on
4882 * arc_adjust_waiters_cv. If we have become "not overflowing" since
4883 * arc_get_data_impl() checked, we need to wake it up. We could
4884 * broadcast the CV here, but arc_get_data_impl() may have not yet
4885 * gone to sleep. We would need to use a mutex to ensure that this
4886 * function doesn't broadcast until arc_get_data_impl() has gone to
4887 * sleep (e.g. the arc_adjust_lock). However, the lock ordering of
4888 * such a lock would necessarily be incorrect with respect to the
4889 * zthr_lock, which is held before this function is called, and is
4890 * held by arc_get_data_impl() when it calls zthr_wakeup().
4892 return (arc_adjust_needed);
4896 * Keep arc_size under arc_c by running arc_adjust which evicts data
4900 arc_adjust_cb(void *arg, zthr_t *zthr)
4902 uint64_t evicted = 0;
4904 /* Evict from cache */
4905 evicted = arc_adjust();
4908 * If evicted is zero, we couldn't evict anything
4909 * via arc_adjust(). This could be due to hash lock
4910 * collisions, but more likely due to the majority of
4911 * arc buffers being unevictable. Therefore, even if
4912 * arc_size is above arc_c, another pass is unlikely to
4913 * be helpful and could potentially cause us to enter an
4914 * infinite loop. Additionally, zthr_iscancelled() is
4915 * checked here so that if the arc is shutting down, the
4916 * broadcast will wake any remaining arc adjust waiters.
4918 mutex_enter(&arc_adjust_lock);
4919 arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
4920 evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4921 if (!arc_adjust_needed) {
4923 * We're either no longer overflowing, or we
4924 * can't evict anything more, so we should wake
4927 cv_broadcast(&arc_adjust_waiters_cv);
4929 mutex_exit(&arc_adjust_lock);
4934 arc_reap_cb_check(void *arg, zthr_t *zthr)
4936 int64_t free_memory = arc_available_memory();
4939 * If a kmem reap is already active, don't schedule more. We must
4940 * check for this because kmem_cache_reap_soon() won't actually
4941 * block on the cache being reaped (this is to prevent callers from
4942 * becoming implicitly blocked by a system-wide kmem reap -- which,
4943 * on a system with many, many full magazines, can take minutes).
4945 if (!kmem_cache_reap_active() &&
4947 arc_no_grow = B_TRUE;
4950 * Wait at least zfs_grow_retry (default 60) seconds
4951 * before considering growing.
4953 arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4955 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4956 arc_no_grow = B_TRUE;
4957 } else if (gethrtime() >= arc_growtime) {
4958 arc_no_grow = B_FALSE;
4965 * Keep enough free memory in the system by reaping the ARC's kmem
4966 * caches. To cause more slabs to be reapable, we may reduce the
4967 * target size of the cache (arc_c), causing the arc_adjust_cb()
4968 * to free more buffers.
4972 arc_reap_cb(void *arg, zthr_t *zthr)
4974 int64_t free_memory;
4977 * Kick off asynchronous kmem_reap()'s of all our caches.
4979 arc_kmem_reap_soon();
4982 * Wait at least arc_kmem_cache_reap_retry_ms between
4983 * arc_kmem_reap_soon() calls. Without this check it is possible to
4984 * end up in a situation where we spend lots of time reaping
4985 * caches, while we're near arc_c_min. Waiting here also gives the
4986 * subsequent free memory check a chance of finding that the
4987 * asynchronous reap has already freed enough memory, and we don't
4988 * need to call arc_reduce_target_size().
4990 delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4993 * Reduce the target size as needed to maintain the amount of free
4994 * memory in the system at a fraction of the arc_size (1/128th by
4995 * default). If oversubscribed (free_memory < 0) then reduce the
4996 * target arc_size by the deficit amount plus the fractional
4997 * amount. If free memory is positive but less then the fractional
4998 * amount, reduce by what is needed to hit the fractional amount.
5000 free_memory = arc_available_memory();
5003 (arc_c >> arc_shrink_shift) - free_memory;
5007 to_free = MAX(to_free, ptob(needfree));
5010 arc_reduce_target_size(to_free);
5014 static u_int arc_dnlc_evicts_arg;
5015 extern struct vfsops zfs_vfsops;
5018 arc_dnlc_evicts_thread(void *dummy __unused)
5023 CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
5025 mutex_enter(&arc_dnlc_evicts_lock);
5026 while (!arc_dnlc_evicts_thread_exit) {
5027 CALLB_CPR_SAFE_BEGIN(&cpr);
5028 (void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
5029 CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
5030 if (arc_dnlc_evicts_arg != 0) {
5031 percent = arc_dnlc_evicts_arg;
5032 mutex_exit(&arc_dnlc_evicts_lock);
5034 vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
5036 mutex_enter(&arc_dnlc_evicts_lock);
5038 * Clear our token only after vnlru_free()
5039 * pass is done, to avoid false queueing of
5042 arc_dnlc_evicts_arg = 0;
5045 arc_dnlc_evicts_thread_exit = FALSE;
5046 cv_broadcast(&arc_dnlc_evicts_cv);
5047 CALLB_CPR_EXIT(&cpr);
5052 dnlc_reduce_cache(void *arg)
5056 percent = (u_int)(uintptr_t)arg;
5057 mutex_enter(&arc_dnlc_evicts_lock);
5058 if (arc_dnlc_evicts_arg == 0) {
5059 arc_dnlc_evicts_arg = percent;
5060 cv_broadcast(&arc_dnlc_evicts_cv);
5062 mutex_exit(&arc_dnlc_evicts_lock);
5066 * Adapt arc info given the number of bytes we are trying to add and
5067 * the state that we are comming from. This function is only called
5068 * when we are adding new content to the cache.
5071 arc_adapt(int bytes, arc_state_t *state)
5074 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
5075 int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
5076 int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
5078 if (state == arc_l2c_only)
5083 * Adapt the target size of the MRU list:
5084 * - if we just hit in the MRU ghost list, then increase
5085 * the target size of the MRU list.
5086 * - if we just hit in the MFU ghost list, then increase
5087 * the target size of the MFU list by decreasing the
5088 * target size of the MRU list.
5090 if (state == arc_mru_ghost) {
5091 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
5092 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
5094 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
5095 } else if (state == arc_mfu_ghost) {
5098 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
5099 mult = MIN(mult, 10);
5101 delta = MIN(bytes * mult, arc_p);
5102 arc_p = MAX(arc_p_min, arc_p - delta);
5104 ASSERT((int64_t)arc_p >= 0);
5107 * Wake reap thread if we do not have any available memory
5109 if (arc_reclaim_needed()) {
5110 zthr_wakeup(arc_reap_zthr);
5117 if (arc_c >= arc_c_max)
5121 * If we're within (2 * maxblocksize) bytes of the target
5122 * cache size, increment the target cache size
5124 if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
5126 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
5127 atomic_add_64(&arc_c, (int64_t)bytes);
5128 if (arc_c > arc_c_max)
5130 else if (state == arc_anon)
5131 atomic_add_64(&arc_p, (int64_t)bytes);
5135 ASSERT((int64_t)arc_p >= 0);
5139 * Check if arc_size has grown past our upper threshold, determined by
5140 * zfs_arc_overflow_shift.
5143 arc_is_overflowing(void)
5145 /* Always allow at least one block of overflow */
5146 int64_t overflow = MAX(SPA_MAXBLOCKSIZE,
5147 arc_c >> zfs_arc_overflow_shift);
5150 * We just compare the lower bound here for performance reasons. Our
5151 * primary goals are to make sure that the arc never grows without
5152 * bound, and that it can reach its maximum size. This check
5153 * accomplishes both goals. The maximum amount we could run over by is
5154 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
5155 * in the ARC. In practice, that's in the tens of MB, which is low
5156 * enough to be safe.
5158 return (aggsum_lower_bound(&arc_size) >= (int64_t)arc_c + overflow);
5162 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag, boolean_t do_adapt)
5164 arc_buf_contents_t type = arc_buf_type(hdr);
5166 arc_get_data_impl(hdr, size, tag, do_adapt);
5167 if (type == ARC_BUFC_METADATA) {
5168 return (abd_alloc(size, B_TRUE));
5170 ASSERT(type == ARC_BUFC_DATA);
5171 return (abd_alloc(size, B_FALSE));
5176 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5178 arc_buf_contents_t type = arc_buf_type(hdr);
5180 arc_get_data_impl(hdr, size, tag, B_TRUE);
5181 if (type == ARC_BUFC_METADATA) {
5182 return (zio_buf_alloc(size));
5184 ASSERT(type == ARC_BUFC_DATA);
5185 return (zio_data_buf_alloc(size));
5190 * Allocate a block and return it to the caller. If we are hitting the
5191 * hard limit for the cache size, we must sleep, waiting for the eviction
5192 * thread to catch up. If we're past the target size but below the hard
5193 * limit, we'll only signal the reclaim thread and continue on.
5196 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag, boolean_t do_adapt)
5198 arc_state_t *state = hdr->b_l1hdr.b_state;
5199 arc_buf_contents_t type = arc_buf_type(hdr);
5202 arc_adapt(size, state);
5205 * If arc_size is currently overflowing, and has grown past our
5206 * upper limit, we must be adding data faster than the evict
5207 * thread can evict. Thus, to ensure we don't compound the
5208 * problem by adding more data and forcing arc_size to grow even
5209 * further past it's target size, we halt and wait for the
5210 * eviction thread to catch up.
5212 * It's also possible that the reclaim thread is unable to evict
5213 * enough buffers to get arc_size below the overflow limit (e.g.
5214 * due to buffers being un-evictable, or hash lock collisions).
5215 * In this case, we want to proceed regardless if we're
5216 * overflowing; thus we don't use a while loop here.
5218 if (arc_is_overflowing()) {
5219 mutex_enter(&arc_adjust_lock);
5222 * Now that we've acquired the lock, we may no longer be
5223 * over the overflow limit, lets check.
5225 * We're ignoring the case of spurious wake ups. If that
5226 * were to happen, it'd let this thread consume an ARC
5227 * buffer before it should have (i.e. before we're under
5228 * the overflow limit and were signalled by the reclaim
5229 * thread). As long as that is a rare occurrence, it
5230 * shouldn't cause any harm.
5232 if (arc_is_overflowing()) {
5233 arc_adjust_needed = B_TRUE;
5234 zthr_wakeup(arc_adjust_zthr);
5235 (void) cv_wait(&arc_adjust_waiters_cv,
5238 mutex_exit(&arc_adjust_lock);
5241 VERIFY3U(hdr->b_type, ==, type);
5242 if (type == ARC_BUFC_METADATA) {
5243 arc_space_consume(size, ARC_SPACE_META);
5245 arc_space_consume(size, ARC_SPACE_DATA);
5249 * Update the state size. Note that ghost states have a
5250 * "ghost size" and so don't need to be updated.
5252 if (!GHOST_STATE(state)) {
5254 (void) zfs_refcount_add_many(&state->arcs_size, size, tag);
5257 * If this is reached via arc_read, the link is
5258 * protected by the hash lock. If reached via
5259 * arc_buf_alloc, the header should not be accessed by
5260 * any other thread. And, if reached via arc_read_done,
5261 * the hash lock will protect it if it's found in the
5262 * hash table; otherwise no other thread should be
5263 * trying to [add|remove]_reference it.
5265 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5266 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5267 (void) zfs_refcount_add_many(&state->arcs_esize[type],
5272 * If we are growing the cache, and we are adding anonymous
5273 * data, and we have outgrown arc_p, update arc_p
5275 if (aggsum_upper_bound(&arc_size) < arc_c &&
5276 hdr->b_l1hdr.b_state == arc_anon &&
5277 (zfs_refcount_count(&arc_anon->arcs_size) +
5278 zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
5279 arc_p = MIN(arc_c, arc_p + size);
5281 ARCSTAT_BUMP(arcstat_allocated);
5285 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5287 arc_free_data_impl(hdr, size, tag);
5292 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5294 arc_buf_contents_t type = arc_buf_type(hdr);
5296 arc_free_data_impl(hdr, size, tag);
5297 if (type == ARC_BUFC_METADATA) {
5298 zio_buf_free(buf, size);
5300 ASSERT(type == ARC_BUFC_DATA);
5301 zio_data_buf_free(buf, size);
5306 * Free the arc data buffer.
5309 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5311 arc_state_t *state = hdr->b_l1hdr.b_state;
5312 arc_buf_contents_t type = arc_buf_type(hdr);
5314 /* protected by hash lock, if in the hash table */
5315 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5316 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5317 ASSERT(state != arc_anon && state != arc_l2c_only);
5319 (void) zfs_refcount_remove_many(&state->arcs_esize[type],
5322 (void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
5324 VERIFY3U(hdr->b_type, ==, type);
5325 if (type == ARC_BUFC_METADATA) {
5326 arc_space_return(size, ARC_SPACE_META);
5328 ASSERT(type == ARC_BUFC_DATA);
5329 arc_space_return(size, ARC_SPACE_DATA);
5334 * This routine is called whenever a buffer is accessed.
5335 * NOTE: the hash lock is dropped in this function.
5338 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5342 ASSERT(MUTEX_HELD(hash_lock));
5343 ASSERT(HDR_HAS_L1HDR(hdr));
5345 if (hdr->b_l1hdr.b_state == arc_anon) {
5347 * This buffer is not in the cache, and does not
5348 * appear in our "ghost" list. Add the new buffer
5352 ASSERT0(hdr->b_l1hdr.b_arc_access);
5353 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5354 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5355 arc_change_state(arc_mru, hdr, hash_lock);
5357 } else if (hdr->b_l1hdr.b_state == arc_mru) {
5358 now = ddi_get_lbolt();
5361 * If this buffer is here because of a prefetch, then either:
5362 * - clear the flag if this is a "referencing" read
5363 * (any subsequent access will bump this into the MFU state).
5365 * - move the buffer to the head of the list if this is
5366 * another prefetch (to make it less likely to be evicted).
5368 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5369 if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5370 /* link protected by hash lock */
5371 ASSERT(multilist_link_active(
5372 &hdr->b_l1hdr.b_arc_node));
5374 arc_hdr_clear_flags(hdr,
5376 ARC_FLAG_PRESCIENT_PREFETCH);
5377 ARCSTAT_BUMP(arcstat_mru_hits);
5379 hdr->b_l1hdr.b_arc_access = now;
5384 * This buffer has been "accessed" only once so far,
5385 * but it is still in the cache. Move it to the MFU
5388 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5390 * More than 125ms have passed since we
5391 * instantiated this buffer. Move it to the
5392 * most frequently used state.
5394 hdr->b_l1hdr.b_arc_access = now;
5395 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5396 arc_change_state(arc_mfu, hdr, hash_lock);
5398 atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
5399 ARCSTAT_BUMP(arcstat_mru_hits);
5400 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5401 arc_state_t *new_state;
5403 * This buffer has been "accessed" recently, but
5404 * was evicted from the cache. Move it to the
5408 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5409 new_state = arc_mru;
5410 if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5411 arc_hdr_clear_flags(hdr,
5413 ARC_FLAG_PRESCIENT_PREFETCH);
5415 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5417 new_state = arc_mfu;
5418 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5421 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5422 arc_change_state(new_state, hdr, hash_lock);
5424 atomic_inc_32(&hdr->b_l1hdr.b_mru_ghost_hits);
5425 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5426 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
5428 * This buffer has been accessed more than once and is
5429 * still in the cache. Keep it in the MFU state.
5431 * NOTE: an add_reference() that occurred when we did
5432 * the arc_read() will have kicked this off the list.
5433 * If it was a prefetch, we will explicitly move it to
5434 * the head of the list now.
5437 atomic_inc_32(&hdr->b_l1hdr.b_mfu_hits);
5438 ARCSTAT_BUMP(arcstat_mfu_hits);
5439 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5440 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5441 arc_state_t *new_state = arc_mfu;
5443 * This buffer has been accessed more than once but has
5444 * been evicted from the cache. Move it back to the
5448 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5450 * This is a prefetch access...
5451 * move this block back to the MRU state.
5453 new_state = arc_mru;
5456 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5457 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5458 arc_change_state(new_state, hdr, hash_lock);
5460 atomic_inc_32(&hdr->b_l1hdr.b_mfu_ghost_hits);
5461 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5462 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5464 * This buffer is on the 2nd Level ARC.
5467 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5468 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5469 arc_change_state(arc_mfu, hdr, hash_lock);
5471 ASSERT(!"invalid arc state");
5476 * This routine is called by dbuf_hold() to update the arc_access() state
5477 * which otherwise would be skipped for entries in the dbuf cache.
5480 arc_buf_access(arc_buf_t *buf)
5482 mutex_enter(&buf->b_evict_lock);
5483 arc_buf_hdr_t *hdr = buf->b_hdr;
5486 * Avoid taking the hash_lock when possible as an optimization.
5487 * The header must be checked again under the hash_lock in order
5488 * to handle the case where it is concurrently being released.
5490 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5491 mutex_exit(&buf->b_evict_lock);
5492 ARCSTAT_BUMP(arcstat_access_skip);
5496 kmutex_t *hash_lock = HDR_LOCK(hdr);
5497 mutex_enter(hash_lock);
5499 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5500 mutex_exit(hash_lock);
5501 mutex_exit(&buf->b_evict_lock);
5502 ARCSTAT_BUMP(arcstat_access_skip);
5506 mutex_exit(&buf->b_evict_lock);
5508 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5509 hdr->b_l1hdr.b_state == arc_mfu);
5511 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5512 arc_access(hdr, hash_lock);
5513 mutex_exit(hash_lock);
5515 ARCSTAT_BUMP(arcstat_hits);
5516 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5517 demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5520 /* a generic arc_read_done_func_t which you can use */
5523 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5524 arc_buf_t *buf, void *arg)
5529 bcopy(buf->b_data, arg, arc_buf_size(buf));
5530 arc_buf_destroy(buf, arg);
5533 /* a generic arc_read_done_func_t */
5536 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5537 arc_buf_t *buf, void *arg)
5539 arc_buf_t **bufp = arg;
5541 ASSERT(zio == NULL || zio->io_error != 0);
5544 ASSERT(zio == NULL || zio->io_error == 0);
5546 ASSERT(buf->b_data != NULL);
5551 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5553 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5554 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5555 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
5557 if (HDR_COMPRESSION_ENABLED(hdr)) {
5558 ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
5559 BP_GET_COMPRESS(bp));
5561 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5562 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5567 arc_read_done(zio_t *zio)
5569 arc_buf_hdr_t *hdr = zio->io_private;
5570 kmutex_t *hash_lock = NULL;
5571 arc_callback_t *callback_list;
5572 arc_callback_t *acb;
5573 boolean_t freeable = B_FALSE;
5574 boolean_t no_zio_error = (zio->io_error == 0);
5577 * The hdr was inserted into hash-table and removed from lists
5578 * prior to starting I/O. We should find this header, since
5579 * it's in the hash table, and it should be legit since it's
5580 * not possible to evict it during the I/O. The only possible
5581 * reason for it not to be found is if we were freed during the
5584 if (HDR_IN_HASH_TABLE(hdr)) {
5585 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5586 ASSERT3U(hdr->b_dva.dva_word[0], ==,
5587 BP_IDENTITY(zio->io_bp)->dva_word[0]);
5588 ASSERT3U(hdr->b_dva.dva_word[1], ==,
5589 BP_IDENTITY(zio->io_bp)->dva_word[1]);
5591 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
5594 ASSERT((found == hdr &&
5595 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5596 (found == hdr && HDR_L2_READING(hdr)));
5597 ASSERT3P(hash_lock, !=, NULL);
5601 /* byteswap if necessary */
5602 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5603 if (BP_GET_LEVEL(zio->io_bp) > 0) {
5604 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5606 hdr->b_l1hdr.b_byteswap =
5607 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5610 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5614 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5615 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5616 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5618 callback_list = hdr->b_l1hdr.b_acb;
5619 ASSERT3P(callback_list, !=, NULL);
5621 if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5623 * Only call arc_access on anonymous buffers. This is because
5624 * if we've issued an I/O for an evicted buffer, we've already
5625 * called arc_access (to prevent any simultaneous readers from
5626 * getting confused).
5628 arc_access(hdr, hash_lock);
5632 * If a read request has a callback (i.e. acb_done is not NULL), then we
5633 * make a buf containing the data according to the parameters which were
5634 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5635 * aren't needlessly decompressing the data multiple times.
5637 int callback_cnt = 0;
5638 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5645 int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5646 acb->acb_compressed, zio->io_error == 0,
5650 * Decompression failed. Set io_error
5651 * so that when we call acb_done (below),
5652 * we will indicate that the read failed.
5653 * Note that in the unusual case where one
5654 * callback is compressed and another
5655 * uncompressed, we will mark all of them
5656 * as failed, even though the uncompressed
5657 * one can't actually fail. In this case,
5658 * the hdr will not be anonymous, because
5659 * if there are multiple callbacks, it's
5660 * because multiple threads found the same
5661 * arc buf in the hash table.
5663 zio->io_error = error;
5668 * If there are multiple callbacks, we must have the hash lock,
5669 * because the only way for multiple threads to find this hdr is
5670 * in the hash table. This ensures that if there are multiple
5671 * callbacks, the hdr is not anonymous. If it were anonymous,
5672 * we couldn't use arc_buf_destroy() in the error case below.
5674 ASSERT(callback_cnt < 2 || hash_lock != NULL);
5676 hdr->b_l1hdr.b_acb = NULL;
5677 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5678 if (callback_cnt == 0) {
5679 ASSERT(HDR_PREFETCH(hdr));
5680 ASSERT0(hdr->b_l1hdr.b_bufcnt);
5681 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5684 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5685 callback_list != NULL);
5688 arc_hdr_verify(hdr, zio->io_bp);
5690 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5691 if (hdr->b_l1hdr.b_state != arc_anon)
5692 arc_change_state(arc_anon, hdr, hash_lock);
5693 if (HDR_IN_HASH_TABLE(hdr))
5694 buf_hash_remove(hdr);
5695 freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5699 * Broadcast before we drop the hash_lock to avoid the possibility
5700 * that the hdr (and hence the cv) might be freed before we get to
5701 * the cv_broadcast().
5703 cv_broadcast(&hdr->b_l1hdr.b_cv);
5705 if (hash_lock != NULL) {
5706 mutex_exit(hash_lock);
5709 * This block was freed while we waited for the read to
5710 * complete. It has been removed from the hash table and
5711 * moved to the anonymous state (so that it won't show up
5714 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5715 freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5718 /* execute each callback and free its structure */
5719 while ((acb = callback_list) != NULL) {
5720 if (acb->acb_done != NULL) {
5721 if (zio->io_error != 0 && acb->acb_buf != NULL) {
5723 * If arc_buf_alloc_impl() fails during
5724 * decompression, the buf will still be
5725 * allocated, and needs to be freed here.
5727 arc_buf_destroy(acb->acb_buf, acb->acb_private);
5728 acb->acb_buf = NULL;
5730 acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5731 acb->acb_buf, acb->acb_private);
5734 if (acb->acb_zio_dummy != NULL) {
5735 acb->acb_zio_dummy->io_error = zio->io_error;
5736 zio_nowait(acb->acb_zio_dummy);
5739 callback_list = acb->acb_next;
5740 kmem_free(acb, sizeof (arc_callback_t));
5744 arc_hdr_destroy(hdr);
5748 * "Read" the block at the specified DVA (in bp) via the
5749 * cache. If the block is found in the cache, invoke the provided
5750 * callback immediately and return. Note that the `zio' parameter
5751 * in the callback will be NULL in this case, since no IO was
5752 * required. If the block is not in the cache pass the read request
5753 * on to the spa with a substitute callback function, so that the
5754 * requested block will be added to the cache.
5756 * If a read request arrives for a block that has a read in-progress,
5757 * either wait for the in-progress read to complete (and return the
5758 * results); or, if this is a read with a "done" func, add a record
5759 * to the read to invoke the "done" func when the read completes,
5760 * and return; or just return.
5762 * arc_read_done() will invoke all the requested "done" functions
5763 * for readers of this block.
5766 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_read_done_func_t *done,
5767 void *private, zio_priority_t priority, int zio_flags,
5768 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5770 arc_buf_hdr_t *hdr = NULL;
5771 kmutex_t *hash_lock = NULL;
5773 uint64_t guid = spa_load_guid(spa);
5774 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5777 ASSERT(!BP_IS_EMBEDDED(bp) ||
5778 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5781 if (!BP_IS_EMBEDDED(bp)) {
5783 * Embedded BP's have no DVA and require no I/O to "read".
5784 * Create an anonymous arc buf to back it.
5786 hdr = buf_hash_find(guid, bp, &hash_lock);
5789 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
5790 arc_buf_t *buf = NULL;
5791 *arc_flags |= ARC_FLAG_CACHED;
5793 if (HDR_IO_IN_PROGRESS(hdr)) {
5794 zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5796 ASSERT3P(head_zio, !=, NULL);
5797 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5798 priority == ZIO_PRIORITY_SYNC_READ) {
5800 * This is a sync read that needs to wait for
5801 * an in-flight async read. Request that the
5802 * zio have its priority upgraded.
5804 zio_change_priority(head_zio, priority);
5805 DTRACE_PROBE1(arc__async__upgrade__sync,
5806 arc_buf_hdr_t *, hdr);
5807 ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5809 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5810 arc_hdr_clear_flags(hdr,
5811 ARC_FLAG_PREDICTIVE_PREFETCH);
5814 if (*arc_flags & ARC_FLAG_WAIT) {
5815 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5816 mutex_exit(hash_lock);
5819 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5822 arc_callback_t *acb = NULL;
5824 acb = kmem_zalloc(sizeof (arc_callback_t),
5826 acb->acb_done = done;
5827 acb->acb_private = private;
5828 acb->acb_compressed = compressed_read;
5830 acb->acb_zio_dummy = zio_null(pio,
5831 spa, NULL, NULL, NULL, zio_flags);
5833 ASSERT3P(acb->acb_done, !=, NULL);
5834 acb->acb_zio_head = head_zio;
5835 acb->acb_next = hdr->b_l1hdr.b_acb;
5836 hdr->b_l1hdr.b_acb = acb;
5837 mutex_exit(hash_lock);
5840 mutex_exit(hash_lock);
5844 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5845 hdr->b_l1hdr.b_state == arc_mfu);
5848 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5850 * This is a demand read which does not have to
5851 * wait for i/o because we did a predictive
5852 * prefetch i/o for it, which has completed.
5855 arc__demand__hit__predictive__prefetch,
5856 arc_buf_hdr_t *, hdr);
5858 arcstat_demand_hit_predictive_prefetch);
5859 arc_hdr_clear_flags(hdr,
5860 ARC_FLAG_PREDICTIVE_PREFETCH);
5863 if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5865 arcstat_demand_hit_prescient_prefetch);
5866 arc_hdr_clear_flags(hdr,
5867 ARC_FLAG_PRESCIENT_PREFETCH);
5870 ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5871 /* Get a buf with the desired data in it. */
5872 rc = arc_buf_alloc_impl(hdr, private,
5873 compressed_read, B_TRUE, &buf);
5875 arc_buf_destroy(buf, private);
5878 ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
5879 rc == 0 || rc != ENOENT);
5880 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
5881 zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5882 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5884 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5885 arc_access(hdr, hash_lock);
5886 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5887 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5888 if (*arc_flags & ARC_FLAG_L2CACHE)
5889 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5890 mutex_exit(hash_lock);
5891 ARCSTAT_BUMP(arcstat_hits);
5892 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5893 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5894 data, metadata, hits);
5897 done(NULL, zb, bp, buf, private);
5899 uint64_t lsize = BP_GET_LSIZE(bp);
5900 uint64_t psize = BP_GET_PSIZE(bp);
5901 arc_callback_t *acb;
5904 boolean_t devw = B_FALSE;
5908 /* this block is not in the cache */
5909 arc_buf_hdr_t *exists = NULL;
5910 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5911 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5912 BP_GET_COMPRESS(bp), type);
5914 if (!BP_IS_EMBEDDED(bp)) {
5915 hdr->b_dva = *BP_IDENTITY(bp);
5916 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5917 exists = buf_hash_insert(hdr, &hash_lock);
5919 if (exists != NULL) {
5920 /* somebody beat us to the hash insert */
5921 mutex_exit(hash_lock);
5922 buf_discard_identity(hdr);
5923 arc_hdr_destroy(hdr);
5924 goto top; /* restart the IO request */
5928 * This block is in the ghost cache. If it was L2-only
5929 * (and thus didn't have an L1 hdr), we realloc the
5930 * header to add an L1 hdr.
5932 if (!HDR_HAS_L1HDR(hdr)) {
5933 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5936 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5937 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5938 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5939 ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5940 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5941 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5944 * This is a delicate dance that we play here.
5945 * This hdr is in the ghost list so we access it
5946 * to move it out of the ghost list before we
5947 * initiate the read. If it's a prefetch then
5948 * it won't have a callback so we'll remove the
5949 * reference that arc_buf_alloc_impl() created. We
5950 * do this after we've called arc_access() to
5951 * avoid hitting an assert in remove_reference().
5953 arc_adapt(arc_hdr_size(hdr), hdr->b_l1hdr.b_state);
5954 arc_access(hdr, hash_lock);
5955 arc_hdr_alloc_pabd(hdr, B_FALSE);
5957 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5958 size = arc_hdr_size(hdr);
5961 * If compression is enabled on the hdr, then will do
5962 * RAW I/O and will store the compressed data in the hdr's
5963 * data block. Otherwise, the hdr's data block will contain
5964 * the uncompressed data.
5966 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5967 zio_flags |= ZIO_FLAG_RAW;
5970 if (*arc_flags & ARC_FLAG_PREFETCH)
5971 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5972 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5973 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5975 if (*arc_flags & ARC_FLAG_L2CACHE)
5976 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5977 if (BP_GET_LEVEL(bp) > 0)
5978 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5979 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5980 arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5981 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5983 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5984 acb->acb_done = done;
5985 acb->acb_private = private;
5986 acb->acb_compressed = compressed_read;
5988 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5989 hdr->b_l1hdr.b_acb = acb;
5990 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5992 if (HDR_HAS_L2HDR(hdr) &&
5993 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5994 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5995 addr = hdr->b_l2hdr.b_daddr;
5997 * Lock out L2ARC device removal.
5999 if (vdev_is_dead(vd) ||
6000 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6005 * We count both async reads and scrub IOs as asynchronous so
6006 * that both can be upgraded in the event of a cache hit while
6007 * the read IO is still in-flight.
6009 if (priority == ZIO_PRIORITY_ASYNC_READ ||
6010 priority == ZIO_PRIORITY_SCRUB)
6011 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6013 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6016 * At this point, we have a level 1 cache miss. Try again in
6017 * L2ARC if possible.
6019 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6021 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
6022 uint64_t, lsize, zbookmark_phys_t *, zb);
6023 ARCSTAT_BUMP(arcstat_misses);
6024 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
6025 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
6026 data, metadata, misses);
6031 racct_add_force(curproc, RACCT_READBPS, size);
6032 racct_add_force(curproc, RACCT_READIOPS, 1);
6033 PROC_UNLOCK(curproc);
6036 curthread->td_ru.ru_inblock++;
6039 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
6041 * Read from the L2ARC if the following are true:
6042 * 1. The L2ARC vdev was previously cached.
6043 * 2. This buffer still has L2ARC metadata.
6044 * 3. This buffer isn't currently writing to the L2ARC.
6045 * 4. The L2ARC entry wasn't evicted, which may
6046 * also have invalidated the vdev.
6047 * 5. This isn't prefetch and l2arc_noprefetch is set.
6049 if (HDR_HAS_L2HDR(hdr) &&
6050 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
6051 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
6052 l2arc_read_callback_t *cb;
6056 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6057 ARCSTAT_BUMP(arcstat_l2_hits);
6058 atomic_inc_32(&hdr->b_l2hdr.b_hits);
6060 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6062 cb->l2rcb_hdr = hdr;
6065 cb->l2rcb_flags = zio_flags;
6067 asize = vdev_psize_to_asize(vd, size);
6068 if (asize != size) {
6069 abd = abd_alloc_for_io(asize,
6070 HDR_ISTYPE_METADATA(hdr));
6071 cb->l2rcb_abd = abd;
6073 abd = hdr->b_l1hdr.b_pabd;
6076 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6077 addr + asize <= vd->vdev_psize -
6078 VDEV_LABEL_END_SIZE);
6081 * l2arc read. The SCL_L2ARC lock will be
6082 * released by l2arc_read_done().
6083 * Issue a null zio if the underlying buffer
6084 * was squashed to zero size by compression.
6086 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
6087 ZIO_COMPRESS_EMPTY);
6088 rzio = zio_read_phys(pio, vd, addr,
6091 l2arc_read_done, cb, priority,
6092 zio_flags | ZIO_FLAG_DONT_CACHE |
6094 ZIO_FLAG_DONT_PROPAGATE |
6095 ZIO_FLAG_DONT_RETRY, B_FALSE);
6096 acb->acb_zio_head = rzio;
6098 if (hash_lock != NULL)
6099 mutex_exit(hash_lock);
6101 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6103 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
6105 if (*arc_flags & ARC_FLAG_NOWAIT) {
6110 ASSERT(*arc_flags & ARC_FLAG_WAIT);
6111 if (zio_wait(rzio) == 0)
6114 /* l2arc read error; goto zio_read() */
6115 if (hash_lock != NULL)
6116 mutex_enter(hash_lock);
6118 DTRACE_PROBE1(l2arc__miss,
6119 arc_buf_hdr_t *, hdr);
6120 ARCSTAT_BUMP(arcstat_l2_misses);
6121 if (HDR_L2_WRITING(hdr))
6122 ARCSTAT_BUMP(arcstat_l2_rw_clash);
6123 spa_config_exit(spa, SCL_L2ARC, vd);
6127 spa_config_exit(spa, SCL_L2ARC, vd);
6128 if (l2arc_ndev != 0) {
6129 DTRACE_PROBE1(l2arc__miss,
6130 arc_buf_hdr_t *, hdr);
6131 ARCSTAT_BUMP(arcstat_l2_misses);
6135 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
6136 arc_read_done, hdr, priority, zio_flags, zb);
6137 acb->acb_zio_head = rzio;
6139 if (hash_lock != NULL)
6140 mutex_exit(hash_lock);
6142 if (*arc_flags & ARC_FLAG_WAIT)
6143 return (zio_wait(rzio));
6145 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6152 arc_add_prune_callback(arc_prune_func_t *func, void *private)
6156 p = kmem_alloc(sizeof (*p), KM_SLEEP);
6158 p->p_private = private;
6159 list_link_init(&p->p_node);
6160 zfs_refcount_create(&p->p_refcnt);
6162 mutex_enter(&arc_prune_mtx);
6163 zfs_refcount_add(&p->p_refcnt, &arc_prune_list);
6164 list_insert_head(&arc_prune_list, p);
6165 mutex_exit(&arc_prune_mtx);
6171 arc_remove_prune_callback(arc_prune_t *p)
6173 boolean_t wait = B_FALSE;
6174 mutex_enter(&arc_prune_mtx);
6175 list_remove(&arc_prune_list, p);
6176 if (zfs_refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
6178 mutex_exit(&arc_prune_mtx);
6180 /* wait for arc_prune_task to finish */
6182 taskq_wait(arc_prune_taskq);
6183 ASSERT0(zfs_refcount_count(&p->p_refcnt));
6184 zfs_refcount_destroy(&p->p_refcnt);
6185 kmem_free(p, sizeof (*p));
6189 * Notify the arc that a block was freed, and thus will never be used again.
6192 arc_freed(spa_t *spa, const blkptr_t *bp)
6195 kmutex_t *hash_lock;
6196 uint64_t guid = spa_load_guid(spa);
6198 ASSERT(!BP_IS_EMBEDDED(bp));
6200 hdr = buf_hash_find(guid, bp, &hash_lock);
6205 * We might be trying to free a block that is still doing I/O
6206 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6207 * dmu_sync-ed block). If this block is being prefetched, then it
6208 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6209 * until the I/O completes. A block may also have a reference if it is
6210 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6211 * have written the new block to its final resting place on disk but
6212 * without the dedup flag set. This would have left the hdr in the MRU
6213 * state and discoverable. When the txg finally syncs it detects that
6214 * the block was overridden in open context and issues an override I/O.
6215 * Since this is a dedup block, the override I/O will determine if the
6216 * block is already in the DDT. If so, then it will replace the io_bp
6217 * with the bp from the DDT and allow the I/O to finish. When the I/O
6218 * reaches the done callback, dbuf_write_override_done, it will
6219 * check to see if the io_bp and io_bp_override are identical.
6220 * If they are not, then it indicates that the bp was replaced with
6221 * the bp in the DDT and the override bp is freed. This allows
6222 * us to arrive here with a reference on a block that is being
6223 * freed. So if we have an I/O in progress, or a reference to
6224 * this hdr, then we don't destroy the hdr.
6226 if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6227 zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6228 arc_change_state(arc_anon, hdr, hash_lock);
6229 arc_hdr_destroy(hdr);
6230 mutex_exit(hash_lock);
6232 mutex_exit(hash_lock);
6238 * Release this buffer from the cache, making it an anonymous buffer. This
6239 * must be done after a read and prior to modifying the buffer contents.
6240 * If the buffer has more than one reference, we must make
6241 * a new hdr for the buffer.
6244 arc_release(arc_buf_t *buf, void *tag)
6246 arc_buf_hdr_t *hdr = buf->b_hdr;
6249 * It would be nice to assert that if it's DMU metadata (level >
6250 * 0 || it's the dnode file), then it must be syncing context.
6251 * But we don't know that information at this level.
6254 mutex_enter(&buf->b_evict_lock);
6256 ASSERT(HDR_HAS_L1HDR(hdr));
6259 * We don't grab the hash lock prior to this check, because if
6260 * the buffer's header is in the arc_anon state, it won't be
6261 * linked into the hash table.
6263 if (hdr->b_l1hdr.b_state == arc_anon) {
6264 mutex_exit(&buf->b_evict_lock);
6265 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6266 ASSERT(!HDR_IN_HASH_TABLE(hdr));
6267 ASSERT(!HDR_HAS_L2HDR(hdr));
6268 ASSERT(HDR_EMPTY(hdr));
6269 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6270 ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6271 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6273 hdr->b_l1hdr.b_arc_access = 0;
6276 * If the buf is being overridden then it may already
6277 * have a hdr that is not empty.
6279 buf_discard_identity(hdr);
6285 kmutex_t *hash_lock = HDR_LOCK(hdr);
6286 mutex_enter(hash_lock);
6289 * This assignment is only valid as long as the hash_lock is
6290 * held, we must be careful not to reference state or the
6291 * b_state field after dropping the lock.
6293 arc_state_t *state = hdr->b_l1hdr.b_state;
6294 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6295 ASSERT3P(state, !=, arc_anon);
6297 /* this buffer is not on any list */
6298 ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6300 if (HDR_HAS_L2HDR(hdr)) {
6301 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6304 * We have to recheck this conditional again now that
6305 * we're holding the l2ad_mtx to prevent a race with
6306 * another thread which might be concurrently calling
6307 * l2arc_evict(). In that case, l2arc_evict() might have
6308 * destroyed the header's L2 portion as we were waiting
6309 * to acquire the l2ad_mtx.
6311 if (HDR_HAS_L2HDR(hdr)) {
6313 arc_hdr_l2hdr_destroy(hdr);
6316 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6320 * Do we have more than one buf?
6322 if (hdr->b_l1hdr.b_bufcnt > 1) {
6323 arc_buf_hdr_t *nhdr;
6324 uint64_t spa = hdr->b_spa;
6325 uint64_t psize = HDR_GET_PSIZE(hdr);
6326 uint64_t lsize = HDR_GET_LSIZE(hdr);
6327 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
6328 arc_buf_contents_t type = arc_buf_type(hdr);
6329 VERIFY3U(hdr->b_type, ==, type);
6331 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6332 (void) remove_reference(hdr, hash_lock, tag);
6334 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6335 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6336 ASSERT(ARC_BUF_LAST(buf));
6340 * Pull the data off of this hdr and attach it to
6341 * a new anonymous hdr. Also find the last buffer
6342 * in the hdr's buffer list.
6344 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6345 ASSERT3P(lastbuf, !=, NULL);
6348 * If the current arc_buf_t and the hdr are sharing their data
6349 * buffer, then we must stop sharing that block.
6351 if (arc_buf_is_shared(buf)) {
6352 VERIFY(!arc_buf_is_shared(lastbuf));
6355 * First, sever the block sharing relationship between
6356 * buf and the arc_buf_hdr_t.
6358 arc_unshare_buf(hdr, buf);
6361 * Now we need to recreate the hdr's b_pabd. Since we
6362 * have lastbuf handy, we try to share with it, but if
6363 * we can't then we allocate a new b_pabd and copy the
6364 * data from buf into it.
6366 if (arc_can_share(hdr, lastbuf)) {
6367 arc_share_buf(hdr, lastbuf);
6369 arc_hdr_alloc_pabd(hdr, B_TRUE);
6370 abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6371 buf->b_data, psize);
6373 VERIFY3P(lastbuf->b_data, !=, NULL);
6374 } else if (HDR_SHARED_DATA(hdr)) {
6376 * Uncompressed shared buffers are always at the end
6377 * of the list. Compressed buffers don't have the
6378 * same requirements. This makes it hard to
6379 * simply assert that the lastbuf is shared so
6380 * we rely on the hdr's compression flags to determine
6381 * if we have a compressed, shared buffer.
6383 ASSERT(arc_buf_is_shared(lastbuf) ||
6384 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
6385 ASSERT(!ARC_BUF_SHARED(buf));
6387 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6388 ASSERT3P(state, !=, arc_l2c_only);
6390 (void) zfs_refcount_remove_many(&state->arcs_size,
6391 arc_buf_size(buf), buf);
6393 if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6394 ASSERT3P(state, !=, arc_l2c_only);
6395 (void) zfs_refcount_remove_many(
6396 &state->arcs_esize[type],
6397 arc_buf_size(buf), buf);
6400 hdr->b_l1hdr.b_bufcnt -= 1;
6401 arc_cksum_verify(buf);
6403 arc_buf_unwatch(buf);
6406 mutex_exit(hash_lock);
6409 * Allocate a new hdr. The new hdr will contain a b_pabd
6410 * buffer which will be freed in arc_write().
6412 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
6413 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6414 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6415 ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6416 VERIFY3U(nhdr->b_type, ==, type);
6417 ASSERT(!HDR_SHARED_DATA(nhdr));
6419 nhdr->b_l1hdr.b_buf = buf;
6420 nhdr->b_l1hdr.b_bufcnt = 1;
6421 (void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6424 mutex_exit(&buf->b_evict_lock);
6425 (void) zfs_refcount_add_many(&arc_anon->arcs_size,
6426 arc_buf_size(buf), buf);
6428 mutex_exit(&buf->b_evict_lock);
6429 ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6430 /* protected by hash lock, or hdr is on arc_anon */
6431 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6432 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6433 arc_change_state(arc_anon, hdr, hash_lock);
6434 hdr->b_l1hdr.b_arc_access = 0;
6435 mutex_exit(hash_lock);
6437 buf_discard_identity(hdr);
6443 arc_released(arc_buf_t *buf)
6447 mutex_enter(&buf->b_evict_lock);
6448 released = (buf->b_data != NULL &&
6449 buf->b_hdr->b_l1hdr.b_state == arc_anon);
6450 mutex_exit(&buf->b_evict_lock);
6456 arc_referenced(arc_buf_t *buf)
6460 mutex_enter(&buf->b_evict_lock);
6461 referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6462 mutex_exit(&buf->b_evict_lock);
6463 return (referenced);
6468 arc_write_ready(zio_t *zio)
6470 arc_write_callback_t *callback = zio->io_private;
6471 arc_buf_t *buf = callback->awcb_buf;
6472 arc_buf_hdr_t *hdr = buf->b_hdr;
6473 uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
6475 ASSERT(HDR_HAS_L1HDR(hdr));
6476 ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6477 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6480 * If we're reexecuting this zio because the pool suspended, then
6481 * cleanup any state that was previously set the first time the
6482 * callback was invoked.
6484 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6485 arc_cksum_free(hdr);
6487 arc_buf_unwatch(buf);
6489 if (hdr->b_l1hdr.b_pabd != NULL) {
6490 if (arc_buf_is_shared(buf)) {
6491 arc_unshare_buf(hdr, buf);
6493 arc_hdr_free_pabd(hdr);
6497 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6498 ASSERT(!HDR_SHARED_DATA(hdr));
6499 ASSERT(!arc_buf_is_shared(buf));
6501 callback->awcb_ready(zio, buf, callback->awcb_private);
6503 if (HDR_IO_IN_PROGRESS(hdr))
6504 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6506 arc_cksum_compute(buf);
6507 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6509 enum zio_compress compress;
6510 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6511 compress = ZIO_COMPRESS_OFF;
6513 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
6514 compress = BP_GET_COMPRESS(zio->io_bp);
6516 HDR_SET_PSIZE(hdr, psize);
6517 arc_hdr_set_compress(hdr, compress);
6521 * Fill the hdr with data. If the hdr is compressed, the data we want
6522 * is available from the zio, otherwise we can take it from the buf.
6524 * We might be able to share the buf's data with the hdr here. However,
6525 * doing so would cause the ARC to be full of linear ABDs if we write a
6526 * lot of shareable data. As a compromise, we check whether scattered
6527 * ABDs are allowed, and assume that if they are then the user wants
6528 * the ARC to be primarily filled with them regardless of the data being
6529 * written. Therefore, if they're allowed then we allocate one and copy
6530 * the data into it; otherwise, we share the data directly if we can.
6532 if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6533 arc_hdr_alloc_pabd(hdr, B_TRUE);
6536 * Ideally, we would always copy the io_abd into b_pabd, but the
6537 * user may have disabled compressed ARC, thus we must check the
6538 * hdr's compression setting rather than the io_bp's.
6540 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
6541 ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
6543 ASSERT3U(psize, >, 0);
6545 abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6547 ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6549 abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6553 ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6554 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6555 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6557 arc_share_buf(hdr, buf);
6560 arc_hdr_verify(hdr, zio->io_bp);
6564 arc_write_children_ready(zio_t *zio)
6566 arc_write_callback_t *callback = zio->io_private;
6567 arc_buf_t *buf = callback->awcb_buf;
6569 callback->awcb_children_ready(zio, buf, callback->awcb_private);
6573 * The SPA calls this callback for each physical write that happens on behalf
6574 * of a logical write. See the comment in dbuf_write_physdone() for details.
6577 arc_write_physdone(zio_t *zio)
6579 arc_write_callback_t *cb = zio->io_private;
6580 if (cb->awcb_physdone != NULL)
6581 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6585 arc_write_done(zio_t *zio)
6587 arc_write_callback_t *callback = zio->io_private;
6588 arc_buf_t *buf = callback->awcb_buf;
6589 arc_buf_hdr_t *hdr = buf->b_hdr;
6591 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6593 if (zio->io_error == 0) {
6594 arc_hdr_verify(hdr, zio->io_bp);
6596 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6597 buf_discard_identity(hdr);
6599 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6600 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6603 ASSERT(HDR_EMPTY(hdr));
6607 * If the block to be written was all-zero or compressed enough to be
6608 * embedded in the BP, no write was performed so there will be no
6609 * dva/birth/checksum. The buffer must therefore remain anonymous
6612 if (!HDR_EMPTY(hdr)) {
6613 arc_buf_hdr_t *exists;
6614 kmutex_t *hash_lock;
6616 ASSERT3U(zio->io_error, ==, 0);
6618 arc_cksum_verify(buf);
6620 exists = buf_hash_insert(hdr, &hash_lock);
6621 if (exists != NULL) {
6623 * This can only happen if we overwrite for
6624 * sync-to-convergence, because we remove
6625 * buffers from the hash table when we arc_free().
6627 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6628 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6629 panic("bad overwrite, hdr=%p exists=%p",
6630 (void *)hdr, (void *)exists);
6631 ASSERT(zfs_refcount_is_zero(
6632 &exists->b_l1hdr.b_refcnt));
6633 arc_change_state(arc_anon, exists, hash_lock);
6634 mutex_exit(hash_lock);
6635 arc_hdr_destroy(exists);
6636 exists = buf_hash_insert(hdr, &hash_lock);
6637 ASSERT3P(exists, ==, NULL);
6638 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6640 ASSERT(zio->io_prop.zp_nopwrite);
6641 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6642 panic("bad nopwrite, hdr=%p exists=%p",
6643 (void *)hdr, (void *)exists);
6646 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6647 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6648 ASSERT(BP_GET_DEDUP(zio->io_bp));
6649 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6652 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6653 /* if it's not anon, we are doing a scrub */
6654 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6655 arc_access(hdr, hash_lock);
6656 mutex_exit(hash_lock);
6658 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6661 ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6662 callback->awcb_done(zio, buf, callback->awcb_private);
6664 abd_put(zio->io_abd);
6665 kmem_free(callback, sizeof (arc_write_callback_t));
6669 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6670 boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6671 arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6672 arc_write_done_func_t *done, void *private, zio_priority_t priority,
6673 int zio_flags, const zbookmark_phys_t *zb)
6675 arc_buf_hdr_t *hdr = buf->b_hdr;
6676 arc_write_callback_t *callback;
6678 zio_prop_t localprop = *zp;
6680 ASSERT3P(ready, !=, NULL);
6681 ASSERT3P(done, !=, NULL);
6682 ASSERT(!HDR_IO_ERROR(hdr));
6683 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6684 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6685 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6687 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6688 if (ARC_BUF_COMPRESSED(buf)) {
6690 * We're writing a pre-compressed buffer. Make the
6691 * compression algorithm requested by the zio_prop_t match
6692 * the pre-compressed buffer's compression algorithm.
6694 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6696 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6697 zio_flags |= ZIO_FLAG_RAW;
6699 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6700 callback->awcb_ready = ready;
6701 callback->awcb_children_ready = children_ready;
6702 callback->awcb_physdone = physdone;
6703 callback->awcb_done = done;
6704 callback->awcb_private = private;
6705 callback->awcb_buf = buf;
6708 * The hdr's b_pabd is now stale, free it now. A new data block
6709 * will be allocated when the zio pipeline calls arc_write_ready().
6711 if (hdr->b_l1hdr.b_pabd != NULL) {
6713 * If the buf is currently sharing the data block with
6714 * the hdr then we need to break that relationship here.
6715 * The hdr will remain with a NULL data pointer and the
6716 * buf will take sole ownership of the block.
6718 if (arc_buf_is_shared(buf)) {
6719 arc_unshare_buf(hdr, buf);
6721 arc_hdr_free_pabd(hdr);
6723 VERIFY3P(buf->b_data, !=, NULL);
6724 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6726 ASSERT(!arc_buf_is_shared(buf));
6727 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6729 zio = zio_write(pio, spa, txg, bp,
6730 abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6731 HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6732 (children_ready != NULL) ? arc_write_children_ready : NULL,
6733 arc_write_physdone, arc_write_done, callback,
6734 priority, zio_flags, zb);
6740 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
6743 uint64_t available_memory = ptob(freemem);
6745 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
6746 available_memory = MIN(available_memory, uma_avail());
6749 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
6752 if (txg > spa->spa_lowmem_last_txg) {
6753 spa->spa_lowmem_last_txg = txg;
6754 spa->spa_lowmem_page_load = 0;
6757 * If we are in pageout, we know that memory is already tight,
6758 * the arc is already going to be evicting, so we just want to
6759 * continue to let page writes occur as quickly as possible.
6761 if (curproc == pageproc) {
6762 if (spa->spa_lowmem_page_load >
6763 MAX(ptob(minfree), available_memory) / 4)
6764 return (SET_ERROR(ERESTART));
6765 /* Note: reserve is inflated, so we deflate */
6766 atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
6768 } else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
6769 /* memory is low, delay before restarting */
6770 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6771 return (SET_ERROR(EAGAIN));
6773 spa->spa_lowmem_page_load = 0;
6774 #endif /* _KERNEL */
6779 arc_tempreserve_clear(uint64_t reserve)
6781 atomic_add_64(&arc_tempreserve, -reserve);
6782 ASSERT((int64_t)arc_tempreserve >= 0);
6786 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
6791 if (reserve > arc_c/4 && !arc_no_grow) {
6792 arc_c = MIN(arc_c_max, reserve * 4);
6793 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
6795 if (reserve > arc_c)
6796 return (SET_ERROR(ENOMEM));
6799 * Don't count loaned bufs as in flight dirty data to prevent long
6800 * network delays from blocking transactions that are ready to be
6801 * assigned to a txg.
6804 /* assert that it has not wrapped around */
6805 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6807 anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
6808 arc_loaned_bytes), 0);
6811 * Writes will, almost always, require additional memory allocations
6812 * in order to compress/encrypt/etc the data. We therefore need to
6813 * make sure that there is sufficient available memory for this.
6815 error = arc_memory_throttle(spa, reserve, txg);
6820 * Throttle writes when the amount of dirty data in the cache
6821 * gets too large. We try to keep the cache less than half full
6822 * of dirty blocks so that our sync times don't grow too large.
6824 * In the case of one pool being built on another pool, we want
6825 * to make sure we don't end up throttling the lower (backing)
6826 * pool when the upper pool is the majority contributor to dirty
6827 * data. To insure we make forward progress during throttling, we
6828 * also check the current pool's net dirty data and only throttle
6829 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6830 * data in the cache.
6832 * Note: if two requests come in concurrently, we might let them
6833 * both succeed, when one of them should fail. Not a huge deal.
6835 uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6836 uint64_t spa_dirty_anon = spa_dirty_data(spa);
6838 if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
6839 anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
6840 spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
6841 uint64_t meta_esize =
6843 &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6844 uint64_t data_esize =
6845 zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6846 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6847 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6848 arc_tempreserve >> 10, meta_esize >> 10,
6849 data_esize >> 10, reserve >> 10, arc_c >> 10);
6850 return (SET_ERROR(ERESTART));
6852 atomic_add_64(&arc_tempreserve, reserve);
6857 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6858 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6860 size->value.ui64 = zfs_refcount_count(&state->arcs_size);
6861 evict_data->value.ui64 =
6862 zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6863 evict_metadata->value.ui64 =
6864 zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6868 arc_kstat_update(kstat_t *ksp, int rw)
6870 arc_stats_t *as = ksp->ks_data;
6872 if (rw == KSTAT_WRITE) {
6875 arc_kstat_update_state(arc_anon,
6876 &as->arcstat_anon_size,
6877 &as->arcstat_anon_evictable_data,
6878 &as->arcstat_anon_evictable_metadata);
6879 arc_kstat_update_state(arc_mru,
6880 &as->arcstat_mru_size,
6881 &as->arcstat_mru_evictable_data,
6882 &as->arcstat_mru_evictable_metadata);
6883 arc_kstat_update_state(arc_mru_ghost,
6884 &as->arcstat_mru_ghost_size,
6885 &as->arcstat_mru_ghost_evictable_data,
6886 &as->arcstat_mru_ghost_evictable_metadata);
6887 arc_kstat_update_state(arc_mfu,
6888 &as->arcstat_mfu_size,
6889 &as->arcstat_mfu_evictable_data,
6890 &as->arcstat_mfu_evictable_metadata);
6891 arc_kstat_update_state(arc_mfu_ghost,
6892 &as->arcstat_mfu_ghost_size,
6893 &as->arcstat_mfu_ghost_evictable_data,
6894 &as->arcstat_mfu_ghost_evictable_metadata);
6896 ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6897 ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6898 ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6899 ARCSTAT(arcstat_metadata_size) =
6900 aggsum_value(&astat_metadata_size);
6901 ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6902 ARCSTAT(arcstat_bonus_size) = aggsum_value(&astat_bonus_size);
6903 ARCSTAT(arcstat_dnode_size) = aggsum_value(&astat_dnode_size);
6904 ARCSTAT(arcstat_dbuf_size) = aggsum_value(&astat_dbuf_size);
6905 #if defined(__FreeBSD__) && defined(COMPAT_FREEBSD11)
6906 ARCSTAT(arcstat_other_size) = aggsum_value(&astat_bonus_size) +
6907 aggsum_value(&astat_dnode_size) +
6908 aggsum_value(&astat_dbuf_size);
6910 ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6917 * This function *must* return indices evenly distributed between all
6918 * sublists of the multilist. This is needed due to how the ARC eviction
6919 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6920 * distributed between all sublists and uses this assumption when
6921 * deciding which sublist to evict from and how much to evict from it.
6924 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6926 arc_buf_hdr_t *hdr = obj;
6929 * We rely on b_dva to generate evenly distributed index
6930 * numbers using buf_hash below. So, as an added precaution,
6931 * let's make sure we never add empty buffers to the arc lists.
6933 ASSERT(!HDR_EMPTY(hdr));
6936 * The assumption here, is the hash value for a given
6937 * arc_buf_hdr_t will remain constant throughout it's lifetime
6938 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6939 * Thus, we don't need to store the header's sublist index
6940 * on insertion, as this index can be recalculated on removal.
6942 * Also, the low order bits of the hash value are thought to be
6943 * distributed evenly. Otherwise, in the case that the multilist
6944 * has a power of two number of sublists, each sublists' usage
6945 * would not be evenly distributed.
6947 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6948 multilist_get_num_sublists(ml));
6952 static eventhandler_tag arc_event_lowmem = NULL;
6955 arc_lowmem(void *arg __unused, int howto __unused)
6957 int64_t free_memory, to_free;
6959 arc_no_grow = B_TRUE;
6961 arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
6962 free_memory = arc_available_memory();
6963 to_free = (arc_c >> arc_shrink_shift) - MIN(free_memory, 0);
6964 DTRACE_PROBE2(arc__needfree, int64_t, free_memory, int64_t, to_free);
6965 arc_reduce_target_size(to_free);
6967 mutex_enter(&arc_adjust_lock);
6968 arc_adjust_needed = B_TRUE;
6969 zthr_wakeup(arc_adjust_zthr);
6972 * It is unsafe to block here in arbitrary threads, because we can come
6973 * here from ARC itself and may hold ARC locks and thus risk a deadlock
6974 * with ARC reclaim thread.
6976 if (curproc == pageproc)
6977 (void) cv_wait(&arc_adjust_waiters_cv, &arc_adjust_lock);
6978 mutex_exit(&arc_adjust_lock);
6983 arc_state_init(void)
6985 arc_anon = &ARC_anon;
6987 arc_mru_ghost = &ARC_mru_ghost;
6989 arc_mfu_ghost = &ARC_mfu_ghost;
6990 arc_l2c_only = &ARC_l2c_only;
6992 arc_mru->arcs_list[ARC_BUFC_METADATA] =
6993 multilist_create(sizeof (arc_buf_hdr_t),
6994 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6995 arc_state_multilist_index_func);
6996 arc_mru->arcs_list[ARC_BUFC_DATA] =
6997 multilist_create(sizeof (arc_buf_hdr_t),
6998 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6999 arc_state_multilist_index_func);
7000 arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
7001 multilist_create(sizeof (arc_buf_hdr_t),
7002 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7003 arc_state_multilist_index_func);
7004 arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
7005 multilist_create(sizeof (arc_buf_hdr_t),
7006 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7007 arc_state_multilist_index_func);
7008 arc_mfu->arcs_list[ARC_BUFC_METADATA] =
7009 multilist_create(sizeof (arc_buf_hdr_t),
7010 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7011 arc_state_multilist_index_func);
7012 arc_mfu->arcs_list[ARC_BUFC_DATA] =
7013 multilist_create(sizeof (arc_buf_hdr_t),
7014 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7015 arc_state_multilist_index_func);
7016 arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
7017 multilist_create(sizeof (arc_buf_hdr_t),
7018 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7019 arc_state_multilist_index_func);
7020 arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
7021 multilist_create(sizeof (arc_buf_hdr_t),
7022 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7023 arc_state_multilist_index_func);
7024 arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
7025 multilist_create(sizeof (arc_buf_hdr_t),
7026 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7027 arc_state_multilist_index_func);
7028 arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
7029 multilist_create(sizeof (arc_buf_hdr_t),
7030 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7031 arc_state_multilist_index_func);
7033 zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7034 zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7035 zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7036 zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7037 zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7038 zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7039 zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7040 zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7041 zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7042 zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7043 zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7044 zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7046 zfs_refcount_create(&arc_anon->arcs_size);
7047 zfs_refcount_create(&arc_mru->arcs_size);
7048 zfs_refcount_create(&arc_mru_ghost->arcs_size);
7049 zfs_refcount_create(&arc_mfu->arcs_size);
7050 zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7051 zfs_refcount_create(&arc_l2c_only->arcs_size);
7053 aggsum_init(&arc_meta_used, 0);
7054 aggsum_init(&arc_size, 0);
7055 aggsum_init(&astat_data_size, 0);
7056 aggsum_init(&astat_metadata_size, 0);
7057 aggsum_init(&astat_hdr_size, 0);
7058 aggsum_init(&astat_bonus_size, 0);
7059 aggsum_init(&astat_dnode_size, 0);
7060 aggsum_init(&astat_dbuf_size, 0);
7061 aggsum_init(&astat_l2_hdr_size, 0);
7065 arc_state_fini(void)
7067 zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7068 zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7069 zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7070 zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7071 zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7072 zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7073 zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7074 zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7075 zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7076 zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7077 zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7078 zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7080 zfs_refcount_destroy(&arc_anon->arcs_size);
7081 zfs_refcount_destroy(&arc_mru->arcs_size);
7082 zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7083 zfs_refcount_destroy(&arc_mfu->arcs_size);
7084 zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7085 zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7087 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
7088 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7089 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7090 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7091 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
7092 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7093 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
7094 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7096 aggsum_fini(&arc_meta_used);
7097 aggsum_fini(&arc_size);
7098 aggsum_fini(&astat_data_size);
7099 aggsum_fini(&astat_metadata_size);
7100 aggsum_fini(&astat_hdr_size);
7101 aggsum_fini(&astat_bonus_size);
7102 aggsum_fini(&astat_dnode_size);
7103 aggsum_fini(&astat_dbuf_size);
7104 aggsum_fini(&astat_l2_hdr_size);
7116 int i, prefetch_tunable_set = 0;
7119 * allmem is "all memory that we could possibly use".
7123 uint64_t allmem = ptob(physmem - swapfs_minfree);
7125 uint64_t allmem = (physmem * PAGESIZE) / 2;
7128 uint64_t allmem = kmem_size();
7130 mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
7131 cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
7133 mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
7134 cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
7136 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
7137 arc_c_min = MAX(allmem / 32, arc_abs_min);
7138 /* set max to 5/8 of all memory, or all but 1GB, whichever is more */
7139 if (allmem >= 1 << 30)
7140 arc_c_max = allmem - (1 << 30);
7142 arc_c_max = arc_c_min;
7143 arc_c_max = MAX(allmem * 5 / 8, arc_c_max);
7146 * In userland, there's only the memory pressure that we artificially
7147 * create (see arc_available_memory()). Don't let arc_c get too
7148 * small, because it can cause transactions to be larger than
7149 * arc_c, causing arc_tempreserve_space() to fail.
7152 arc_c_min = arc_c_max / 2;
7157 * Allow the tunables to override our calculations if they are
7160 if (zfs_arc_max > arc_abs_min && zfs_arc_max < allmem) {
7161 arc_c_max = zfs_arc_max;
7162 arc_c_min = MIN(arc_c_min, arc_c_max);
7164 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
7165 arc_c_min = zfs_arc_min;
7169 arc_p = (arc_c >> 1);
7171 /* limit meta-data to 1/4 of the arc capacity */
7172 arc_meta_limit = arc_c_max / 4;
7176 * Metadata is stored in the kernel's heap. Don't let us
7177 * use more than half the heap for the ARC.
7180 arc_meta_limit = MIN(arc_meta_limit, uma_limit() / 2);
7181 arc_dnode_limit = arc_meta_limit / 10;
7183 arc_meta_limit = MIN(arc_meta_limit,
7184 vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
7188 /* Allow the tunable to override if it is reasonable */
7189 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
7190 arc_meta_limit = zfs_arc_meta_limit;
7192 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
7193 arc_c_min = arc_meta_limit / 2;
7195 if (zfs_arc_meta_min > 0) {
7196 arc_meta_min = zfs_arc_meta_min;
7198 arc_meta_min = arc_c_min / 2;
7201 /* Valid range: <arc_meta_min> - <arc_c_max> */
7202 if ((zfs_arc_dnode_limit) && (zfs_arc_dnode_limit != arc_dnode_limit) &&
7203 (zfs_arc_dnode_limit >= zfs_arc_meta_min) &&
7204 (zfs_arc_dnode_limit <= arc_c_max))
7205 arc_dnode_limit = zfs_arc_dnode_limit;
7207 if (zfs_arc_grow_retry > 0)
7208 arc_grow_retry = zfs_arc_grow_retry;
7210 if (zfs_arc_shrink_shift > 0)
7211 arc_shrink_shift = zfs_arc_shrink_shift;
7213 if (zfs_arc_no_grow_shift > 0)
7214 arc_no_grow_shift = zfs_arc_no_grow_shift;
7216 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
7218 if (arc_no_grow_shift >= arc_shrink_shift)
7219 arc_no_grow_shift = arc_shrink_shift - 1;
7221 if (zfs_arc_p_min_shift > 0)
7222 arc_p_min_shift = zfs_arc_p_min_shift;
7224 /* if kmem_flags are set, lets try to use less memory */
7225 if (kmem_debugging())
7227 if (arc_c < arc_c_min)
7230 zfs_arc_min = arc_c_min;
7231 zfs_arc_max = arc_c_max;
7236 * The arc must be "uninitialized", so that hdr_recl() (which is
7237 * registered by buf_init()) will not access arc_reap_zthr before
7240 ASSERT(!arc_initialized);
7243 list_create(&arc_prune_list, sizeof (arc_prune_t),
7244 offsetof(arc_prune_t, p_node));
7245 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
7247 arc_prune_taskq = taskq_create("arc_prune", max_ncpus, minclsyspri,
7248 max_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
7250 arc_dnlc_evicts_thread_exit = FALSE;
7252 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7253 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7255 if (arc_ksp != NULL) {
7256 arc_ksp->ks_data = &arc_stats;
7257 arc_ksp->ks_update = arc_kstat_update;
7258 kstat_install(arc_ksp);
7261 arc_adjust_zthr = zthr_create_timer(arc_adjust_cb_check,
7262 arc_adjust_cb, NULL, SEC2NSEC(1));
7263 arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
7264 arc_reap_cb, NULL, SEC2NSEC(1));
7267 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
7268 EVENTHANDLER_PRI_FIRST);
7271 (void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
7272 TS_RUN, minclsyspri);
7274 arc_initialized = B_TRUE;
7278 * Calculate maximum amount of dirty data per pool.
7280 * If it has been set by /etc/system, take that.
7281 * Otherwise, use a percentage of physical memory defined by
7282 * zfs_dirty_data_max_percent (default 10%) with a cap at
7283 * zfs_dirty_data_max_max (default 4GB).
7285 if (zfs_dirty_data_max == 0) {
7286 zfs_dirty_data_max = ptob(physmem) *
7287 zfs_dirty_data_max_percent / 100;
7288 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7289 zfs_dirty_data_max_max);
7293 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
7294 prefetch_tunable_set = 1;
7297 if (prefetch_tunable_set == 0) {
7298 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
7300 printf(" add \"vfs.zfs.prefetch_disable=0\" "
7301 "to /boot/loader.conf.\n");
7302 zfs_prefetch_disable = 1;
7305 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
7306 prefetch_tunable_set == 0) {
7307 printf("ZFS NOTICE: Prefetch is disabled by default if less "
7308 "than 4GB of RAM is present;\n"
7309 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
7310 "to /boot/loader.conf.\n");
7311 zfs_prefetch_disable = 1;
7314 /* Warn about ZFS memory and address space requirements. */
7315 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
7316 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
7317 "expect unstable behavior.\n");
7319 if (allmem < 512 * (1 << 20)) {
7320 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
7321 "expect unstable behavior.\n");
7322 printf(" Consider tuning vm.kmem_size and "
7323 "vm.kmem_size_max\n");
7324 printf(" in /boot/loader.conf.\n");
7335 if (arc_event_lowmem != NULL)
7336 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
7339 /* Use B_TRUE to ensure *all* buffers are evicted */
7340 arc_flush(NULL, B_TRUE);
7342 mutex_enter(&arc_dnlc_evicts_lock);
7343 arc_dnlc_evicts_thread_exit = TRUE;
7345 * The user evicts thread will set arc_user_evicts_thread_exit
7346 * to FALSE when it is finished exiting; we're waiting for that.
7348 while (arc_dnlc_evicts_thread_exit) {
7349 cv_signal(&arc_dnlc_evicts_cv);
7350 cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
7352 mutex_exit(&arc_dnlc_evicts_lock);
7354 arc_initialized = B_FALSE;
7356 if (arc_ksp != NULL) {
7357 kstat_delete(arc_ksp);
7361 taskq_wait(arc_prune_taskq);
7362 taskq_destroy(arc_prune_taskq);
7364 mutex_enter(&arc_prune_mtx);
7365 while ((p = list_head(&arc_prune_list)) != NULL) {
7366 list_remove(&arc_prune_list, p);
7367 zfs_refcount_remove(&p->p_refcnt, &arc_prune_list);
7368 zfs_refcount_destroy(&p->p_refcnt);
7369 kmem_free(p, sizeof (*p));
7371 mutex_exit(&arc_prune_mtx);
7373 list_destroy(&arc_prune_list);
7374 mutex_destroy(&arc_prune_mtx);
7376 (void) zthr_cancel(arc_adjust_zthr);
7377 zthr_destroy(arc_adjust_zthr);
7379 mutex_destroy(&arc_dnlc_evicts_lock);
7380 cv_destroy(&arc_dnlc_evicts_cv);
7382 (void) zthr_cancel(arc_reap_zthr);
7383 zthr_destroy(arc_reap_zthr);
7385 mutex_destroy(&arc_adjust_lock);
7386 cv_destroy(&arc_adjust_waiters_cv);
7389 * buf_fini() must proceed arc_state_fini() because buf_fin() may
7390 * trigger the release of kmem magazines, which can callback to
7391 * arc_space_return() which accesses aggsums freed in act_state_fini().
7396 ASSERT0(arc_loaned_bytes);
7402 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7403 * It uses dedicated storage devices to hold cached data, which are populated
7404 * using large infrequent writes. The main role of this cache is to boost
7405 * the performance of random read workloads. The intended L2ARC devices
7406 * include short-stroked disks, solid state disks, and other media with
7407 * substantially faster read latency than disk.
7409 * +-----------------------+
7411 * +-----------------------+
7414 * l2arc_feed_thread() arc_read()
7418 * +---------------+ |
7420 * +---------------+ |
7425 * +-------+ +-------+
7427 * | cache | | cache |
7428 * +-------+ +-------+
7429 * +=========+ .-----.
7430 * : L2ARC : |-_____-|
7431 * : devices : | Disks |
7432 * +=========+ `-_____-'
7434 * Read requests are satisfied from the following sources, in order:
7437 * 2) vdev cache of L2ARC devices
7439 * 4) vdev cache of disks
7442 * Some L2ARC device types exhibit extremely slow write performance.
7443 * To accommodate for this there are some significant differences between
7444 * the L2ARC and traditional cache design:
7446 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
7447 * the ARC behave as usual, freeing buffers and placing headers on ghost
7448 * lists. The ARC does not send buffers to the L2ARC during eviction as
7449 * this would add inflated write latencies for all ARC memory pressure.
7451 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7452 * It does this by periodically scanning buffers from the eviction-end of
7453 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7454 * not already there. It scans until a headroom of buffers is satisfied,
7455 * which itself is a buffer for ARC eviction. If a compressible buffer is
7456 * found during scanning and selected for writing to an L2ARC device, we
7457 * temporarily boost scanning headroom during the next scan cycle to make
7458 * sure we adapt to compression effects (which might significantly reduce
7459 * the data volume we write to L2ARC). The thread that does this is
7460 * l2arc_feed_thread(), illustrated below; example sizes are included to
7461 * provide a better sense of ratio than this diagram:
7464 * +---------------------+----------+
7465 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
7466 * +---------------------+----------+ | o L2ARC eligible
7467 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
7468 * +---------------------+----------+ |
7469 * 15.9 Gbytes ^ 32 Mbytes |
7471 * l2arc_feed_thread()
7473 * l2arc write hand <--[oooo]--'
7477 * +==============================+
7478 * L2ARC dev |####|#|###|###| |####| ... |
7479 * +==============================+
7482 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7483 * evicted, then the L2ARC has cached a buffer much sooner than it probably
7484 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
7485 * safe to say that this is an uncommon case, since buffers at the end of
7486 * the ARC lists have moved there due to inactivity.
7488 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7489 * then the L2ARC simply misses copying some buffers. This serves as a
7490 * pressure valve to prevent heavy read workloads from both stalling the ARC
7491 * with waits and clogging the L2ARC with writes. This also helps prevent
7492 * the potential for the L2ARC to churn if it attempts to cache content too
7493 * quickly, such as during backups of the entire pool.
7495 * 5. After system boot and before the ARC has filled main memory, there are
7496 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7497 * lists can remain mostly static. Instead of searching from tail of these
7498 * lists as pictured, the l2arc_feed_thread() will search from the list heads
7499 * for eligible buffers, greatly increasing its chance of finding them.
7501 * The L2ARC device write speed is also boosted during this time so that
7502 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
7503 * there are no L2ARC reads, and no fear of degrading read performance
7504 * through increased writes.
7506 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7507 * the vdev queue can aggregate them into larger and fewer writes. Each
7508 * device is written to in a rotor fashion, sweeping writes through
7509 * available space then repeating.
7511 * 7. The L2ARC does not store dirty content. It never needs to flush
7512 * write buffers back to disk based storage.
7514 * 8. If an ARC buffer is written (and dirtied) which also exists in the
7515 * L2ARC, the now stale L2ARC buffer is immediately dropped.
7517 * The performance of the L2ARC can be tweaked by a number of tunables, which
7518 * may be necessary for different workloads:
7520 * l2arc_write_max max write bytes per interval
7521 * l2arc_write_boost extra write bytes during device warmup
7522 * l2arc_noprefetch skip caching prefetched buffers
7523 * l2arc_headroom number of max device writes to precache
7524 * l2arc_headroom_boost when we find compressed buffers during ARC
7525 * scanning, we multiply headroom by this
7526 * percentage factor for the next scan cycle,
7527 * since more compressed buffers are likely to
7529 * l2arc_feed_secs seconds between L2ARC writing
7531 * Tunables may be removed or added as future performance improvements are
7532 * integrated, and also may become zpool properties.
7534 * There are three key functions that control how the L2ARC warms up:
7536 * l2arc_write_eligible() check if a buffer is eligible to cache
7537 * l2arc_write_size() calculate how much to write
7538 * l2arc_write_interval() calculate sleep delay between writes
7540 * These three functions determine what to write, how much, and how quickly
7545 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7548 * A buffer is *not* eligible for the L2ARC if it:
7549 * 1. belongs to a different spa.
7550 * 2. is already cached on the L2ARC.
7551 * 3. has an I/O in progress (it may be an incomplete read).
7552 * 4. is flagged not eligible (zfs property).
7554 if (hdr->b_spa != spa_guid) {
7555 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
7558 if (HDR_HAS_L2HDR(hdr)) {
7559 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
7562 if (HDR_IO_IN_PROGRESS(hdr)) {
7563 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
7566 if (!HDR_L2CACHE(hdr)) {
7567 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
7575 l2arc_write_size(void)
7580 * Make sure our globals have meaningful values in case the user
7583 size = l2arc_write_max;
7585 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7586 "be greater than zero, resetting it to the default (%d)",
7588 size = l2arc_write_max = L2ARC_WRITE_SIZE;
7591 if (arc_warm == B_FALSE)
7592 size += l2arc_write_boost;
7599 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7601 clock_t interval, next, now;
7604 * If the ARC lists are busy, increase our write rate; if the
7605 * lists are stale, idle back. This is achieved by checking
7606 * how much we previously wrote - if it was more than half of
7607 * what we wanted, schedule the next write much sooner.
7609 if (l2arc_feed_again && wrote > (wanted / 2))
7610 interval = (hz * l2arc_feed_min_ms) / 1000;
7612 interval = hz * l2arc_feed_secs;
7614 now = ddi_get_lbolt();
7615 next = MAX(now, MIN(now + interval, began + interval));
7621 * Cycle through L2ARC devices. This is how L2ARC load balances.
7622 * If a device is returned, this also returns holding the spa config lock.
7624 static l2arc_dev_t *
7625 l2arc_dev_get_next(void)
7627 l2arc_dev_t *first, *next = NULL;
7630 * Lock out the removal of spas (spa_namespace_lock), then removal
7631 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
7632 * both locks will be dropped and a spa config lock held instead.
7634 mutex_enter(&spa_namespace_lock);
7635 mutex_enter(&l2arc_dev_mtx);
7637 /* if there are no vdevs, there is nothing to do */
7638 if (l2arc_ndev == 0)
7642 next = l2arc_dev_last;
7644 /* loop around the list looking for a non-faulted vdev */
7646 next = list_head(l2arc_dev_list);
7648 next = list_next(l2arc_dev_list, next);
7650 next = list_head(l2arc_dev_list);
7653 /* if we have come back to the start, bail out */
7656 else if (next == first)
7659 } while (vdev_is_dead(next->l2ad_vdev));
7661 /* if we were unable to find any usable vdevs, return NULL */
7662 if (vdev_is_dead(next->l2ad_vdev))
7665 l2arc_dev_last = next;
7668 mutex_exit(&l2arc_dev_mtx);
7671 * Grab the config lock to prevent the 'next' device from being
7672 * removed while we are writing to it.
7675 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7676 mutex_exit(&spa_namespace_lock);
7682 * Free buffers that were tagged for destruction.
7685 l2arc_do_free_on_write()
7688 l2arc_data_free_t *df, *df_prev;
7690 mutex_enter(&l2arc_free_on_write_mtx);
7691 buflist = l2arc_free_on_write;
7693 for (df = list_tail(buflist); df; df = df_prev) {
7694 df_prev = list_prev(buflist, df);
7695 ASSERT3P(df->l2df_abd, !=, NULL);
7696 abd_free(df->l2df_abd);
7697 list_remove(buflist, df);
7698 kmem_free(df, sizeof (l2arc_data_free_t));
7701 mutex_exit(&l2arc_free_on_write_mtx);
7705 * A write to a cache device has completed. Update all headers to allow
7706 * reads from these buffers to begin.
7709 l2arc_write_done(zio_t *zio)
7711 l2arc_write_callback_t *cb;
7714 arc_buf_hdr_t *head, *hdr, *hdr_prev;
7715 kmutex_t *hash_lock;
7716 int64_t bytes_dropped = 0;
7718 cb = zio->io_private;
7719 ASSERT3P(cb, !=, NULL);
7720 dev = cb->l2wcb_dev;
7721 ASSERT3P(dev, !=, NULL);
7722 head = cb->l2wcb_head;
7723 ASSERT3P(head, !=, NULL);
7724 buflist = &dev->l2ad_buflist;
7725 ASSERT3P(buflist, !=, NULL);
7726 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7727 l2arc_write_callback_t *, cb);
7729 if (zio->io_error != 0)
7730 ARCSTAT_BUMP(arcstat_l2_writes_error);
7733 * All writes completed, or an error was hit.
7736 mutex_enter(&dev->l2ad_mtx);
7737 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7738 hdr_prev = list_prev(buflist, hdr);
7740 hash_lock = HDR_LOCK(hdr);
7743 * We cannot use mutex_enter or else we can deadlock
7744 * with l2arc_write_buffers (due to swapping the order
7745 * the hash lock and l2ad_mtx are taken).
7747 if (!mutex_tryenter(hash_lock)) {
7749 * Missed the hash lock. We must retry so we
7750 * don't leave the ARC_FLAG_L2_WRITING bit set.
7752 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7755 * We don't want to rescan the headers we've
7756 * already marked as having been written out, so
7757 * we reinsert the head node so we can pick up
7758 * where we left off.
7760 list_remove(buflist, head);
7761 list_insert_after(buflist, hdr, head);
7763 mutex_exit(&dev->l2ad_mtx);
7766 * We wait for the hash lock to become available
7767 * to try and prevent busy waiting, and increase
7768 * the chance we'll be able to acquire the lock
7769 * the next time around.
7771 mutex_enter(hash_lock);
7772 mutex_exit(hash_lock);
7777 * We could not have been moved into the arc_l2c_only
7778 * state while in-flight due to our ARC_FLAG_L2_WRITING
7779 * bit being set. Let's just ensure that's being enforced.
7781 ASSERT(HDR_HAS_L1HDR(hdr));
7783 if (zio->io_error != 0) {
7785 * Error - drop L2ARC entry.
7787 list_remove(buflist, hdr);
7789 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7791 ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
7792 ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
7794 bytes_dropped += arc_hdr_size(hdr);
7795 (void) zfs_refcount_remove_many(&dev->l2ad_alloc,
7796 arc_hdr_size(hdr), hdr);
7800 * Allow ARC to begin reads and ghost list evictions to
7803 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7805 mutex_exit(hash_lock);
7808 atomic_inc_64(&l2arc_writes_done);
7809 list_remove(buflist, head);
7810 ASSERT(!HDR_HAS_L1HDR(head));
7811 kmem_cache_free(hdr_l2only_cache, head);
7812 mutex_exit(&dev->l2ad_mtx);
7814 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7816 l2arc_do_free_on_write();
7818 kmem_free(cb, sizeof (l2arc_write_callback_t));
7822 * A read to a cache device completed. Validate buffer contents before
7823 * handing over to the regular ARC routines.
7826 l2arc_read_done(zio_t *zio)
7828 l2arc_read_callback_t *cb;
7830 kmutex_t *hash_lock;
7831 boolean_t valid_cksum;
7833 ASSERT3P(zio->io_vd, !=, NULL);
7834 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7836 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7838 cb = zio->io_private;
7839 ASSERT3P(cb, !=, NULL);
7840 hdr = cb->l2rcb_hdr;
7841 ASSERT3P(hdr, !=, NULL);
7843 hash_lock = HDR_LOCK(hdr);
7844 mutex_enter(hash_lock);
7845 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7848 * If the data was read into a temporary buffer,
7849 * move it and free the buffer.
7851 if (cb->l2rcb_abd != NULL) {
7852 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7853 if (zio->io_error == 0) {
7854 abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
7859 * The following must be done regardless of whether
7860 * there was an error:
7861 * - free the temporary buffer
7862 * - point zio to the real ARC buffer
7863 * - set zio size accordingly
7864 * These are required because zio is either re-used for
7865 * an I/O of the block in the case of the error
7866 * or the zio is passed to arc_read_done() and it
7869 abd_free(cb->l2rcb_abd);
7870 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7871 zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
7874 ASSERT3P(zio->io_abd, !=, NULL);
7877 * Check this survived the L2ARC journey.
7879 ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
7880 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
7881 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
7883 valid_cksum = arc_cksum_is_equal(hdr, zio);
7884 if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7885 mutex_exit(hash_lock);
7886 zio->io_private = hdr;
7889 mutex_exit(hash_lock);
7891 * Buffer didn't survive caching. Increment stats and
7892 * reissue to the original storage device.
7894 if (zio->io_error != 0) {
7895 ARCSTAT_BUMP(arcstat_l2_io_error);
7897 zio->io_error = SET_ERROR(EIO);
7900 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7903 * If there's no waiter, issue an async i/o to the primary
7904 * storage now. If there *is* a waiter, the caller must
7905 * issue the i/o in a context where it's OK to block.
7907 if (zio->io_waiter == NULL) {
7908 zio_t *pio = zio_unique_parent(zio);
7910 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7912 zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7913 hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
7914 hdr, zio->io_priority, cb->l2rcb_flags,
7919 kmem_free(cb, sizeof (l2arc_read_callback_t));
7923 * This is the list priority from which the L2ARC will search for pages to
7924 * cache. This is used within loops (0..3) to cycle through lists in the
7925 * desired order. This order can have a significant effect on cache
7928 * Currently the metadata lists are hit first, MFU then MRU, followed by
7929 * the data lists. This function returns a locked list, and also returns
7932 static multilist_sublist_t *
7933 l2arc_sublist_lock(int list_num)
7935 multilist_t *ml = NULL;
7938 ASSERT(list_num >= 0 && list_num <= 3);
7942 ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
7945 ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
7948 ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
7951 ml = arc_mru->arcs_list[ARC_BUFC_DATA];
7956 * Return a randomly-selected sublist. This is acceptable
7957 * because the caller feeds only a little bit of data for each
7958 * call (8MB). Subsequent calls will result in different
7959 * sublists being selected.
7961 idx = multilist_get_random_index(ml);
7962 return (multilist_sublist_lock(ml, idx));
7966 * Evict buffers from the device write hand to the distance specified in
7967 * bytes. This distance may span populated buffers, it may span nothing.
7968 * This is clearing a region on the L2ARC device ready for writing.
7969 * If the 'all' boolean is set, every buffer is evicted.
7972 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7975 arc_buf_hdr_t *hdr, *hdr_prev;
7976 kmutex_t *hash_lock;
7979 buflist = &dev->l2ad_buflist;
7981 if (!all && dev->l2ad_first) {
7983 * This is the first sweep through the device. There is
7989 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7991 * When nearing the end of the device, evict to the end
7992 * before the device write hand jumps to the start.
7994 taddr = dev->l2ad_end;
7996 taddr = dev->l2ad_hand + distance;
7998 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7999 uint64_t, taddr, boolean_t, all);
8002 mutex_enter(&dev->l2ad_mtx);
8003 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
8004 hdr_prev = list_prev(buflist, hdr);
8006 hash_lock = HDR_LOCK(hdr);
8009 * We cannot use mutex_enter or else we can deadlock
8010 * with l2arc_write_buffers (due to swapping the order
8011 * the hash lock and l2ad_mtx are taken).
8013 if (!mutex_tryenter(hash_lock)) {
8015 * Missed the hash lock. Retry.
8017 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
8018 mutex_exit(&dev->l2ad_mtx);
8019 mutex_enter(hash_lock);
8020 mutex_exit(hash_lock);
8025 * A header can't be on this list if it doesn't have L2 header.
8027 ASSERT(HDR_HAS_L2HDR(hdr));
8029 /* Ensure this header has finished being written. */
8030 ASSERT(!HDR_L2_WRITING(hdr));
8031 ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8033 if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
8034 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
8036 * We've evicted to the target address,
8037 * or the end of the device.
8039 mutex_exit(hash_lock);
8043 if (!HDR_HAS_L1HDR(hdr)) {
8044 ASSERT(!HDR_L2_READING(hdr));
8046 * This doesn't exist in the ARC. Destroy.
8047 * arc_hdr_destroy() will call list_remove()
8048 * and decrement arcstat_l2_lsize.
8050 arc_change_state(arc_anon, hdr, hash_lock);
8051 arc_hdr_destroy(hdr);
8053 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
8054 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
8056 * Invalidate issued or about to be issued
8057 * reads, since we may be about to write
8058 * over this location.
8060 if (HDR_L2_READING(hdr)) {
8061 ARCSTAT_BUMP(arcstat_l2_evict_reading);
8062 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
8065 arc_hdr_l2hdr_destroy(hdr);
8067 mutex_exit(hash_lock);
8069 mutex_exit(&dev->l2ad_mtx);
8073 * Find and write ARC buffers to the L2ARC device.
8075 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
8076 * for reading until they have completed writing.
8077 * The headroom_boost is an in-out parameter used to maintain headroom boost
8078 * state between calls to this function.
8080 * Returns the number of bytes actually written (which may be smaller than
8081 * the delta by which the device hand has changed due to alignment).
8084 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
8086 arc_buf_hdr_t *hdr, *hdr_prev, *head;
8087 uint64_t write_asize, write_psize, write_lsize, headroom;
8089 l2arc_write_callback_t *cb;
8091 uint64_t guid = spa_load_guid(spa);
8094 ASSERT3P(dev->l2ad_vdev, !=, NULL);
8097 write_lsize = write_asize = write_psize = 0;
8099 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
8100 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
8102 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
8104 * Copy buffers for L2ARC writing.
8106 for (try = 0; try <= 3; try++) {
8107 multilist_sublist_t *mls = l2arc_sublist_lock(try);
8108 uint64_t passed_sz = 0;
8110 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
8113 * L2ARC fast warmup.
8115 * Until the ARC is warm and starts to evict, read from the
8116 * head of the ARC lists rather than the tail.
8118 if (arc_warm == B_FALSE)
8119 hdr = multilist_sublist_head(mls);
8121 hdr = multilist_sublist_tail(mls);
8123 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
8125 headroom = target_sz * l2arc_headroom;
8126 if (zfs_compressed_arc_enabled)
8127 headroom = (headroom * l2arc_headroom_boost) / 100;
8129 for (; hdr; hdr = hdr_prev) {
8130 kmutex_t *hash_lock;
8132 if (arc_warm == B_FALSE)
8133 hdr_prev = multilist_sublist_next(mls, hdr);
8135 hdr_prev = multilist_sublist_prev(mls, hdr);
8136 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
8137 HDR_GET_LSIZE(hdr));
8139 hash_lock = HDR_LOCK(hdr);
8140 if (!mutex_tryenter(hash_lock)) {
8141 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
8143 * Skip this buffer rather than waiting.
8148 passed_sz += HDR_GET_LSIZE(hdr);
8149 if (passed_sz > headroom) {
8153 mutex_exit(hash_lock);
8154 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
8158 if (!l2arc_write_eligible(guid, hdr)) {
8159 mutex_exit(hash_lock);
8164 * We rely on the L1 portion of the header below, so
8165 * it's invalid for this header to have been evicted out
8166 * of the ghost cache, prior to being written out. The
8167 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8169 ASSERT(HDR_HAS_L1HDR(hdr));
8171 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8172 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8173 ASSERT3U(arc_hdr_size(hdr), >, 0);
8174 uint64_t psize = arc_hdr_size(hdr);
8175 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
8178 if ((write_asize + asize) > target_sz) {
8180 mutex_exit(hash_lock);
8181 ARCSTAT_BUMP(arcstat_l2_write_full);
8187 * Insert a dummy header on the buflist so
8188 * l2arc_write_done() can find where the
8189 * write buffers begin without searching.
8191 mutex_enter(&dev->l2ad_mtx);
8192 list_insert_head(&dev->l2ad_buflist, head);
8193 mutex_exit(&dev->l2ad_mtx);
8196 sizeof (l2arc_write_callback_t), KM_SLEEP);
8197 cb->l2wcb_dev = dev;
8198 cb->l2wcb_head = head;
8199 pio = zio_root(spa, l2arc_write_done, cb,
8201 ARCSTAT_BUMP(arcstat_l2_write_pios);
8204 hdr->b_l2hdr.b_dev = dev;
8205 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
8206 arc_hdr_set_flags(hdr,
8207 ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
8209 mutex_enter(&dev->l2ad_mtx);
8210 list_insert_head(&dev->l2ad_buflist, hdr);
8211 mutex_exit(&dev->l2ad_mtx);
8213 (void) zfs_refcount_add_many(&dev->l2ad_alloc, psize,
8217 * Normally the L2ARC can use the hdr's data, but if
8218 * we're sharing data between the hdr and one of its
8219 * bufs, L2ARC needs its own copy of the data so that
8220 * the ZIO below can't race with the buf consumer.
8221 * Another case where we need to create a copy of the
8222 * data is when the buffer size is not device-aligned
8223 * and we need to pad the block to make it such.
8224 * That also keeps the clock hand suitably aligned.
8226 * To ensure that the copy will be available for the
8227 * lifetime of the ZIO and be cleaned up afterwards, we
8228 * add it to the l2arc_free_on_write queue.
8231 if (!HDR_SHARED_DATA(hdr) && psize == asize) {
8232 to_write = hdr->b_l1hdr.b_pabd;
8234 to_write = abd_alloc_for_io(asize,
8235 HDR_ISTYPE_METADATA(hdr));
8236 abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
8237 if (asize != psize) {
8238 abd_zero_off(to_write, psize,
8241 l2arc_free_abd_on_write(to_write, asize,
8244 wzio = zio_write_phys(pio, dev->l2ad_vdev,
8245 hdr->b_l2hdr.b_daddr, asize, to_write,
8246 ZIO_CHECKSUM_OFF, NULL, hdr,
8247 ZIO_PRIORITY_ASYNC_WRITE,
8248 ZIO_FLAG_CANFAIL, B_FALSE);
8250 write_lsize += HDR_GET_LSIZE(hdr);
8251 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
8254 write_psize += psize;
8255 write_asize += asize;
8256 dev->l2ad_hand += asize;
8258 mutex_exit(hash_lock);
8260 (void) zio_nowait(wzio);
8263 multilist_sublist_unlock(mls);
8269 /* No buffers selected for writing? */
8271 ASSERT0(write_lsize);
8272 ASSERT(!HDR_HAS_L1HDR(head));
8273 kmem_cache_free(hdr_l2only_cache, head);
8277 ASSERT3U(write_psize, <=, target_sz);
8278 ARCSTAT_BUMP(arcstat_l2_writes_sent);
8279 ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
8280 ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
8281 ARCSTAT_INCR(arcstat_l2_psize, write_psize);
8282 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
8285 * Bump device hand to the device start if it is approaching the end.
8286 * l2arc_evict() will already have evicted ahead for this case.
8288 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
8289 dev->l2ad_hand = dev->l2ad_start;
8290 dev->l2ad_first = B_FALSE;
8293 dev->l2ad_writing = B_TRUE;
8294 (void) zio_wait(pio);
8295 dev->l2ad_writing = B_FALSE;
8297 return (write_asize);
8301 * This thread feeds the L2ARC at regular intervals. This is the beating
8302 * heart of the L2ARC.
8306 l2arc_feed_thread(void *unused __unused)
8311 uint64_t size, wrote;
8312 clock_t begin, next = ddi_get_lbolt();
8314 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
8316 mutex_enter(&l2arc_feed_thr_lock);
8318 while (l2arc_thread_exit == 0) {
8319 CALLB_CPR_SAFE_BEGIN(&cpr);
8320 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
8321 next - ddi_get_lbolt());
8322 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
8323 next = ddi_get_lbolt() + hz;
8326 * Quick check for L2ARC devices.
8328 mutex_enter(&l2arc_dev_mtx);
8329 if (l2arc_ndev == 0) {
8330 mutex_exit(&l2arc_dev_mtx);
8333 mutex_exit(&l2arc_dev_mtx);
8334 begin = ddi_get_lbolt();
8337 * This selects the next l2arc device to write to, and in
8338 * doing so the next spa to feed from: dev->l2ad_spa. This
8339 * will return NULL if there are now no l2arc devices or if
8340 * they are all faulted.
8342 * If a device is returned, its spa's config lock is also
8343 * held to prevent device removal. l2arc_dev_get_next()
8344 * will grab and release l2arc_dev_mtx.
8346 if ((dev = l2arc_dev_get_next()) == NULL)
8349 spa = dev->l2ad_spa;
8350 ASSERT3P(spa, !=, NULL);
8353 * If the pool is read-only then force the feed thread to
8354 * sleep a little longer.
8356 if (!spa_writeable(spa)) {
8357 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
8358 spa_config_exit(spa, SCL_L2ARC, dev);
8363 * Avoid contributing to memory pressure.
8365 if (arc_reclaim_needed()) {
8366 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
8367 spa_config_exit(spa, SCL_L2ARC, dev);
8371 ARCSTAT_BUMP(arcstat_l2_feeds);
8373 size = l2arc_write_size();
8376 * Evict L2ARC buffers that will be overwritten.
8378 l2arc_evict(dev, size, B_FALSE);
8381 * Write ARC buffers.
8383 wrote = l2arc_write_buffers(spa, dev, size);
8386 * Calculate interval between writes.
8388 next = l2arc_write_interval(begin, size, wrote);
8389 spa_config_exit(spa, SCL_L2ARC, dev);
8392 l2arc_thread_exit = 0;
8393 cv_broadcast(&l2arc_feed_thr_cv);
8394 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
8399 l2arc_vdev_present(vdev_t *vd)
8403 mutex_enter(&l2arc_dev_mtx);
8404 for (dev = list_head(l2arc_dev_list); dev != NULL;
8405 dev = list_next(l2arc_dev_list, dev)) {
8406 if (dev->l2ad_vdev == vd)
8409 mutex_exit(&l2arc_dev_mtx);
8411 return (dev != NULL);
8415 * Add a vdev for use by the L2ARC. By this point the spa has already
8416 * validated the vdev and opened it.
8419 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
8421 l2arc_dev_t *adddev;
8423 ASSERT(!l2arc_vdev_present(vd));
8425 vdev_ashift_optimize(vd);
8428 * Create a new l2arc device entry.
8430 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
8431 adddev->l2ad_spa = spa;
8432 adddev->l2ad_vdev = vd;
8433 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
8434 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
8435 adddev->l2ad_hand = adddev->l2ad_start;
8436 adddev->l2ad_first = B_TRUE;
8437 adddev->l2ad_writing = B_FALSE;
8439 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
8441 * This is a list of all ARC buffers that are still valid on the
8444 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
8445 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
8447 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
8448 zfs_refcount_create(&adddev->l2ad_alloc);
8451 * Add device to global list
8453 mutex_enter(&l2arc_dev_mtx);
8454 list_insert_head(l2arc_dev_list, adddev);
8455 atomic_inc_64(&l2arc_ndev);
8456 mutex_exit(&l2arc_dev_mtx);
8460 * Remove a vdev from the L2ARC.
8463 l2arc_remove_vdev(vdev_t *vd)
8465 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
8468 * Find the device by vdev
8470 mutex_enter(&l2arc_dev_mtx);
8471 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
8472 nextdev = list_next(l2arc_dev_list, dev);
8473 if (vd == dev->l2ad_vdev) {
8478 ASSERT3P(remdev, !=, NULL);
8481 * Remove device from global list
8483 list_remove(l2arc_dev_list, remdev);
8484 l2arc_dev_last = NULL; /* may have been invalidated */
8485 atomic_dec_64(&l2arc_ndev);
8486 mutex_exit(&l2arc_dev_mtx);
8489 * Clear all buflists and ARC references. L2ARC device flush.
8491 l2arc_evict(remdev, 0, B_TRUE);
8492 list_destroy(&remdev->l2ad_buflist);
8493 mutex_destroy(&remdev->l2ad_mtx);
8494 zfs_refcount_destroy(&remdev->l2ad_alloc);
8495 kmem_free(remdev, sizeof (l2arc_dev_t));
8501 l2arc_thread_exit = 0;
8503 l2arc_writes_sent = 0;
8504 l2arc_writes_done = 0;
8506 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
8507 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
8508 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
8509 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
8511 l2arc_dev_list = &L2ARC_dev_list;
8512 l2arc_free_on_write = &L2ARC_free_on_write;
8513 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
8514 offsetof(l2arc_dev_t, l2ad_node));
8515 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
8516 offsetof(l2arc_data_free_t, l2df_list_node));
8523 * This is called from dmu_fini(), which is called from spa_fini();
8524 * Because of this, we can assume that all l2arc devices have
8525 * already been removed when the pools themselves were removed.
8528 l2arc_do_free_on_write();
8530 mutex_destroy(&l2arc_feed_thr_lock);
8531 cv_destroy(&l2arc_feed_thr_cv);
8532 mutex_destroy(&l2arc_dev_mtx);
8533 mutex_destroy(&l2arc_free_on_write_mtx);
8535 list_destroy(l2arc_dev_list);
8536 list_destroy(l2arc_free_on_write);
8542 if (!(spa_mode_global & FWRITE))
8545 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
8546 TS_RUN, minclsyspri);
8552 if (!(spa_mode_global & FWRITE))
8555 mutex_enter(&l2arc_feed_thr_lock);
8556 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
8557 l2arc_thread_exit = 1;
8558 while (l2arc_thread_exit != 0)
8559 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
8560 mutex_exit(&l2arc_feed_thr_lock);