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 <zfs_fletcher.h>
286 #include <sys/aggsum.h>
287 #include <sys/cityhash.h>
289 #include <machine/vmparam.h>
293 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
294 boolean_t arc_watch = B_FALSE;
299 static kmutex_t arc_reclaim_lock;
300 static kcondvar_t arc_reclaim_thread_cv;
301 static boolean_t arc_reclaim_thread_exit;
302 static kcondvar_t arc_reclaim_waiters_cv;
304 static kmutex_t arc_dnlc_evicts_lock;
305 static kcondvar_t arc_dnlc_evicts_cv;
306 static boolean_t arc_dnlc_evicts_thread_exit;
308 uint_t arc_reduce_dnlc_percent = 3;
311 * The number of headers to evict in arc_evict_state_impl() before
312 * dropping the sublist lock and evicting from another sublist. A lower
313 * value means we're more likely to evict the "correct" header (i.e. the
314 * oldest header in the arc state), but comes with higher overhead
315 * (i.e. more invocations of arc_evict_state_impl()).
317 int zfs_arc_evict_batch_limit = 10;
319 /* number of seconds before growing cache again */
320 static int arc_grow_retry = 60;
322 /* number of milliseconds before attempting a kmem-cache-reap */
323 static int arc_kmem_cache_reap_retry_ms = 1000;
325 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
326 int zfs_arc_overflow_shift = 8;
328 /* shift of arc_c for calculating both min and max arc_p */
329 static int arc_p_min_shift = 4;
331 /* log2(fraction of arc to reclaim) */
332 static int arc_shrink_shift = 7;
335 * log2(fraction of ARC which must be free to allow growing).
336 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
337 * when reading a new block into the ARC, we will evict an equal-sized block
340 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
341 * we will still not allow it to grow.
343 int arc_no_grow_shift = 5;
347 * minimum lifespan of a prefetch block in clock ticks
348 * (initialized in arc_init())
350 static int zfs_arc_min_prefetch_ms = 1;
351 static int zfs_arc_min_prescient_prefetch_ms = 6;
354 * If this percent of memory is free, don't throttle.
356 int arc_lotsfree_percent = 10;
359 extern boolean_t zfs_prefetch_disable;
362 * The arc has filled available memory and has now warmed up.
364 static boolean_t arc_warm;
367 * log2 fraction of the zio arena to keep free.
369 int arc_zio_arena_free_shift = 2;
372 * These tunables are for performance analysis.
374 uint64_t zfs_arc_max;
375 uint64_t zfs_arc_min;
376 uint64_t zfs_arc_meta_limit = 0;
377 uint64_t zfs_arc_meta_min = 0;
378 uint64_t zfs_arc_dnode_limit = 0;
379 uint64_t zfs_arc_dnode_reduce_percent = 10;
380 int zfs_arc_grow_retry = 0;
381 int zfs_arc_shrink_shift = 0;
382 int zfs_arc_no_grow_shift = 0;
383 int zfs_arc_p_min_shift = 0;
384 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
385 u_int zfs_arc_free_target = 0;
387 /* Absolute min for arc min / max is 16MB. */
388 static uint64_t arc_abs_min = 16 << 20;
391 * ARC dirty data constraints for arc_tempreserve_space() throttle
393 uint_t zfs_arc_dirty_limit_percent = 50; /* total dirty data limit */
394 uint_t zfs_arc_anon_limit_percent = 25; /* anon block dirty limit */
395 uint_t zfs_arc_pool_dirty_percent = 20; /* each pool's anon allowance */
397 boolean_t zfs_compressed_arc_enabled = B_TRUE;
399 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
400 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
401 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
402 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
403 static int sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS);
405 #if defined(__FreeBSD__) && defined(_KERNEL)
407 arc_free_target_init(void *unused __unused)
410 zfs_arc_free_target = vm_cnt.v_free_target;
412 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
413 arc_free_target_init, NULL);
415 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
416 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
417 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
418 TUNABLE_INT("vfs.zfs.arc_grow_retry", &zfs_arc_grow_retry);
419 TUNABLE_INT("vfs.zfs.arc_no_grow_shift", &zfs_arc_no_grow_shift);
420 SYSCTL_DECL(_vfs_zfs);
421 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
422 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
423 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
424 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
425 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_no_grow_shift, CTLTYPE_U32 | CTLFLAG_RWTUN,
426 0, sizeof(uint32_t), sysctl_vfs_zfs_arc_no_grow_shift, "U",
427 "log2(fraction of ARC which must be free to allow growing)");
428 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
429 &zfs_arc_average_blocksize, 0,
430 "ARC average blocksize");
431 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
432 &arc_shrink_shift, 0,
433 "log2(fraction of arc to reclaim)");
434 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_grow_retry, CTLFLAG_RW,
436 "Wait in seconds before considering growing ARC");
437 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
438 &zfs_compressed_arc_enabled, 0, "Enable compressed ARC");
441 * We don't have a tunable for arc_free_target due to the dependency on
442 * pagedaemon initialisation.
444 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
445 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
446 sysctl_vfs_zfs_arc_free_target, "IU",
447 "Desired number of free pages below which ARC triggers reclaim");
450 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
455 val = zfs_arc_free_target;
456 err = sysctl_handle_int(oidp, &val, 0, req);
457 if (err != 0 || req->newptr == NULL)
462 if (val > vm_cnt.v_page_count)
465 zfs_arc_free_target = val;
471 * Must be declared here, before the definition of corresponding kstat
472 * macro which uses the same names will confuse the compiler.
474 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
475 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
476 sysctl_vfs_zfs_arc_meta_limit, "QU",
477 "ARC metadata limit");
481 * Note that buffers can be in one of 6 states:
482 * ARC_anon - anonymous (discussed below)
483 * ARC_mru - recently used, currently cached
484 * ARC_mru_ghost - recentely used, no longer in cache
485 * ARC_mfu - frequently used, currently cached
486 * ARC_mfu_ghost - frequently used, no longer in cache
487 * ARC_l2c_only - exists in L2ARC but not other states
488 * When there are no active references to the buffer, they are
489 * are linked onto a list in one of these arc states. These are
490 * the only buffers that can be evicted or deleted. Within each
491 * state there are multiple lists, one for meta-data and one for
492 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
493 * etc.) is tracked separately so that it can be managed more
494 * explicitly: favored over data, limited explicitly.
496 * Anonymous buffers are buffers that are not associated with
497 * a DVA. These are buffers that hold dirty block copies
498 * before they are written to stable storage. By definition,
499 * they are "ref'd" and are considered part of arc_mru
500 * that cannot be freed. Generally, they will aquire a DVA
501 * as they are written and migrate onto the arc_mru list.
503 * The ARC_l2c_only state is for buffers that are in the second
504 * level ARC but no longer in any of the ARC_m* lists. The second
505 * level ARC itself may also contain buffers that are in any of
506 * the ARC_m* states - meaning that a buffer can exist in two
507 * places. The reason for the ARC_l2c_only state is to keep the
508 * buffer header in the hash table, so that reads that hit the
509 * second level ARC benefit from these fast lookups.
512 typedef struct arc_state {
514 * list of evictable buffers
516 multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
518 * total amount of evictable data in this state
520 refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
522 * total amount of data in this state; this includes: evictable,
523 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
525 refcount_t arcs_size;
529 static arc_state_t ARC_anon;
530 static arc_state_t ARC_mru;
531 static arc_state_t ARC_mru_ghost;
532 static arc_state_t ARC_mfu;
533 static arc_state_t ARC_mfu_ghost;
534 static arc_state_t ARC_l2c_only;
536 typedef struct arc_stats {
537 kstat_named_t arcstat_hits;
538 kstat_named_t arcstat_misses;
539 kstat_named_t arcstat_demand_data_hits;
540 kstat_named_t arcstat_demand_data_misses;
541 kstat_named_t arcstat_demand_metadata_hits;
542 kstat_named_t arcstat_demand_metadata_misses;
543 kstat_named_t arcstat_prefetch_data_hits;
544 kstat_named_t arcstat_prefetch_data_misses;
545 kstat_named_t arcstat_prefetch_metadata_hits;
546 kstat_named_t arcstat_prefetch_metadata_misses;
547 kstat_named_t arcstat_mru_hits;
548 kstat_named_t arcstat_mru_ghost_hits;
549 kstat_named_t arcstat_mfu_hits;
550 kstat_named_t arcstat_mfu_ghost_hits;
551 kstat_named_t arcstat_allocated;
552 kstat_named_t arcstat_deleted;
554 * Number of buffers that could not be evicted because the hash lock
555 * was held by another thread. The lock may not necessarily be held
556 * by something using the same buffer, since hash locks are shared
557 * by multiple buffers.
559 kstat_named_t arcstat_mutex_miss;
561 * Number of buffers skipped when updating the access state due to the
562 * header having already been released after acquiring the hash lock.
564 kstat_named_t arcstat_access_skip;
566 * Number of buffers skipped because they have I/O in progress, are
567 * indirect prefetch buffers that have not lived long enough, or are
568 * not from the spa we're trying to evict from.
570 kstat_named_t arcstat_evict_skip;
572 * Number of times arc_evict_state() was unable to evict enough
573 * buffers to reach it's target amount.
575 kstat_named_t arcstat_evict_not_enough;
576 kstat_named_t arcstat_evict_l2_cached;
577 kstat_named_t arcstat_evict_l2_eligible;
578 kstat_named_t arcstat_evict_l2_ineligible;
579 kstat_named_t arcstat_evict_l2_skip;
580 kstat_named_t arcstat_hash_elements;
581 kstat_named_t arcstat_hash_elements_max;
582 kstat_named_t arcstat_hash_collisions;
583 kstat_named_t arcstat_hash_chains;
584 kstat_named_t arcstat_hash_chain_max;
585 kstat_named_t arcstat_p;
586 kstat_named_t arcstat_c;
587 kstat_named_t arcstat_c_min;
588 kstat_named_t arcstat_c_max;
589 /* Not updated directly; only synced in arc_kstat_update. */
590 kstat_named_t arcstat_size;
592 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
593 * Note that the compressed bytes may match the uncompressed bytes
594 * if the block is either not compressed or compressed arc is disabled.
596 kstat_named_t arcstat_compressed_size;
598 * Uncompressed size of the data stored in b_pabd. If compressed
599 * arc is disabled then this value will be identical to the stat
602 kstat_named_t arcstat_uncompressed_size;
604 * Number of bytes stored in all the arc_buf_t's. This is classified
605 * as "overhead" since this data is typically short-lived and will
606 * be evicted from the arc when it becomes unreferenced unless the
607 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
608 * values have been set (see comment in dbuf.c for more information).
610 kstat_named_t arcstat_overhead_size;
612 * Number of bytes consumed by internal ARC structures necessary
613 * for tracking purposes; these structures are not actually
614 * backed by ARC buffers. This includes arc_buf_hdr_t structures
615 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
616 * caches), and arc_buf_t structures (allocated via arc_buf_t
618 * Not updated directly; only synced in arc_kstat_update.
620 kstat_named_t arcstat_hdr_size;
622 * Number of bytes consumed by ARC buffers of type equal to
623 * ARC_BUFC_DATA. This is generally consumed by buffers backing
624 * on disk user data (e.g. plain file contents).
625 * Not updated directly; only synced in arc_kstat_update.
627 kstat_named_t arcstat_data_size;
629 * Number of bytes consumed by ARC buffers of type equal to
630 * ARC_BUFC_METADATA. This is generally consumed by buffers
631 * backing on disk data that is used for internal ZFS
632 * structures (e.g. ZAP, dnode, indirect blocks, etc).
633 * Not updated directly; only synced in arc_kstat_update.
635 kstat_named_t arcstat_metadata_size;
637 * Number of bytes consumed by dmu_buf_impl_t objects.
639 kstat_named_t arcstat_dbuf_size;
641 * Number of bytes consumed by dnode_t objects.
643 kstat_named_t arcstat_dnode_size;
645 * Number of bytes consumed by bonus buffers.
647 kstat_named_t arcstat_bonus_size;
649 * Total number of bytes consumed by ARC buffers residing in the
650 * arc_anon state. This includes *all* buffers in the arc_anon
651 * state; e.g. data, metadata, evictable, and unevictable buffers
652 * are all included in this value.
653 * Not updated directly; only synced in arc_kstat_update.
655 kstat_named_t arcstat_anon_size;
657 * Number of bytes consumed by ARC buffers that meet the
658 * following criteria: backing buffers of type ARC_BUFC_DATA,
659 * residing in the arc_anon state, and are eligible for eviction
660 * (e.g. have no outstanding holds on the buffer).
661 * Not updated directly; only synced in arc_kstat_update.
663 kstat_named_t arcstat_anon_evictable_data;
665 * Number of bytes consumed by ARC buffers that meet the
666 * following criteria: backing buffers of type ARC_BUFC_METADATA,
667 * residing in the arc_anon state, and are eligible for eviction
668 * (e.g. have no outstanding holds on the buffer).
669 * Not updated directly; only synced in arc_kstat_update.
671 kstat_named_t arcstat_anon_evictable_metadata;
673 * Total number of bytes consumed by ARC buffers residing in the
674 * arc_mru state. This includes *all* buffers in the arc_mru
675 * state; e.g. data, metadata, evictable, and unevictable buffers
676 * are all included in this value.
677 * Not updated directly; only synced in arc_kstat_update.
679 kstat_named_t arcstat_mru_size;
681 * Number of bytes consumed by ARC buffers that meet the
682 * following criteria: backing buffers of type ARC_BUFC_DATA,
683 * residing in the arc_mru state, and are eligible for eviction
684 * (e.g. have no outstanding holds on the buffer).
685 * Not updated directly; only synced in arc_kstat_update.
687 kstat_named_t arcstat_mru_evictable_data;
689 * Number of bytes consumed by ARC buffers that meet the
690 * following criteria: backing buffers of type ARC_BUFC_METADATA,
691 * residing in the arc_mru state, and are eligible for eviction
692 * (e.g. have no outstanding holds on the buffer).
693 * Not updated directly; only synced in arc_kstat_update.
695 kstat_named_t arcstat_mru_evictable_metadata;
697 * Total number of bytes that *would have been* consumed by ARC
698 * buffers in the arc_mru_ghost state. The key thing to note
699 * here, is the fact that this size doesn't actually indicate
700 * RAM consumption. The ghost lists only consist of headers and
701 * don't actually have ARC buffers linked off of these headers.
702 * Thus, *if* the headers had associated ARC buffers, these
703 * buffers *would have* consumed this number of bytes.
704 * Not updated directly; only synced in arc_kstat_update.
706 kstat_named_t arcstat_mru_ghost_size;
708 * Number of bytes that *would have been* consumed by ARC
709 * buffers that are eligible for eviction, of type
710 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
711 * Not updated directly; only synced in arc_kstat_update.
713 kstat_named_t arcstat_mru_ghost_evictable_data;
715 * Number of bytes that *would have been* consumed by ARC
716 * buffers that are eligible for eviction, of type
717 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
718 * Not updated directly; only synced in arc_kstat_update.
720 kstat_named_t arcstat_mru_ghost_evictable_metadata;
722 * Total number of bytes consumed by ARC buffers residing in the
723 * arc_mfu state. This includes *all* buffers in the arc_mfu
724 * state; e.g. data, metadata, evictable, and unevictable buffers
725 * are all included in this value.
726 * Not updated directly; only synced in arc_kstat_update.
728 kstat_named_t arcstat_mfu_size;
730 * Number of bytes consumed by ARC buffers that are eligible for
731 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
733 * Not updated directly; only synced in arc_kstat_update.
735 kstat_named_t arcstat_mfu_evictable_data;
737 * Number of bytes consumed by ARC buffers that are eligible for
738 * eviction, of type ARC_BUFC_METADATA, and reside in the
740 * Not updated directly; only synced in arc_kstat_update.
742 kstat_named_t arcstat_mfu_evictable_metadata;
744 * Total number of bytes that *would have been* consumed by ARC
745 * buffers in the arc_mfu_ghost state. See the comment above
746 * arcstat_mru_ghost_size for more details.
747 * Not updated directly; only synced in arc_kstat_update.
749 kstat_named_t arcstat_mfu_ghost_size;
751 * Number of bytes that *would have been* consumed by ARC
752 * buffers that are eligible for eviction, of type
753 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
754 * Not updated directly; only synced in arc_kstat_update.
756 kstat_named_t arcstat_mfu_ghost_evictable_data;
758 * Number of bytes that *would have been* consumed by ARC
759 * buffers that are eligible for eviction, of type
760 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
761 * Not updated directly; only synced in arc_kstat_update.
763 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
764 kstat_named_t arcstat_l2_hits;
765 kstat_named_t arcstat_l2_misses;
766 kstat_named_t arcstat_l2_feeds;
767 kstat_named_t arcstat_l2_rw_clash;
768 kstat_named_t arcstat_l2_read_bytes;
769 kstat_named_t arcstat_l2_write_bytes;
770 kstat_named_t arcstat_l2_writes_sent;
771 kstat_named_t arcstat_l2_writes_done;
772 kstat_named_t arcstat_l2_writes_error;
773 kstat_named_t arcstat_l2_writes_lock_retry;
774 kstat_named_t arcstat_l2_evict_lock_retry;
775 kstat_named_t arcstat_l2_evict_reading;
776 kstat_named_t arcstat_l2_evict_l1cached;
777 kstat_named_t arcstat_l2_free_on_write;
778 kstat_named_t arcstat_l2_abort_lowmem;
779 kstat_named_t arcstat_l2_cksum_bad;
780 kstat_named_t arcstat_l2_io_error;
781 kstat_named_t arcstat_l2_lsize;
782 kstat_named_t arcstat_l2_psize;
783 /* Not updated directly; only synced in arc_kstat_update. */
784 kstat_named_t arcstat_l2_hdr_size;
785 kstat_named_t arcstat_l2_write_trylock_fail;
786 kstat_named_t arcstat_l2_write_passed_headroom;
787 kstat_named_t arcstat_l2_write_spa_mismatch;
788 kstat_named_t arcstat_l2_write_in_l2;
789 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
790 kstat_named_t arcstat_l2_write_not_cacheable;
791 kstat_named_t arcstat_l2_write_full;
792 kstat_named_t arcstat_l2_write_buffer_iter;
793 kstat_named_t arcstat_l2_write_pios;
794 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
795 kstat_named_t arcstat_l2_write_buffer_list_iter;
796 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
797 kstat_named_t arcstat_memory_throttle_count;
798 kstat_named_t arcstat_memory_direct_count;
799 kstat_named_t arcstat_memory_indirect_count;
800 kstat_named_t arcstat_memory_all_bytes;
801 kstat_named_t arcstat_memory_free_bytes;
802 kstat_named_t arcstat_memory_available_bytes;
803 kstat_named_t arcstat_no_grow;
804 kstat_named_t arcstat_tempreserve;
805 kstat_named_t arcstat_loaned_bytes;
806 kstat_named_t arcstat_prune;
807 /* Not updated directly; only synced in arc_kstat_update. */
808 kstat_named_t arcstat_meta_used;
809 kstat_named_t arcstat_meta_limit;
810 kstat_named_t arcstat_dnode_limit;
811 kstat_named_t arcstat_meta_max;
812 kstat_named_t arcstat_meta_min;
813 kstat_named_t arcstat_async_upgrade_sync;
814 kstat_named_t arcstat_demand_hit_predictive_prefetch;
815 kstat_named_t arcstat_demand_hit_prescient_prefetch;
818 static arc_stats_t arc_stats = {
819 { "hits", KSTAT_DATA_UINT64 },
820 { "misses", KSTAT_DATA_UINT64 },
821 { "demand_data_hits", KSTAT_DATA_UINT64 },
822 { "demand_data_misses", KSTAT_DATA_UINT64 },
823 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
824 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
825 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
826 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
827 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
828 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
829 { "mru_hits", KSTAT_DATA_UINT64 },
830 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
831 { "mfu_hits", KSTAT_DATA_UINT64 },
832 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
833 { "allocated", KSTAT_DATA_UINT64 },
834 { "deleted", KSTAT_DATA_UINT64 },
835 { "mutex_miss", KSTAT_DATA_UINT64 },
836 { "access_skip", KSTAT_DATA_UINT64 },
837 { "evict_skip", KSTAT_DATA_UINT64 },
838 { "evict_not_enough", KSTAT_DATA_UINT64 },
839 { "evict_l2_cached", KSTAT_DATA_UINT64 },
840 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
841 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
842 { "evict_l2_skip", KSTAT_DATA_UINT64 },
843 { "hash_elements", KSTAT_DATA_UINT64 },
844 { "hash_elements_max", KSTAT_DATA_UINT64 },
845 { "hash_collisions", KSTAT_DATA_UINT64 },
846 { "hash_chains", KSTAT_DATA_UINT64 },
847 { "hash_chain_max", KSTAT_DATA_UINT64 },
848 { "p", KSTAT_DATA_UINT64 },
849 { "c", KSTAT_DATA_UINT64 },
850 { "c_min", KSTAT_DATA_UINT64 },
851 { "c_max", KSTAT_DATA_UINT64 },
852 { "size", KSTAT_DATA_UINT64 },
853 { "compressed_size", KSTAT_DATA_UINT64 },
854 { "uncompressed_size", KSTAT_DATA_UINT64 },
855 { "overhead_size", KSTAT_DATA_UINT64 },
856 { "hdr_size", KSTAT_DATA_UINT64 },
857 { "data_size", KSTAT_DATA_UINT64 },
858 { "metadata_size", KSTAT_DATA_UINT64 },
859 { "dbuf_size", KSTAT_DATA_UINT64 },
860 { "dnode_size", KSTAT_DATA_UINT64 },
861 { "bonus_size", KSTAT_DATA_UINT64 },
862 { "anon_size", KSTAT_DATA_UINT64 },
863 { "anon_evictable_data", KSTAT_DATA_UINT64 },
864 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
865 { "mru_size", KSTAT_DATA_UINT64 },
866 { "mru_evictable_data", KSTAT_DATA_UINT64 },
867 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
868 { "mru_ghost_size", KSTAT_DATA_UINT64 },
869 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
870 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
871 { "mfu_size", KSTAT_DATA_UINT64 },
872 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
873 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
874 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
875 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
876 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
877 { "l2_hits", KSTAT_DATA_UINT64 },
878 { "l2_misses", KSTAT_DATA_UINT64 },
879 { "l2_feeds", KSTAT_DATA_UINT64 },
880 { "l2_rw_clash", KSTAT_DATA_UINT64 },
881 { "l2_read_bytes", KSTAT_DATA_UINT64 },
882 { "l2_write_bytes", KSTAT_DATA_UINT64 },
883 { "l2_writes_sent", KSTAT_DATA_UINT64 },
884 { "l2_writes_done", KSTAT_DATA_UINT64 },
885 { "l2_writes_error", KSTAT_DATA_UINT64 },
886 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
887 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
888 { "l2_evict_reading", KSTAT_DATA_UINT64 },
889 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
890 { "l2_free_on_write", KSTAT_DATA_UINT64 },
891 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
892 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
893 { "l2_io_error", KSTAT_DATA_UINT64 },
894 { "l2_size", KSTAT_DATA_UINT64 },
895 { "l2_asize", KSTAT_DATA_UINT64 },
896 { "l2_hdr_size", KSTAT_DATA_UINT64 },
897 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
898 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
899 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
900 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
901 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
902 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
903 { "l2_write_full", KSTAT_DATA_UINT64 },
904 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
905 { "l2_write_pios", KSTAT_DATA_UINT64 },
906 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
907 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
908 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
909 { "memory_throttle_count", KSTAT_DATA_UINT64 },
910 { "memory_direct_count", KSTAT_DATA_UINT64 },
911 { "memory_indirect_count", KSTAT_DATA_UINT64 },
912 { "memory_all_bytes", KSTAT_DATA_UINT64 },
913 { "memory_free_bytes", KSTAT_DATA_UINT64 },
914 { "memory_available_bytes", KSTAT_DATA_UINT64 },
915 { "arc_no_grow", KSTAT_DATA_UINT64 },
916 { "arc_tempreserve", KSTAT_DATA_UINT64 },
917 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
918 { "arc_prune", KSTAT_DATA_UINT64 },
919 { "arc_meta_used", KSTAT_DATA_UINT64 },
920 { "arc_meta_limit", KSTAT_DATA_UINT64 },
921 { "arc_dnode_limit", KSTAT_DATA_UINT64 },
922 { "arc_meta_max", KSTAT_DATA_UINT64 },
923 { "arc_meta_min", KSTAT_DATA_UINT64 },
924 { "async_upgrade_sync", KSTAT_DATA_UINT64 },
925 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
926 { "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
929 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
931 #define ARCSTAT_INCR(stat, val) \
932 atomic_add_64(&arc_stats.stat.value.ui64, (val))
934 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
935 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
937 #define ARCSTAT_MAX(stat, val) { \
939 while ((val) > (m = arc_stats.stat.value.ui64) && \
940 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
944 #define ARCSTAT_MAXSTAT(stat) \
945 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
948 * We define a macro to allow ARC hits/misses to be easily broken down by
949 * two separate conditions, giving a total of four different subtypes for
950 * each of hits and misses (so eight statistics total).
952 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
955 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
957 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
961 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
963 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
968 static arc_state_t *arc_anon;
969 static arc_state_t *arc_mru;
970 static arc_state_t *arc_mru_ghost;
971 static arc_state_t *arc_mfu;
972 static arc_state_t *arc_mfu_ghost;
973 static arc_state_t *arc_l2c_only;
976 * There are several ARC variables that are critical to export as kstats --
977 * but we don't want to have to grovel around in the kstat whenever we wish to
978 * manipulate them. For these variables, we therefore define them to be in
979 * terms of the statistic variable. This assures that we are not introducing
980 * the possibility of inconsistency by having shadow copies of the variables,
981 * while still allowing the code to be readable.
983 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
984 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
985 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
986 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
987 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
988 #define arc_dnode_limit ARCSTAT(arcstat_dnode_limit) /* max size for dnodes */
989 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
990 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
991 #define arc_dbuf_size ARCSTAT(arcstat_dbuf_size) /* dbuf metadata */
992 #define arc_dnode_size ARCSTAT(arcstat_dnode_size) /* dnode metadata */
993 #define arc_bonus_size ARCSTAT(arcstat_bonus_size) /* bonus buffer metadata */
995 /* compressed size of entire arc */
996 #define arc_compressed_size ARCSTAT(arcstat_compressed_size)
997 /* uncompressed size of entire arc */
998 #define arc_uncompressed_size ARCSTAT(arcstat_uncompressed_size)
999 /* number of bytes in the arc from arc_buf_t's */
1000 #define arc_overhead_size ARCSTAT(arcstat_overhead_size)
1003 * There are also some ARC variables that we want to export, but that are
1004 * updated so often that having the canonical representation be the statistic
1005 * variable causes a performance bottleneck. We want to use aggsum_t's for these
1006 * instead, but still be able to export the kstat in the same way as before.
1007 * The solution is to always use the aggsum version, except in the kstat update
1011 aggsum_t arc_meta_used;
1012 aggsum_t astat_data_size;
1013 aggsum_t astat_metadata_size;
1014 aggsum_t astat_hdr_size;
1015 aggsum_t astat_bonus_size;
1016 aggsum_t astat_dnode_size;
1017 aggsum_t astat_dbuf_size;
1018 aggsum_t astat_l2_hdr_size;
1020 static list_t arc_prune_list;
1021 static kmutex_t arc_prune_mtx;
1022 static taskq_t *arc_prune_taskq;
1024 static int arc_no_grow; /* Don't try to grow cache size */
1025 static uint64_t arc_tempreserve;
1026 static uint64_t arc_loaned_bytes;
1028 typedef struct arc_callback arc_callback_t;
1030 struct arc_callback {
1032 arc_read_done_func_t *acb_done;
1034 boolean_t acb_compressed;
1035 zio_t *acb_zio_dummy;
1036 zio_t *acb_zio_head;
1037 arc_callback_t *acb_next;
1040 typedef struct arc_write_callback arc_write_callback_t;
1042 struct arc_write_callback {
1044 arc_write_done_func_t *awcb_ready;
1045 arc_write_done_func_t *awcb_children_ready;
1046 arc_write_done_func_t *awcb_physdone;
1047 arc_write_done_func_t *awcb_done;
1048 arc_buf_t *awcb_buf;
1052 * ARC buffers are separated into multiple structs as a memory saving measure:
1053 * - Common fields struct, always defined, and embedded within it:
1054 * - L2-only fields, always allocated but undefined when not in L2ARC
1055 * - L1-only fields, only allocated when in L1ARC
1057 * Buffer in L1 Buffer only in L2
1058 * +------------------------+ +------------------------+
1059 * | arc_buf_hdr_t | | arc_buf_hdr_t |
1063 * +------------------------+ +------------------------+
1064 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
1065 * | (undefined if L1-only) | | |
1066 * +------------------------+ +------------------------+
1067 * | l1arc_buf_hdr_t |
1072 * +------------------------+
1074 * Because it's possible for the L2ARC to become extremely large, we can wind
1075 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
1076 * is minimized by only allocating the fields necessary for an L1-cached buffer
1077 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
1078 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
1079 * words in pointers. arc_hdr_realloc() is used to switch a header between
1080 * these two allocation states.
1082 typedef struct l1arc_buf_hdr {
1083 kmutex_t b_freeze_lock;
1084 zio_cksum_t *b_freeze_cksum;
1087 * Used for debugging with kmem_flags - by allocating and freeing
1088 * b_thawed when the buffer is thawed, we get a record of the stack
1089 * trace that thawed it.
1096 /* for waiting on writes to complete */
1100 /* protected by arc state mutex */
1101 arc_state_t *b_state;
1102 multilist_node_t b_arc_node;
1104 /* updated atomically */
1105 clock_t b_arc_access;
1107 /* self protecting */
1108 refcount_t b_refcnt;
1110 arc_callback_t *b_acb;
1114 typedef struct l2arc_dev l2arc_dev_t;
1116 typedef struct l2arc_buf_hdr {
1117 /* protected by arc_buf_hdr mutex */
1118 l2arc_dev_t *b_dev; /* L2ARC device */
1119 uint64_t b_daddr; /* disk address, offset byte */
1121 list_node_t b_l2node;
1124 struct arc_buf_hdr {
1125 /* protected by hash lock */
1129 arc_buf_contents_t b_type;
1130 arc_buf_hdr_t *b_hash_next;
1131 arc_flags_t b_flags;
1134 * This field stores the size of the data buffer after
1135 * compression, and is set in the arc's zio completion handlers.
1136 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1138 * While the block pointers can store up to 32MB in their psize
1139 * field, we can only store up to 32MB minus 512B. This is due
1140 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1141 * a field of zeros represents 512B in the bp). We can't use a
1142 * bias of 1 since we need to reserve a psize of zero, here, to
1143 * represent holes and embedded blocks.
1145 * This isn't a problem in practice, since the maximum size of a
1146 * buffer is limited to 16MB, so we never need to store 32MB in
1147 * this field. Even in the upstream illumos code base, the
1148 * maximum size of a buffer is limited to 16MB.
1153 * This field stores the size of the data buffer before
1154 * compression, and cannot change once set. It is in units
1155 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1157 uint16_t b_lsize; /* immutable */
1158 uint64_t b_spa; /* immutable */
1160 /* L2ARC fields. Undefined when not in L2ARC. */
1161 l2arc_buf_hdr_t b_l2hdr;
1162 /* L1ARC fields. Undefined when in l2arc_only state */
1163 l1arc_buf_hdr_t b_l1hdr;
1166 #if defined(__FreeBSD__) && defined(_KERNEL)
1168 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1173 val = arc_meta_limit;
1174 err = sysctl_handle_64(oidp, &val, 0, req);
1175 if (err != 0 || req->newptr == NULL)
1178 if (val <= 0 || val > arc_c_max)
1181 arc_meta_limit = val;
1186 sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS)
1191 val = arc_no_grow_shift;
1192 err = sysctl_handle_32(oidp, &val, 0, req);
1193 if (err != 0 || req->newptr == NULL)
1196 if (val >= arc_shrink_shift)
1199 arc_no_grow_shift = val;
1204 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1210 err = sysctl_handle_64(oidp, &val, 0, req);
1211 if (err != 0 || req->newptr == NULL)
1214 if (zfs_arc_max == 0) {
1215 /* Loader tunable so blindly set */
1220 if (val < arc_abs_min || val > kmem_size())
1222 if (val < arc_c_min)
1224 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1230 arc_p = (arc_c >> 1);
1232 if (zfs_arc_meta_limit == 0) {
1233 /* limit meta-data to 1/4 of the arc capacity */
1234 arc_meta_limit = arc_c_max / 4;
1237 /* if kmem_flags are set, lets try to use less memory */
1238 if (kmem_debugging())
1241 zfs_arc_max = arc_c;
1247 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1253 err = sysctl_handle_64(oidp, &val, 0, req);
1254 if (err != 0 || req->newptr == NULL)
1257 if (zfs_arc_min == 0) {
1258 /* Loader tunable so blindly set */
1263 if (val < arc_abs_min || val > arc_c_max)
1268 if (zfs_arc_meta_min == 0)
1269 arc_meta_min = arc_c_min / 2;
1271 if (arc_c < arc_c_min)
1274 zfs_arc_min = arc_c_min;
1280 #define GHOST_STATE(state) \
1281 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
1282 (state) == arc_l2c_only)
1284 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1285 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1286 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1287 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1288 #define HDR_PRESCIENT_PREFETCH(hdr) \
1289 ((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
1290 #define HDR_COMPRESSION_ENABLED(hdr) \
1291 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1293 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1294 #define HDR_L2_READING(hdr) \
1295 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1296 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1297 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1298 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1299 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1300 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1302 #define HDR_ISTYPE_METADATA(hdr) \
1303 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1304 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1306 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1307 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1309 /* For storing compression mode in b_flags */
1310 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1312 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1313 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1314 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1315 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1317 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
1318 #define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1319 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1325 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1326 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1329 * Hash table routines
1332 #define HT_LOCK_PAD CACHE_LINE_SIZE
1337 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1341 #define BUF_LOCKS 256
1342 typedef struct buf_hash_table {
1344 arc_buf_hdr_t **ht_table;
1345 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1348 static buf_hash_table_t buf_hash_table;
1350 #define BUF_HASH_INDEX(spa, dva, birth) \
1351 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1352 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1353 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1354 #define HDR_LOCK(hdr) \
1355 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1357 uint64_t zfs_crc64_table[256];
1363 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1364 #define L2ARC_HEADROOM 2 /* num of writes */
1366 * If we discover during ARC scan any buffers to be compressed, we boost
1367 * our headroom for the next scanning cycle by this percentage multiple.
1369 #define L2ARC_HEADROOM_BOOST 200
1370 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1371 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1373 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1374 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1376 /* L2ARC Performance Tunables */
1377 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1378 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1379 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1380 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1381 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1382 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1383 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1384 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1385 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1387 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1388 &l2arc_write_max, 0, "max write size");
1389 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1390 &l2arc_write_boost, 0, "extra write during warmup");
1391 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1392 &l2arc_headroom, 0, "number of dev writes");
1393 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1394 &l2arc_feed_secs, 0, "interval seconds");
1395 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1396 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1398 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1399 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1400 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1401 &l2arc_feed_again, 0, "turbo warmup");
1402 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1403 &l2arc_norw, 0, "no reads during writes");
1405 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1406 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1407 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1408 &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1409 "size of anonymous state");
1410 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1411 &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1412 "size of anonymous state");
1414 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1415 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1416 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1417 &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1418 "size of metadata in mru state");
1419 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1420 &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1421 "size of data in mru state");
1423 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1424 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1425 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1426 &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1427 "size of metadata in mru ghost state");
1428 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1429 &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1430 "size of data in mru ghost state");
1432 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1433 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1434 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1435 &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1436 "size of metadata in mfu state");
1437 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1438 &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1439 "size of data in mfu state");
1441 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1442 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1443 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1444 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1445 "size of metadata in mfu ghost state");
1446 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1447 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1448 "size of data in mfu ghost state");
1450 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1451 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1453 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prefetch_ms, CTLFLAG_RW,
1454 &zfs_arc_min_prefetch_ms, 0, "Min life of prefetch block in ms");
1455 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prescient_prefetch_ms, CTLFLAG_RW,
1456 &zfs_arc_min_prescient_prefetch_ms, 0, "Min life of prescient prefetched block in ms");
1462 vdev_t *l2ad_vdev; /* vdev */
1463 spa_t *l2ad_spa; /* spa */
1464 uint64_t l2ad_hand; /* next write location */
1465 uint64_t l2ad_start; /* first addr on device */
1466 uint64_t l2ad_end; /* last addr on device */
1467 boolean_t l2ad_first; /* first sweep through */
1468 boolean_t l2ad_writing; /* currently writing */
1469 kmutex_t l2ad_mtx; /* lock for buffer list */
1470 list_t l2ad_buflist; /* buffer list */
1471 list_node_t l2ad_node; /* device list node */
1472 refcount_t l2ad_alloc; /* allocated bytes */
1475 static list_t L2ARC_dev_list; /* device list */
1476 static list_t *l2arc_dev_list; /* device list pointer */
1477 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1478 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1479 static list_t L2ARC_free_on_write; /* free after write buf list */
1480 static list_t *l2arc_free_on_write; /* free after write list ptr */
1481 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1482 static uint64_t l2arc_ndev; /* number of devices */
1484 typedef struct l2arc_read_callback {
1485 arc_buf_hdr_t *l2rcb_hdr; /* read header */
1486 blkptr_t l2rcb_bp; /* original blkptr */
1487 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1488 int l2rcb_flags; /* original flags */
1489 abd_t *l2rcb_abd; /* temporary buffer */
1490 } l2arc_read_callback_t;
1492 typedef struct l2arc_write_callback {
1493 l2arc_dev_t *l2wcb_dev; /* device info */
1494 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1495 } l2arc_write_callback_t;
1497 typedef struct l2arc_data_free {
1498 /* protected by l2arc_free_on_write_mtx */
1501 arc_buf_contents_t l2df_type;
1502 list_node_t l2df_list_node;
1503 } l2arc_data_free_t;
1505 static kmutex_t l2arc_feed_thr_lock;
1506 static kcondvar_t l2arc_feed_thr_cv;
1507 static uint8_t l2arc_thread_exit;
1509 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1510 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1511 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1512 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1513 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1514 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1515 static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1516 static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
1517 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1518 static boolean_t arc_is_overflowing();
1519 static void arc_buf_watch(arc_buf_t *);
1520 static void arc_prune_async(int64_t);
1522 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1523 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1524 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1525 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1527 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1528 static void l2arc_read_done(zio_t *);
1531 l2arc_trim(const arc_buf_hdr_t *hdr)
1533 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1535 ASSERT(HDR_HAS_L2HDR(hdr));
1536 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1538 if (HDR_GET_PSIZE(hdr) != 0) {
1539 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1540 HDR_GET_PSIZE(hdr), 0);
1545 * We use Cityhash for this. It's fast, and has good hash properties without
1546 * requiring any large static buffers.
1549 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1551 return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1554 #define HDR_EMPTY(hdr) \
1555 ((hdr)->b_dva.dva_word[0] == 0 && \
1556 (hdr)->b_dva.dva_word[1] == 0)
1558 #define HDR_EQUAL(spa, dva, birth, hdr) \
1559 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1560 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1561 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1564 buf_discard_identity(arc_buf_hdr_t *hdr)
1566 hdr->b_dva.dva_word[0] = 0;
1567 hdr->b_dva.dva_word[1] = 0;
1571 static arc_buf_hdr_t *
1572 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1574 const dva_t *dva = BP_IDENTITY(bp);
1575 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1576 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1577 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1580 mutex_enter(hash_lock);
1581 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1582 hdr = hdr->b_hash_next) {
1583 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1588 mutex_exit(hash_lock);
1594 * Insert an entry into the hash table. If there is already an element
1595 * equal to elem in the hash table, then the already existing element
1596 * will be returned and the new element will not be inserted.
1597 * Otherwise returns NULL.
1598 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1600 static arc_buf_hdr_t *
1601 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1603 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1604 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1605 arc_buf_hdr_t *fhdr;
1608 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1609 ASSERT(hdr->b_birth != 0);
1610 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1612 if (lockp != NULL) {
1614 mutex_enter(hash_lock);
1616 ASSERT(MUTEX_HELD(hash_lock));
1619 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1620 fhdr = fhdr->b_hash_next, i++) {
1621 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1625 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1626 buf_hash_table.ht_table[idx] = hdr;
1627 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1629 /* collect some hash table performance data */
1631 ARCSTAT_BUMP(arcstat_hash_collisions);
1633 ARCSTAT_BUMP(arcstat_hash_chains);
1635 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1638 ARCSTAT_BUMP(arcstat_hash_elements);
1639 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1645 buf_hash_remove(arc_buf_hdr_t *hdr)
1647 arc_buf_hdr_t *fhdr, **hdrp;
1648 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1650 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1651 ASSERT(HDR_IN_HASH_TABLE(hdr));
1653 hdrp = &buf_hash_table.ht_table[idx];
1654 while ((fhdr = *hdrp) != hdr) {
1655 ASSERT3P(fhdr, !=, NULL);
1656 hdrp = &fhdr->b_hash_next;
1658 *hdrp = hdr->b_hash_next;
1659 hdr->b_hash_next = NULL;
1660 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1662 /* collect some hash table performance data */
1663 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1665 if (buf_hash_table.ht_table[idx] &&
1666 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1667 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1671 * Global data structures and functions for the buf kmem cache.
1673 static kmem_cache_t *hdr_full_cache;
1674 static kmem_cache_t *hdr_l2only_cache;
1675 static kmem_cache_t *buf_cache;
1682 kmem_free(buf_hash_table.ht_table,
1683 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1684 for (i = 0; i < BUF_LOCKS; i++)
1685 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1686 kmem_cache_destroy(hdr_full_cache);
1687 kmem_cache_destroy(hdr_l2only_cache);
1688 kmem_cache_destroy(buf_cache);
1692 * Constructor callback - called when the cache is empty
1693 * and a new buf is requested.
1697 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1699 arc_buf_hdr_t *hdr = vbuf;
1701 bzero(hdr, HDR_FULL_SIZE);
1702 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1703 refcount_create(&hdr->b_l1hdr.b_refcnt);
1704 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1705 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1706 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1713 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1715 arc_buf_hdr_t *hdr = vbuf;
1717 bzero(hdr, HDR_L2ONLY_SIZE);
1718 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1725 buf_cons(void *vbuf, void *unused, int kmflag)
1727 arc_buf_t *buf = vbuf;
1729 bzero(buf, sizeof (arc_buf_t));
1730 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1731 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1737 * Destructor callback - called when a cached buf is
1738 * no longer required.
1742 hdr_full_dest(void *vbuf, void *unused)
1744 arc_buf_hdr_t *hdr = vbuf;
1746 ASSERT(HDR_EMPTY(hdr));
1747 cv_destroy(&hdr->b_l1hdr.b_cv);
1748 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1749 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1750 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1751 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1756 hdr_l2only_dest(void *vbuf, void *unused)
1758 arc_buf_hdr_t *hdr = vbuf;
1760 ASSERT(HDR_EMPTY(hdr));
1761 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1766 buf_dest(void *vbuf, void *unused)
1768 arc_buf_t *buf = vbuf;
1770 mutex_destroy(&buf->b_evict_lock);
1771 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1775 * Reclaim callback -- invoked when memory is low.
1779 hdr_recl(void *unused)
1781 dprintf("hdr_recl called\n");
1783 * umem calls the reclaim func when we destroy the buf cache,
1784 * which is after we do arc_fini().
1787 cv_signal(&arc_reclaim_thread_cv);
1794 uint64_t hsize = 1ULL << 12;
1798 * The hash table is big enough to fill all of physical memory
1799 * with an average block size of zfs_arc_average_blocksize (default 8K).
1800 * By default, the table will take up
1801 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1803 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1806 buf_hash_table.ht_mask = hsize - 1;
1807 buf_hash_table.ht_table =
1808 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1809 if (buf_hash_table.ht_table == NULL) {
1810 ASSERT(hsize > (1ULL << 8));
1815 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1816 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1817 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1818 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1820 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1821 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1823 for (i = 0; i < 256; i++)
1824 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1825 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1827 for (i = 0; i < BUF_LOCKS; i++) {
1828 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1829 NULL, MUTEX_DEFAULT, NULL);
1834 * This is the size that the buf occupies in memory. If the buf is compressed,
1835 * it will correspond to the compressed size. You should use this method of
1836 * getting the buf size unless you explicitly need the logical size.
1839 arc_buf_size(arc_buf_t *buf)
1841 return (ARC_BUF_COMPRESSED(buf) ?
1842 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1846 arc_buf_lsize(arc_buf_t *buf)
1848 return (HDR_GET_LSIZE(buf->b_hdr));
1852 arc_get_compression(arc_buf_t *buf)
1854 return (ARC_BUF_COMPRESSED(buf) ?
1855 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1858 #define ARC_MINTIME (hz>>4) /* 62 ms */
1860 static inline boolean_t
1861 arc_buf_is_shared(arc_buf_t *buf)
1863 boolean_t shared = (buf->b_data != NULL &&
1864 buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1865 abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1866 buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1867 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1868 IMPLY(shared, ARC_BUF_SHARED(buf));
1869 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1872 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1873 * already being shared" requirement prevents us from doing that.
1880 * Free the checksum associated with this header. If there is no checksum, this
1884 arc_cksum_free(arc_buf_hdr_t *hdr)
1886 ASSERT(HDR_HAS_L1HDR(hdr));
1887 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1888 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1889 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1890 hdr->b_l1hdr.b_freeze_cksum = NULL;
1892 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1896 * Return true iff at least one of the bufs on hdr is not compressed.
1899 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1901 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1902 if (!ARC_BUF_COMPRESSED(b)) {
1910 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1911 * matches the checksum that is stored in the hdr. If there is no checksum,
1912 * or if the buf is compressed, this is a no-op.
1915 arc_cksum_verify(arc_buf_t *buf)
1917 arc_buf_hdr_t *hdr = buf->b_hdr;
1920 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1923 if (ARC_BUF_COMPRESSED(buf)) {
1924 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1925 arc_hdr_has_uncompressed_buf(hdr));
1929 ASSERT(HDR_HAS_L1HDR(hdr));
1931 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1932 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1933 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1937 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1938 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1939 panic("buffer modified while frozen!");
1940 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1944 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1946 enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1947 boolean_t valid_cksum;
1949 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1950 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1953 * We rely on the blkptr's checksum to determine if the block
1954 * is valid or not. When compressed arc is enabled, the l2arc
1955 * writes the block to the l2arc just as it appears in the pool.
1956 * This allows us to use the blkptr's checksum to validate the
1957 * data that we just read off of the l2arc without having to store
1958 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1959 * arc is disabled, then the data written to the l2arc is always
1960 * uncompressed and won't match the block as it exists in the main
1961 * pool. When this is the case, we must first compress it if it is
1962 * compressed on the main pool before we can validate the checksum.
1964 if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1965 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1966 uint64_t lsize = HDR_GET_LSIZE(hdr);
1969 abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
1970 csize = zio_compress_data(compress, zio->io_abd,
1971 abd_to_buf(cdata), lsize);
1973 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1974 if (csize < HDR_GET_PSIZE(hdr)) {
1976 * Compressed blocks are always a multiple of the
1977 * smallest ashift in the pool. Ideally, we would
1978 * like to round up the csize to the next
1979 * spa_min_ashift but that value may have changed
1980 * since the block was last written. Instead,
1981 * we rely on the fact that the hdr's psize
1982 * was set to the psize of the block when it was
1983 * last written. We set the csize to that value
1984 * and zero out any part that should not contain
1987 abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1988 csize = HDR_GET_PSIZE(hdr);
1990 zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1994 * Block pointers always store the checksum for the logical data.
1995 * If the block pointer has the gang bit set, then the checksum
1996 * it represents is for the reconstituted data and not for an
1997 * individual gang member. The zio pipeline, however, must be able to
1998 * determine the checksum of each of the gang constituents so it
1999 * treats the checksum comparison differently than what we need
2000 * for l2arc blocks. This prevents us from using the
2001 * zio_checksum_error() interface directly. Instead we must call the
2002 * zio_checksum_error_impl() so that we can ensure the checksum is
2003 * generated using the correct checksum algorithm and accounts for the
2004 * logical I/O size and not just a gang fragment.
2006 valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
2007 BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
2008 zio->io_offset, NULL) == 0);
2009 zio_pop_transforms(zio);
2010 return (valid_cksum);
2014 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
2015 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
2016 * isn't modified later on. If buf is compressed or there is already a checksum
2017 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
2020 arc_cksum_compute(arc_buf_t *buf)
2022 arc_buf_hdr_t *hdr = buf->b_hdr;
2024 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2027 ASSERT(HDR_HAS_L1HDR(hdr));
2029 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
2030 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
2031 ASSERT(arc_hdr_has_uncompressed_buf(hdr));
2032 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2034 } else if (ARC_BUF_COMPRESSED(buf)) {
2035 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2039 ASSERT(!ARC_BUF_COMPRESSED(buf));
2040 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
2042 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
2043 hdr->b_l1hdr.b_freeze_cksum);
2044 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2052 typedef struct procctl {
2060 arc_buf_unwatch(arc_buf_t *buf)
2067 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2068 ctl.prwatch.pr_size = 0;
2069 ctl.prwatch.pr_wflags = 0;
2070 result = write(arc_procfd, &ctl, sizeof (ctl));
2071 ASSERT3U(result, ==, sizeof (ctl));
2078 arc_buf_watch(arc_buf_t *buf)
2085 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2086 ctl.prwatch.pr_size = arc_buf_size(buf);
2087 ctl.prwatch.pr_wflags = WA_WRITE;
2088 result = write(arc_procfd, &ctl, sizeof (ctl));
2089 ASSERT3U(result, ==, sizeof (ctl));
2093 #endif /* illumos */
2095 static arc_buf_contents_t
2096 arc_buf_type(arc_buf_hdr_t *hdr)
2098 arc_buf_contents_t type;
2099 if (HDR_ISTYPE_METADATA(hdr)) {
2100 type = ARC_BUFC_METADATA;
2102 type = ARC_BUFC_DATA;
2104 VERIFY3U(hdr->b_type, ==, type);
2109 arc_is_metadata(arc_buf_t *buf)
2111 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
2115 arc_bufc_to_flags(arc_buf_contents_t type)
2119 /* metadata field is 0 if buffer contains normal data */
2121 case ARC_BUFC_METADATA:
2122 return (ARC_FLAG_BUFC_METADATA);
2126 panic("undefined ARC buffer type!");
2127 return ((uint32_t)-1);
2131 arc_buf_thaw(arc_buf_t *buf)
2133 arc_buf_hdr_t *hdr = buf->b_hdr;
2135 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2136 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2138 arc_cksum_verify(buf);
2141 * Compressed buffers do not manipulate the b_freeze_cksum or
2142 * allocate b_thawed.
2144 if (ARC_BUF_COMPRESSED(buf)) {
2145 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2146 arc_hdr_has_uncompressed_buf(hdr));
2150 ASSERT(HDR_HAS_L1HDR(hdr));
2151 arc_cksum_free(hdr);
2153 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
2155 if (zfs_flags & ZFS_DEBUG_MODIFY) {
2156 if (hdr->b_l1hdr.b_thawed != NULL)
2157 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2158 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
2162 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2165 arc_buf_unwatch(buf);
2170 arc_buf_freeze(arc_buf_t *buf)
2172 arc_buf_hdr_t *hdr = buf->b_hdr;
2173 kmutex_t *hash_lock;
2175 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2178 if (ARC_BUF_COMPRESSED(buf)) {
2179 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2180 arc_hdr_has_uncompressed_buf(hdr));
2184 hash_lock = HDR_LOCK(hdr);
2185 mutex_enter(hash_lock);
2187 ASSERT(HDR_HAS_L1HDR(hdr));
2188 ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2189 hdr->b_l1hdr.b_state == arc_anon);
2190 arc_cksum_compute(buf);
2191 mutex_exit(hash_lock);
2195 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2196 * the following functions should be used to ensure that the flags are
2197 * updated in a thread-safe way. When manipulating the flags either
2198 * the hash_lock must be held or the hdr must be undiscoverable. This
2199 * ensures that we're not racing with any other threads when updating
2203 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2205 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2206 hdr->b_flags |= flags;
2210 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2212 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2213 hdr->b_flags &= ~flags;
2217 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2218 * done in a special way since we have to clear and set bits
2219 * at the same time. Consumers that wish to set the compression bits
2220 * must use this function to ensure that the flags are updated in
2221 * thread-safe manner.
2224 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2226 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2229 * Holes and embedded blocks will always have a psize = 0 so
2230 * we ignore the compression of the blkptr and set the
2231 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2232 * Holes and embedded blocks remain anonymous so we don't
2233 * want to uncompress them. Mark them as uncompressed.
2235 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2236 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2237 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
2238 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2239 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2241 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2242 HDR_SET_COMPRESS(hdr, cmp);
2243 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2244 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2249 * Looks for another buf on the same hdr which has the data decompressed, copies
2250 * from it, and returns true. If no such buf exists, returns false.
2253 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
2255 arc_buf_hdr_t *hdr = buf->b_hdr;
2256 boolean_t copied = B_FALSE;
2258 ASSERT(HDR_HAS_L1HDR(hdr));
2259 ASSERT3P(buf->b_data, !=, NULL);
2260 ASSERT(!ARC_BUF_COMPRESSED(buf));
2262 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
2263 from = from->b_next) {
2264 /* can't use our own data buffer */
2269 if (!ARC_BUF_COMPRESSED(from)) {
2270 bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
2277 * There were no decompressed bufs, so there should not be a
2278 * checksum on the hdr either.
2280 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
2286 * Given a buf that has a data buffer attached to it, this function will
2287 * efficiently fill the buf with data of the specified compression setting from
2288 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2289 * are already sharing a data buf, no copy is performed.
2291 * If the buf is marked as compressed but uncompressed data was requested, this
2292 * will allocate a new data buffer for the buf, remove that flag, and fill the
2293 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2294 * uncompressed data, and (since we haven't added support for it yet) if you
2295 * want compressed data your buf must already be marked as compressed and have
2296 * the correct-sized data buffer.
2299 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
2301 arc_buf_hdr_t *hdr = buf->b_hdr;
2302 boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2303 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2305 ASSERT3P(buf->b_data, !=, NULL);
2306 IMPLY(compressed, hdr_compressed);
2307 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2309 if (hdr_compressed == compressed) {
2310 if (!arc_buf_is_shared(buf)) {
2311 abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
2315 ASSERT(hdr_compressed);
2316 ASSERT(!compressed);
2317 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2320 * If the buf is sharing its data with the hdr, unlink it and
2321 * allocate a new data buffer for the buf.
2323 if (arc_buf_is_shared(buf)) {
2324 ASSERT(ARC_BUF_COMPRESSED(buf));
2326 /* We need to give the buf it's own b_data */
2327 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2329 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2330 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2332 /* Previously overhead was 0; just add new overhead */
2333 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2334 } else if (ARC_BUF_COMPRESSED(buf)) {
2335 /* We need to reallocate the buf's b_data */
2336 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2339 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2341 /* We increased the size of b_data; update overhead */
2342 ARCSTAT_INCR(arcstat_overhead_size,
2343 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2347 * Regardless of the buf's previous compression settings, it
2348 * should not be compressed at the end of this function.
2350 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2353 * Try copying the data from another buf which already has a
2354 * decompressed version. If that's not possible, it's time to
2355 * bite the bullet and decompress the data from the hdr.
2357 if (arc_buf_try_copy_decompressed_data(buf)) {
2358 /* Skip byteswapping and checksumming (already done) */
2359 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
2362 int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2363 hdr->b_l1hdr.b_pabd, buf->b_data,
2364 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2367 * Absent hardware errors or software bugs, this should
2368 * be impossible, but log it anyway so we can debug it.
2372 "hdr %p, compress %d, psize %d, lsize %d",
2373 hdr, HDR_GET_COMPRESS(hdr),
2374 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2375 return (SET_ERROR(EIO));
2380 /* Byteswap the buf's data if necessary */
2381 if (bswap != DMU_BSWAP_NUMFUNCS) {
2382 ASSERT(!HDR_SHARED_DATA(hdr));
2383 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2384 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2387 /* Compute the hdr's checksum if necessary */
2388 arc_cksum_compute(buf);
2394 arc_decompress(arc_buf_t *buf)
2396 return (arc_buf_fill(buf, B_FALSE));
2400 * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2403 arc_hdr_size(arc_buf_hdr_t *hdr)
2407 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2408 HDR_GET_PSIZE(hdr) > 0) {
2409 size = HDR_GET_PSIZE(hdr);
2411 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2412 size = HDR_GET_LSIZE(hdr);
2418 * Increment the amount of evictable space in the arc_state_t's refcount.
2419 * We account for the space used by the hdr and the arc buf individually
2420 * so that we can add and remove them from the refcount individually.
2423 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2425 arc_buf_contents_t type = arc_buf_type(hdr);
2427 ASSERT(HDR_HAS_L1HDR(hdr));
2429 if (GHOST_STATE(state)) {
2430 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2431 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2432 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2433 (void) refcount_add_many(&state->arcs_esize[type],
2434 HDR_GET_LSIZE(hdr), hdr);
2438 ASSERT(!GHOST_STATE(state));
2439 if (hdr->b_l1hdr.b_pabd != NULL) {
2440 (void) refcount_add_many(&state->arcs_esize[type],
2441 arc_hdr_size(hdr), hdr);
2443 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2444 buf = buf->b_next) {
2445 if (arc_buf_is_shared(buf))
2447 (void) refcount_add_many(&state->arcs_esize[type],
2448 arc_buf_size(buf), buf);
2453 * Decrement the amount of evictable space in the arc_state_t's refcount.
2454 * We account for the space used by the hdr and the arc buf individually
2455 * so that we can add and remove them from the refcount individually.
2458 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2460 arc_buf_contents_t type = arc_buf_type(hdr);
2462 ASSERT(HDR_HAS_L1HDR(hdr));
2464 if (GHOST_STATE(state)) {
2465 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2466 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2467 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2468 (void) refcount_remove_many(&state->arcs_esize[type],
2469 HDR_GET_LSIZE(hdr), hdr);
2473 ASSERT(!GHOST_STATE(state));
2474 if (hdr->b_l1hdr.b_pabd != NULL) {
2475 (void) refcount_remove_many(&state->arcs_esize[type],
2476 arc_hdr_size(hdr), hdr);
2478 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2479 buf = buf->b_next) {
2480 if (arc_buf_is_shared(buf))
2482 (void) refcount_remove_many(&state->arcs_esize[type],
2483 arc_buf_size(buf), buf);
2488 * Add a reference to this hdr indicating that someone is actively
2489 * referencing that memory. When the refcount transitions from 0 to 1,
2490 * we remove it from the respective arc_state_t list to indicate that
2491 * it is not evictable.
2494 add_reference(arc_buf_hdr_t *hdr, void *tag)
2496 ASSERT(HDR_HAS_L1HDR(hdr));
2497 if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2498 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2499 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2500 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2503 arc_state_t *state = hdr->b_l1hdr.b_state;
2505 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2506 (state != arc_anon)) {
2507 /* We don't use the L2-only state list. */
2508 if (state != arc_l2c_only) {
2509 multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2511 arc_evictable_space_decrement(hdr, state);
2513 /* remove the prefetch flag if we get a reference */
2514 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2519 * Remove a reference from this hdr. When the reference transitions from
2520 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2521 * list making it eligible for eviction.
2524 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2527 arc_state_t *state = hdr->b_l1hdr.b_state;
2529 ASSERT(HDR_HAS_L1HDR(hdr));
2530 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2531 ASSERT(!GHOST_STATE(state));
2534 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2535 * check to prevent usage of the arc_l2c_only list.
2537 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2538 (state != arc_anon)) {
2539 multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2540 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2541 arc_evictable_space_increment(hdr, state);
2547 * Move the supplied buffer to the indicated state. The hash lock
2548 * for the buffer must be held by the caller.
2551 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2552 kmutex_t *hash_lock)
2554 arc_state_t *old_state;
2557 boolean_t update_old, update_new;
2558 arc_buf_contents_t buftype = arc_buf_type(hdr);
2561 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2562 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2563 * L1 hdr doesn't always exist when we change state to arc_anon before
2564 * destroying a header, in which case reallocating to add the L1 hdr is
2567 if (HDR_HAS_L1HDR(hdr)) {
2568 old_state = hdr->b_l1hdr.b_state;
2569 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2570 bufcnt = hdr->b_l1hdr.b_bufcnt;
2571 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
2573 old_state = arc_l2c_only;
2576 update_old = B_FALSE;
2578 update_new = update_old;
2580 ASSERT(MUTEX_HELD(hash_lock));
2581 ASSERT3P(new_state, !=, old_state);
2582 ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2583 ASSERT(old_state != arc_anon || bufcnt <= 1);
2586 * If this buffer is evictable, transfer it from the
2587 * old state list to the new state list.
2590 if (old_state != arc_anon && old_state != arc_l2c_only) {
2591 ASSERT(HDR_HAS_L1HDR(hdr));
2592 multilist_remove(old_state->arcs_list[buftype], hdr);
2594 if (GHOST_STATE(old_state)) {
2596 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2597 update_old = B_TRUE;
2599 arc_evictable_space_decrement(hdr, old_state);
2601 if (new_state != arc_anon && new_state != arc_l2c_only) {
2604 * An L1 header always exists here, since if we're
2605 * moving to some L1-cached state (i.e. not l2c_only or
2606 * anonymous), we realloc the header to add an L1hdr
2609 ASSERT(HDR_HAS_L1HDR(hdr));
2610 multilist_insert(new_state->arcs_list[buftype], hdr);
2612 if (GHOST_STATE(new_state)) {
2614 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2615 update_new = B_TRUE;
2617 arc_evictable_space_increment(hdr, new_state);
2621 ASSERT(!HDR_EMPTY(hdr));
2622 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2623 buf_hash_remove(hdr);
2625 /* adjust state sizes (ignore arc_l2c_only) */
2627 if (update_new && new_state != arc_l2c_only) {
2628 ASSERT(HDR_HAS_L1HDR(hdr));
2629 if (GHOST_STATE(new_state)) {
2633 * When moving a header to a ghost state, we first
2634 * remove all arc buffers. Thus, we'll have a
2635 * bufcnt of zero, and no arc buffer to use for
2636 * the reference. As a result, we use the arc
2637 * header pointer for the reference.
2639 (void) refcount_add_many(&new_state->arcs_size,
2640 HDR_GET_LSIZE(hdr), hdr);
2641 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2643 uint32_t buffers = 0;
2646 * Each individual buffer holds a unique reference,
2647 * thus we must remove each of these references one
2650 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2651 buf = buf->b_next) {
2652 ASSERT3U(bufcnt, !=, 0);
2656 * When the arc_buf_t is sharing the data
2657 * block with the hdr, the owner of the
2658 * reference belongs to the hdr. Only
2659 * add to the refcount if the arc_buf_t is
2662 if (arc_buf_is_shared(buf))
2665 (void) refcount_add_many(&new_state->arcs_size,
2666 arc_buf_size(buf), buf);
2668 ASSERT3U(bufcnt, ==, buffers);
2670 if (hdr->b_l1hdr.b_pabd != NULL) {
2671 (void) refcount_add_many(&new_state->arcs_size,
2672 arc_hdr_size(hdr), hdr);
2674 ASSERT(GHOST_STATE(old_state));
2679 if (update_old && old_state != arc_l2c_only) {
2680 ASSERT(HDR_HAS_L1HDR(hdr));
2681 if (GHOST_STATE(old_state)) {
2683 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2686 * When moving a header off of a ghost state,
2687 * the header will not contain any arc buffers.
2688 * We use the arc header pointer for the reference
2689 * which is exactly what we did when we put the
2690 * header on the ghost state.
2693 (void) refcount_remove_many(&old_state->arcs_size,
2694 HDR_GET_LSIZE(hdr), hdr);
2696 uint32_t buffers = 0;
2699 * Each individual buffer holds a unique reference,
2700 * thus we must remove each of these references one
2703 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2704 buf = buf->b_next) {
2705 ASSERT3U(bufcnt, !=, 0);
2709 * When the arc_buf_t is sharing the data
2710 * block with the hdr, the owner of the
2711 * reference belongs to the hdr. Only
2712 * add to the refcount if the arc_buf_t is
2715 if (arc_buf_is_shared(buf))
2718 (void) refcount_remove_many(
2719 &old_state->arcs_size, arc_buf_size(buf),
2722 ASSERT3U(bufcnt, ==, buffers);
2723 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2724 (void) refcount_remove_many(
2725 &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2729 if (HDR_HAS_L1HDR(hdr))
2730 hdr->b_l1hdr.b_state = new_state;
2733 * L2 headers should never be on the L2 state list since they don't
2734 * have L1 headers allocated.
2736 ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2737 multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2741 arc_space_consume(uint64_t space, arc_space_type_t type)
2743 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2746 case ARC_SPACE_DATA:
2747 aggsum_add(&astat_data_size, space);
2749 case ARC_SPACE_META:
2750 aggsum_add(&astat_metadata_size, space);
2752 case ARC_SPACE_BONUS:
2753 aggsum_add(&astat_bonus_size, space);
2755 case ARC_SPACE_DNODE:
2756 aggsum_add(&astat_dnode_size, space);
2758 case ARC_SPACE_DBUF:
2759 aggsum_add(&astat_dbuf_size, space);
2761 case ARC_SPACE_HDRS:
2762 aggsum_add(&astat_hdr_size, space);
2764 case ARC_SPACE_L2HDRS:
2765 aggsum_add(&astat_l2_hdr_size, space);
2769 if (type != ARC_SPACE_DATA)
2770 aggsum_add(&arc_meta_used, space);
2772 aggsum_add(&arc_size, space);
2776 arc_space_return(uint64_t space, arc_space_type_t type)
2778 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2781 case ARC_SPACE_DATA:
2782 aggsum_add(&astat_data_size, -space);
2784 case ARC_SPACE_META:
2785 aggsum_add(&astat_metadata_size, -space);
2787 case ARC_SPACE_BONUS:
2788 aggsum_add(&astat_bonus_size, -space);
2790 case ARC_SPACE_DNODE:
2791 aggsum_add(&astat_dnode_size, -space);
2793 case ARC_SPACE_DBUF:
2794 aggsum_add(&astat_dbuf_size, -space);
2796 case ARC_SPACE_HDRS:
2797 aggsum_add(&astat_hdr_size, -space);
2799 case ARC_SPACE_L2HDRS:
2800 aggsum_add(&astat_l2_hdr_size, -space);
2804 if (type != ARC_SPACE_DATA) {
2805 ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
2807 * We use the upper bound here rather than the precise value
2808 * because the arc_meta_max value doesn't need to be
2809 * precise. It's only consumed by humans via arcstats.
2811 if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
2812 arc_meta_max = aggsum_upper_bound(&arc_meta_used);
2813 aggsum_add(&arc_meta_used, -space);
2816 ASSERT(aggsum_compare(&arc_size, space) >= 0);
2817 aggsum_add(&arc_size, -space);
2821 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2822 * with the hdr's b_pabd.
2825 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2828 * The criteria for sharing a hdr's data are:
2829 * 1. the hdr's compression matches the buf's compression
2830 * 2. the hdr doesn't need to be byteswapped
2831 * 3. the hdr isn't already being shared
2832 * 4. the buf is either compressed or it is the last buf in the hdr list
2834 * Criterion #4 maintains the invariant that shared uncompressed
2835 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2836 * might ask, "if a compressed buf is allocated first, won't that be the
2837 * last thing in the list?", but in that case it's impossible to create
2838 * a shared uncompressed buf anyway (because the hdr must be compressed
2839 * to have the compressed buf). You might also think that #3 is
2840 * sufficient to make this guarantee, however it's possible
2841 * (specifically in the rare L2ARC write race mentioned in
2842 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2843 * is sharable, but wasn't at the time of its allocation. Rather than
2844 * allow a new shared uncompressed buf to be created and then shuffle
2845 * the list around to make it the last element, this simply disallows
2846 * sharing if the new buf isn't the first to be added.
2848 ASSERT3P(buf->b_hdr, ==, hdr);
2849 boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2850 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2851 return (buf_compressed == hdr_compressed &&
2852 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2853 !HDR_SHARED_DATA(hdr) &&
2854 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2858 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2859 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2860 * copy was made successfully, or an error code otherwise.
2863 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2864 boolean_t fill, arc_buf_t **ret)
2868 ASSERT(HDR_HAS_L1HDR(hdr));
2869 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2870 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2871 hdr->b_type == ARC_BUFC_METADATA);
2872 ASSERT3P(ret, !=, NULL);
2873 ASSERT3P(*ret, ==, NULL);
2875 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2878 buf->b_next = hdr->b_l1hdr.b_buf;
2881 add_reference(hdr, tag);
2884 * We're about to change the hdr's b_flags. We must either
2885 * hold the hash_lock or be undiscoverable.
2887 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2890 * Only honor requests for compressed bufs if the hdr is actually
2893 if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2894 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2897 * If the hdr's data can be shared then we share the data buffer and
2898 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2899 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2900 * buffer to store the buf's data.
2902 * There are two additional restrictions here because we're sharing
2903 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2904 * actively involved in an L2ARC write, because if this buf is used by
2905 * an arc_write() then the hdr's data buffer will be released when the
2906 * write completes, even though the L2ARC write might still be using it.
2907 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2908 * need to be ABD-aware.
2910 boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2911 abd_is_linear(hdr->b_l1hdr.b_pabd);
2913 /* Set up b_data and sharing */
2915 buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2916 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2917 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2920 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2921 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2923 VERIFY3P(buf->b_data, !=, NULL);
2925 hdr->b_l1hdr.b_buf = buf;
2926 hdr->b_l1hdr.b_bufcnt += 1;
2929 * If the user wants the data from the hdr, we need to either copy or
2930 * decompress the data.
2933 return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
2939 static char *arc_onloan_tag = "onloan";
2942 arc_loaned_bytes_update(int64_t delta)
2944 atomic_add_64(&arc_loaned_bytes, delta);
2946 /* assert that it did not wrap around */
2947 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2951 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2952 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2953 * buffers must be returned to the arc before they can be used by the DMU or
2957 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2959 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2960 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2962 arc_loaned_bytes_update(arc_buf_size(buf));
2968 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2969 enum zio_compress compression_type)
2971 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2972 psize, lsize, compression_type);
2974 arc_loaned_bytes_update(arc_buf_size(buf));
2981 * Return a loaned arc buffer to the arc.
2984 arc_return_buf(arc_buf_t *buf, void *tag)
2986 arc_buf_hdr_t *hdr = buf->b_hdr;
2988 ASSERT3P(buf->b_data, !=, NULL);
2989 ASSERT(HDR_HAS_L1HDR(hdr));
2990 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2991 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2993 arc_loaned_bytes_update(-arc_buf_size(buf));
2996 /* Detach an arc_buf from a dbuf (tag) */
2998 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
3000 arc_buf_hdr_t *hdr = buf->b_hdr;
3002 ASSERT3P(buf->b_data, !=, NULL);
3003 ASSERT(HDR_HAS_L1HDR(hdr));
3004 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
3005 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
3007 arc_loaned_bytes_update(arc_buf_size(buf));
3011 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
3013 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
3016 df->l2df_size = size;
3017 df->l2df_type = type;
3018 mutex_enter(&l2arc_free_on_write_mtx);
3019 list_insert_head(l2arc_free_on_write, df);
3020 mutex_exit(&l2arc_free_on_write_mtx);
3024 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
3026 arc_state_t *state = hdr->b_l1hdr.b_state;
3027 arc_buf_contents_t type = arc_buf_type(hdr);
3028 uint64_t size = arc_hdr_size(hdr);
3030 /* protected by hash lock, if in the hash table */
3031 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3032 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3033 ASSERT(state != arc_anon && state != arc_l2c_only);
3035 (void) refcount_remove_many(&state->arcs_esize[type],
3038 (void) refcount_remove_many(&state->arcs_size, size, hdr);
3039 if (type == ARC_BUFC_METADATA) {
3040 arc_space_return(size, ARC_SPACE_META);
3042 ASSERT(type == ARC_BUFC_DATA);
3043 arc_space_return(size, ARC_SPACE_DATA);
3046 l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
3050 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
3051 * data buffer, we transfer the refcount ownership to the hdr and update
3052 * the appropriate kstats.
3055 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3057 arc_state_t *state = hdr->b_l1hdr.b_state;
3059 ASSERT(arc_can_share(hdr, buf));
3060 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3061 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3064 * Start sharing the data buffer. We transfer the
3065 * refcount ownership to the hdr since it always owns
3066 * the refcount whenever an arc_buf_t is shared.
3068 refcount_transfer_ownership(&state->arcs_size, buf, hdr);
3069 hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3070 abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3071 HDR_ISTYPE_METADATA(hdr));
3072 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3073 buf->b_flags |= ARC_BUF_FLAG_SHARED;
3076 * Since we've transferred ownership to the hdr we need
3077 * to increment its compressed and uncompressed kstats and
3078 * decrement the overhead size.
3080 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3081 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3082 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3086 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3088 arc_state_t *state = hdr->b_l1hdr.b_state;
3090 ASSERT(arc_buf_is_shared(buf));
3091 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3092 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3095 * We are no longer sharing this buffer so we need
3096 * to transfer its ownership to the rightful owner.
3098 refcount_transfer_ownership(&state->arcs_size, hdr, buf);
3099 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3100 abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3101 abd_put(hdr->b_l1hdr.b_pabd);
3102 hdr->b_l1hdr.b_pabd = NULL;
3103 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3106 * Since the buffer is no longer shared between
3107 * the arc buf and the hdr, count it as overhead.
3109 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3110 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3111 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3115 * Remove an arc_buf_t from the hdr's buf list and return the last
3116 * arc_buf_t on the list. If no buffers remain on the list then return
3120 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3122 ASSERT(HDR_HAS_L1HDR(hdr));
3123 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3125 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3126 arc_buf_t *lastbuf = NULL;
3129 * Remove the buf from the hdr list and locate the last
3130 * remaining buffer on the list.
3132 while (*bufp != NULL) {
3134 *bufp = buf->b_next;
3137 * If we've removed a buffer in the middle of
3138 * the list then update the lastbuf and update
3141 if (*bufp != NULL) {
3143 bufp = &(*bufp)->b_next;
3147 ASSERT3P(lastbuf, !=, buf);
3148 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
3149 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
3150 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3156 * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
3160 arc_buf_destroy_impl(arc_buf_t *buf)
3162 arc_buf_hdr_t *hdr = buf->b_hdr;
3165 * Free up the data associated with the buf but only if we're not
3166 * sharing this with the hdr. If we are sharing it with the hdr, the
3167 * hdr is responsible for doing the free.
3169 if (buf->b_data != NULL) {
3171 * We're about to change the hdr's b_flags. We must either
3172 * hold the hash_lock or be undiscoverable.
3174 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3176 arc_cksum_verify(buf);
3178 arc_buf_unwatch(buf);
3181 if (arc_buf_is_shared(buf)) {
3182 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3184 uint64_t size = arc_buf_size(buf);
3185 arc_free_data_buf(hdr, buf->b_data, size, buf);
3186 ARCSTAT_INCR(arcstat_overhead_size, -size);
3190 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3191 hdr->b_l1hdr.b_bufcnt -= 1;
3194 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3196 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3198 * If the current arc_buf_t is sharing its data buffer with the
3199 * hdr, then reassign the hdr's b_pabd to share it with the new
3200 * buffer at the end of the list. The shared buffer is always
3201 * the last one on the hdr's buffer list.
3203 * There is an equivalent case for compressed bufs, but since
3204 * they aren't guaranteed to be the last buf in the list and
3205 * that is an exceedingly rare case, we just allow that space be
3206 * wasted temporarily.
3208 if (lastbuf != NULL) {
3209 /* Only one buf can be shared at once */
3210 VERIFY(!arc_buf_is_shared(lastbuf));
3211 /* hdr is uncompressed so can't have compressed buf */
3212 VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3214 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3215 arc_hdr_free_pabd(hdr);
3218 * We must setup a new shared block between the
3219 * last buffer and the hdr. The data would have
3220 * been allocated by the arc buf so we need to transfer
3221 * ownership to the hdr since it's now being shared.
3223 arc_share_buf(hdr, lastbuf);
3225 } else if (HDR_SHARED_DATA(hdr)) {
3227 * Uncompressed shared buffers are always at the end
3228 * of the list. Compressed buffers don't have the
3229 * same requirements. This makes it hard to
3230 * simply assert that the lastbuf is shared so
3231 * we rely on the hdr's compression flags to determine
3232 * if we have a compressed, shared buffer.
3234 ASSERT3P(lastbuf, !=, NULL);
3235 ASSERT(arc_buf_is_shared(lastbuf) ||
3236 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
3240 * Free the checksum if we're removing the last uncompressed buf from
3243 if (!arc_hdr_has_uncompressed_buf(hdr)) {
3244 arc_cksum_free(hdr);
3247 /* clean up the buf */
3249 kmem_cache_free(buf_cache, buf);
3253 arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
3255 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3256 ASSERT(HDR_HAS_L1HDR(hdr));
3257 ASSERT(!HDR_SHARED_DATA(hdr));
3259 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3260 hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
3261 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3262 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3264 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3265 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3269 arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
3271 ASSERT(HDR_HAS_L1HDR(hdr));
3272 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3275 * If the hdr is currently being written to the l2arc then
3276 * we defer freeing the data by adding it to the l2arc_free_on_write
3277 * list. The l2arc will free the data once it's finished
3278 * writing it to the l2arc device.
3280 if (HDR_L2_WRITING(hdr)) {
3281 arc_hdr_free_on_write(hdr);
3282 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3284 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
3285 arc_hdr_size(hdr), hdr);
3287 hdr->b_l1hdr.b_pabd = NULL;
3288 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3290 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3291 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3294 static arc_buf_hdr_t *
3295 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3296 enum zio_compress compression_type, arc_buf_contents_t type)
3300 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3302 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3303 ASSERT(HDR_EMPTY(hdr));
3304 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3305 ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3306 HDR_SET_PSIZE(hdr, psize);
3307 HDR_SET_LSIZE(hdr, lsize);
3311 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3312 arc_hdr_set_compress(hdr, compression_type);
3314 hdr->b_l1hdr.b_state = arc_anon;
3315 hdr->b_l1hdr.b_arc_access = 0;
3316 hdr->b_l1hdr.b_bufcnt = 0;
3317 hdr->b_l1hdr.b_buf = NULL;
3320 * Allocate the hdr's buffer. This will contain either
3321 * the compressed or uncompressed data depending on the block
3322 * it references and compressed arc enablement.
3324 arc_hdr_alloc_pabd(hdr);
3325 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3331 * Transition between the two allocation states for the arc_buf_hdr struct.
3332 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3333 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3334 * version is used when a cache buffer is only in the L2ARC in order to reduce
3337 static arc_buf_hdr_t *
3338 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3340 ASSERT(HDR_HAS_L2HDR(hdr));
3342 arc_buf_hdr_t *nhdr;
3343 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3345 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3346 (old == hdr_l2only_cache && new == hdr_full_cache));
3348 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3350 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3351 buf_hash_remove(hdr);
3353 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3355 if (new == hdr_full_cache) {
3356 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3358 * arc_access and arc_change_state need to be aware that a
3359 * header has just come out of L2ARC, so we set its state to
3360 * l2c_only even though it's about to change.
3362 nhdr->b_l1hdr.b_state = arc_l2c_only;
3364 /* Verify previous threads set to NULL before freeing */
3365 ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
3367 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3368 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3369 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3372 * If we've reached here, We must have been called from
3373 * arc_evict_hdr(), as such we should have already been
3374 * removed from any ghost list we were previously on
3375 * (which protects us from racing with arc_evict_state),
3376 * thus no locking is needed during this check.
3378 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3381 * A buffer must not be moved into the arc_l2c_only
3382 * state if it's not finished being written out to the
3383 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3384 * might try to be accessed, even though it was removed.
3386 VERIFY(!HDR_L2_WRITING(hdr));
3387 VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3390 if (hdr->b_l1hdr.b_thawed != NULL) {
3391 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3392 hdr->b_l1hdr.b_thawed = NULL;
3396 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3399 * The header has been reallocated so we need to re-insert it into any
3402 (void) buf_hash_insert(nhdr, NULL);
3404 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3406 mutex_enter(&dev->l2ad_mtx);
3409 * We must place the realloc'ed header back into the list at
3410 * the same spot. Otherwise, if it's placed earlier in the list,
3411 * l2arc_write_buffers() could find it during the function's
3412 * write phase, and try to write it out to the l2arc.
3414 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3415 list_remove(&dev->l2ad_buflist, hdr);
3417 mutex_exit(&dev->l2ad_mtx);
3420 * Since we're using the pointer address as the tag when
3421 * incrementing and decrementing the l2ad_alloc refcount, we
3422 * must remove the old pointer (that we're about to destroy) and
3423 * add the new pointer to the refcount. Otherwise we'd remove
3424 * the wrong pointer address when calling arc_hdr_destroy() later.
3427 (void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3428 (void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3430 buf_discard_identity(hdr);
3431 kmem_cache_free(old, hdr);
3437 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3438 * The buf is returned thawed since we expect the consumer to modify it.
3441 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3443 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3444 ZIO_COMPRESS_OFF, type);
3445 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3447 arc_buf_t *buf = NULL;
3448 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3455 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3456 * for bufs containing metadata.
3459 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3460 enum zio_compress compression_type)
3462 ASSERT3U(lsize, >, 0);
3463 ASSERT3U(lsize, >=, psize);
3464 ASSERT(compression_type > ZIO_COMPRESS_OFF);
3465 ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3467 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3468 compression_type, ARC_BUFC_DATA);
3469 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3471 arc_buf_t *buf = NULL;
3472 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3474 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3476 if (!arc_buf_is_shared(buf)) {
3478 * To ensure that the hdr has the correct data in it if we call
3479 * arc_decompress() on this buf before it's been written to
3480 * disk, it's easiest if we just set up sharing between the
3483 ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3484 arc_hdr_free_pabd(hdr);
3485 arc_share_buf(hdr, buf);
3492 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3494 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3495 l2arc_dev_t *dev = l2hdr->b_dev;
3496 uint64_t psize = arc_hdr_size(hdr);
3498 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3499 ASSERT(HDR_HAS_L2HDR(hdr));
3501 list_remove(&dev->l2ad_buflist, hdr);
3503 ARCSTAT_INCR(arcstat_l2_psize, -psize);
3504 ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3506 vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3508 (void) refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3509 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3513 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3515 if (HDR_HAS_L1HDR(hdr)) {
3516 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3517 hdr->b_l1hdr.b_bufcnt > 0);
3518 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3519 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3521 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3522 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3524 if (!HDR_EMPTY(hdr))
3525 buf_discard_identity(hdr);
3527 if (HDR_HAS_L2HDR(hdr)) {
3528 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3529 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3532 mutex_enter(&dev->l2ad_mtx);
3535 * Even though we checked this conditional above, we
3536 * need to check this again now that we have the
3537 * l2ad_mtx. This is because we could be racing with
3538 * another thread calling l2arc_evict() which might have
3539 * destroyed this header's L2 portion as we were waiting
3540 * to acquire the l2ad_mtx. If that happens, we don't
3541 * want to re-destroy the header's L2 portion.
3543 if (HDR_HAS_L2HDR(hdr)) {
3545 arc_hdr_l2hdr_destroy(hdr);
3549 mutex_exit(&dev->l2ad_mtx);
3552 if (HDR_HAS_L1HDR(hdr)) {
3553 arc_cksum_free(hdr);
3555 while (hdr->b_l1hdr.b_buf != NULL)
3556 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3559 if (hdr->b_l1hdr.b_thawed != NULL) {
3560 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3561 hdr->b_l1hdr.b_thawed = NULL;
3565 if (hdr->b_l1hdr.b_pabd != NULL) {
3566 arc_hdr_free_pabd(hdr);
3570 ASSERT3P(hdr->b_hash_next, ==, NULL);
3571 if (HDR_HAS_L1HDR(hdr)) {
3572 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3573 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3574 kmem_cache_free(hdr_full_cache, hdr);
3576 kmem_cache_free(hdr_l2only_cache, hdr);
3581 arc_buf_destroy(arc_buf_t *buf, void* tag)
3583 arc_buf_hdr_t *hdr = buf->b_hdr;
3584 kmutex_t *hash_lock = HDR_LOCK(hdr);
3586 if (hdr->b_l1hdr.b_state == arc_anon) {
3587 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3588 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3589 VERIFY0(remove_reference(hdr, NULL, tag));
3590 arc_hdr_destroy(hdr);
3594 mutex_enter(hash_lock);
3595 ASSERT3P(hdr, ==, buf->b_hdr);
3596 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3597 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3598 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3599 ASSERT3P(buf->b_data, !=, NULL);
3601 (void) remove_reference(hdr, hash_lock, tag);
3602 arc_buf_destroy_impl(buf);
3603 mutex_exit(hash_lock);
3607 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3608 * state of the header is dependent on its state prior to entering this
3609 * function. The following transitions are possible:
3611 * - arc_mru -> arc_mru_ghost
3612 * - arc_mfu -> arc_mfu_ghost
3613 * - arc_mru_ghost -> arc_l2c_only
3614 * - arc_mru_ghost -> deleted
3615 * - arc_mfu_ghost -> arc_l2c_only
3616 * - arc_mfu_ghost -> deleted
3619 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3621 arc_state_t *evicted_state, *state;
3622 int64_t bytes_evicted = 0;
3623 int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3624 zfs_arc_min_prescient_prefetch_ms : zfs_arc_min_prefetch_ms;
3626 ASSERT(MUTEX_HELD(hash_lock));
3627 ASSERT(HDR_HAS_L1HDR(hdr));
3629 state = hdr->b_l1hdr.b_state;
3630 if (GHOST_STATE(state)) {
3631 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3632 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3635 * l2arc_write_buffers() relies on a header's L1 portion
3636 * (i.e. its b_pabd field) during it's write phase.
3637 * Thus, we cannot push a header onto the arc_l2c_only
3638 * state (removing it's L1 piece) until the header is
3639 * done being written to the l2arc.
3641 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3642 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3643 return (bytes_evicted);
3646 ARCSTAT_BUMP(arcstat_deleted);
3647 bytes_evicted += HDR_GET_LSIZE(hdr);
3649 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3651 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3652 if (HDR_HAS_L2HDR(hdr)) {
3654 * This buffer is cached on the 2nd Level ARC;
3655 * don't destroy the header.
3657 arc_change_state(arc_l2c_only, hdr, hash_lock);
3659 * dropping from L1+L2 cached to L2-only,
3660 * realloc to remove the L1 header.
3662 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3665 arc_change_state(arc_anon, hdr, hash_lock);
3666 arc_hdr_destroy(hdr);
3668 return (bytes_evicted);
3671 ASSERT(state == arc_mru || state == arc_mfu);
3672 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3674 /* prefetch buffers have a minimum lifespan */
3675 if (HDR_IO_IN_PROGRESS(hdr) ||
3676 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3677 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access < min_lifetime * hz)) {
3678 ARCSTAT_BUMP(arcstat_evict_skip);
3679 return (bytes_evicted);
3682 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3683 while (hdr->b_l1hdr.b_buf) {
3684 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3685 if (!mutex_tryenter(&buf->b_evict_lock)) {
3686 ARCSTAT_BUMP(arcstat_mutex_miss);
3689 if (buf->b_data != NULL)
3690 bytes_evicted += HDR_GET_LSIZE(hdr);
3691 mutex_exit(&buf->b_evict_lock);
3692 arc_buf_destroy_impl(buf);
3695 if (HDR_HAS_L2HDR(hdr)) {
3696 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3698 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3699 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3700 HDR_GET_LSIZE(hdr));
3702 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3703 HDR_GET_LSIZE(hdr));
3707 if (hdr->b_l1hdr.b_bufcnt == 0) {
3708 arc_cksum_free(hdr);
3710 bytes_evicted += arc_hdr_size(hdr);
3713 * If this hdr is being evicted and has a compressed
3714 * buffer then we discard it here before we change states.
3715 * This ensures that the accounting is updated correctly
3716 * in arc_free_data_impl().
3718 arc_hdr_free_pabd(hdr);
3720 arc_change_state(evicted_state, hdr, hash_lock);
3721 ASSERT(HDR_IN_HASH_TABLE(hdr));
3722 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3723 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3726 return (bytes_evicted);
3730 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3731 uint64_t spa, int64_t bytes)
3733 multilist_sublist_t *mls;
3734 uint64_t bytes_evicted = 0;
3736 kmutex_t *hash_lock;
3737 int evict_count = 0;
3739 ASSERT3P(marker, !=, NULL);
3740 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3742 mls = multilist_sublist_lock(ml, idx);
3744 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3745 hdr = multilist_sublist_prev(mls, marker)) {
3746 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3747 (evict_count >= zfs_arc_evict_batch_limit))
3751 * To keep our iteration location, move the marker
3752 * forward. Since we're not holding hdr's hash lock, we
3753 * must be very careful and not remove 'hdr' from the
3754 * sublist. Otherwise, other consumers might mistake the
3755 * 'hdr' as not being on a sublist when they call the
3756 * multilist_link_active() function (they all rely on
3757 * the hash lock protecting concurrent insertions and
3758 * removals). multilist_sublist_move_forward() was
3759 * specifically implemented to ensure this is the case
3760 * (only 'marker' will be removed and re-inserted).
3762 multilist_sublist_move_forward(mls, marker);
3765 * The only case where the b_spa field should ever be
3766 * zero, is the marker headers inserted by
3767 * arc_evict_state(). It's possible for multiple threads
3768 * to be calling arc_evict_state() concurrently (e.g.
3769 * dsl_pool_close() and zio_inject_fault()), so we must
3770 * skip any markers we see from these other threads.
3772 if (hdr->b_spa == 0)
3775 /* we're only interested in evicting buffers of a certain spa */
3776 if (spa != 0 && hdr->b_spa != spa) {
3777 ARCSTAT_BUMP(arcstat_evict_skip);
3781 hash_lock = HDR_LOCK(hdr);
3784 * We aren't calling this function from any code path
3785 * that would already be holding a hash lock, so we're
3786 * asserting on this assumption to be defensive in case
3787 * this ever changes. Without this check, it would be
3788 * possible to incorrectly increment arcstat_mutex_miss
3789 * below (e.g. if the code changed such that we called
3790 * this function with a hash lock held).
3792 ASSERT(!MUTEX_HELD(hash_lock));
3794 if (mutex_tryenter(hash_lock)) {
3795 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3796 mutex_exit(hash_lock);
3798 bytes_evicted += evicted;
3801 * If evicted is zero, arc_evict_hdr() must have
3802 * decided to skip this header, don't increment
3803 * evict_count in this case.
3809 * If arc_size isn't overflowing, signal any
3810 * threads that might happen to be waiting.
3812 * For each header evicted, we wake up a single
3813 * thread. If we used cv_broadcast, we could
3814 * wake up "too many" threads causing arc_size
3815 * to significantly overflow arc_c; since
3816 * arc_get_data_impl() doesn't check for overflow
3817 * when it's woken up (it doesn't because it's
3818 * possible for the ARC to be overflowing while
3819 * full of un-evictable buffers, and the
3820 * function should proceed in this case).
3822 * If threads are left sleeping, due to not
3823 * using cv_broadcast, they will be woken up
3824 * just before arc_reclaim_thread() sleeps.
3826 mutex_enter(&arc_reclaim_lock);
3827 if (!arc_is_overflowing())
3828 cv_signal(&arc_reclaim_waiters_cv);
3829 mutex_exit(&arc_reclaim_lock);
3831 ARCSTAT_BUMP(arcstat_mutex_miss);
3835 multilist_sublist_unlock(mls);
3837 return (bytes_evicted);
3841 * Evict buffers from the given arc state, until we've removed the
3842 * specified number of bytes. Move the removed buffers to the
3843 * appropriate evict state.
3845 * This function makes a "best effort". It skips over any buffers
3846 * it can't get a hash_lock on, and so, may not catch all candidates.
3847 * It may also return without evicting as much space as requested.
3849 * If bytes is specified using the special value ARC_EVICT_ALL, this
3850 * will evict all available (i.e. unlocked and evictable) buffers from
3851 * the given arc state; which is used by arc_flush().
3854 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3855 arc_buf_contents_t type)
3857 uint64_t total_evicted = 0;
3858 multilist_t *ml = state->arcs_list[type];
3860 arc_buf_hdr_t **markers;
3862 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3864 num_sublists = multilist_get_num_sublists(ml);
3867 * If we've tried to evict from each sublist, made some
3868 * progress, but still have not hit the target number of bytes
3869 * to evict, we want to keep trying. The markers allow us to
3870 * pick up where we left off for each individual sublist, rather
3871 * than starting from the tail each time.
3873 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3874 for (int i = 0; i < num_sublists; i++) {
3875 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3878 * A b_spa of 0 is used to indicate that this header is
3879 * a marker. This fact is used in arc_adjust_type() and
3880 * arc_evict_state_impl().
3882 markers[i]->b_spa = 0;
3884 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3885 multilist_sublist_insert_tail(mls, markers[i]);
3886 multilist_sublist_unlock(mls);
3890 * While we haven't hit our target number of bytes to evict, or
3891 * we're evicting all available buffers.
3893 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3894 int sublist_idx = multilist_get_random_index(ml);
3895 uint64_t scan_evicted = 0;
3898 * Try to reduce pinned dnodes with a floor of arc_dnode_limit.
3899 * Request that 10% of the LRUs be scanned by the superblock
3902 if (type == ARC_BUFC_DATA && aggsum_compare(&astat_dnode_size,
3903 arc_dnode_limit) > 0) {
3904 arc_prune_async((aggsum_upper_bound(&astat_dnode_size) -
3905 arc_dnode_limit) / sizeof (dnode_t) /
3906 zfs_arc_dnode_reduce_percent);
3910 * Start eviction using a randomly selected sublist,
3911 * this is to try and evenly balance eviction across all
3912 * sublists. Always starting at the same sublist
3913 * (e.g. index 0) would cause evictions to favor certain
3914 * sublists over others.
3916 for (int i = 0; i < num_sublists; i++) {
3917 uint64_t bytes_remaining;
3918 uint64_t bytes_evicted;
3920 if (bytes == ARC_EVICT_ALL)
3921 bytes_remaining = ARC_EVICT_ALL;
3922 else if (total_evicted < bytes)
3923 bytes_remaining = bytes - total_evicted;
3927 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3928 markers[sublist_idx], spa, bytes_remaining);
3930 scan_evicted += bytes_evicted;
3931 total_evicted += bytes_evicted;
3933 /* we've reached the end, wrap to the beginning */
3934 if (++sublist_idx >= num_sublists)
3939 * If we didn't evict anything during this scan, we have
3940 * no reason to believe we'll evict more during another
3941 * scan, so break the loop.
3943 if (scan_evicted == 0) {
3944 /* This isn't possible, let's make that obvious */
3945 ASSERT3S(bytes, !=, 0);
3948 * When bytes is ARC_EVICT_ALL, the only way to
3949 * break the loop is when scan_evicted is zero.
3950 * In that case, we actually have evicted enough,
3951 * so we don't want to increment the kstat.
3953 if (bytes != ARC_EVICT_ALL) {
3954 ASSERT3S(total_evicted, <, bytes);
3955 ARCSTAT_BUMP(arcstat_evict_not_enough);
3962 for (int i = 0; i < num_sublists; i++) {
3963 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3964 multilist_sublist_remove(mls, markers[i]);
3965 multilist_sublist_unlock(mls);
3967 kmem_cache_free(hdr_full_cache, markers[i]);
3969 kmem_free(markers, sizeof (*markers) * num_sublists);
3971 return (total_evicted);
3975 * Flush all "evictable" data of the given type from the arc state
3976 * specified. This will not evict any "active" buffers (i.e. referenced).
3978 * When 'retry' is set to B_FALSE, the function will make a single pass
3979 * over the state and evict any buffers that it can. Since it doesn't
3980 * continually retry the eviction, it might end up leaving some buffers
3981 * in the ARC due to lock misses.
3983 * When 'retry' is set to B_TRUE, the function will continually retry the
3984 * eviction until *all* evictable buffers have been removed from the
3985 * state. As a result, if concurrent insertions into the state are
3986 * allowed (e.g. if the ARC isn't shutting down), this function might
3987 * wind up in an infinite loop, continually trying to evict buffers.
3990 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3993 uint64_t evicted = 0;
3995 while (refcount_count(&state->arcs_esize[type]) != 0) {
3996 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
4006 * Helper function for arc_prune_async() it is responsible for safely
4007 * handling the execution of a registered arc_prune_func_t.
4010 arc_prune_task(void *ptr)
4012 arc_prune_t *ap = (arc_prune_t *)ptr;
4013 arc_prune_func_t *func = ap->p_pfunc;
4016 func(ap->p_adjust, ap->p_private);
4018 refcount_remove(&ap->p_refcnt, func);
4022 * Notify registered consumers they must drop holds on a portion of the ARC
4023 * buffered they reference. This provides a mechanism to ensure the ARC can
4024 * honor the arc_meta_limit and reclaim otherwise pinned ARC buffers. This
4025 * is analogous to dnlc_reduce_cache() but more generic.
4027 * This operation is performed asynchronously so it may be safely called
4028 * in the context of the arc_reclaim_thread(). A reference is taken here
4029 * for each registered arc_prune_t and the arc_prune_task() is responsible
4030 * for releasing it once the registered arc_prune_func_t has completed.
4033 arc_prune_async(int64_t adjust)
4037 mutex_enter(&arc_prune_mtx);
4038 for (ap = list_head(&arc_prune_list); ap != NULL;
4039 ap = list_next(&arc_prune_list, ap)) {
4041 if (refcount_count(&ap->p_refcnt) >= 2)
4044 refcount_add(&ap->p_refcnt, ap->p_pfunc);
4045 ap->p_adjust = adjust;
4046 if (taskq_dispatch(arc_prune_taskq, arc_prune_task,
4047 ap, TQ_SLEEP) == TASKQID_INVALID) {
4048 refcount_remove(&ap->p_refcnt, ap->p_pfunc);
4051 ARCSTAT_BUMP(arcstat_prune);
4053 mutex_exit(&arc_prune_mtx);
4057 * Evict the specified number of bytes from the state specified,
4058 * restricting eviction to the spa and type given. This function
4059 * prevents us from trying to evict more from a state's list than
4060 * is "evictable", and to skip evicting altogether when passed a
4061 * negative value for "bytes". In contrast, arc_evict_state() will
4062 * evict everything it can, when passed a negative value for "bytes".
4065 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
4066 arc_buf_contents_t type)
4070 if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
4071 delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
4072 return (arc_evict_state(state, spa, delta, type));
4079 * Evict metadata buffers from the cache, such that arc_meta_used is
4080 * capped by the arc_meta_limit tunable.
4083 arc_adjust_meta(uint64_t meta_used)
4085 uint64_t total_evicted = 0;
4089 * If we're over the meta limit, we want to evict enough
4090 * metadata to get back under the meta limit. We don't want to
4091 * evict so much that we drop the MRU below arc_p, though. If
4092 * we're over the meta limit more than we're over arc_p, we
4093 * evict some from the MRU here, and some from the MFU below.
4095 target = MIN((int64_t)(meta_used - arc_meta_limit),
4096 (int64_t)(refcount_count(&arc_anon->arcs_size) +
4097 refcount_count(&arc_mru->arcs_size) - arc_p));
4099 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4102 * Similar to the above, we want to evict enough bytes to get us
4103 * below the meta limit, but not so much as to drop us below the
4104 * space allotted to the MFU (which is defined as arc_c - arc_p).
4106 target = MIN((int64_t)(meta_used - arc_meta_limit),
4107 (int64_t)(refcount_count(&arc_mfu->arcs_size) -
4110 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4112 return (total_evicted);
4116 * Return the type of the oldest buffer in the given arc state
4118 * This function will select a random sublist of type ARC_BUFC_DATA and
4119 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
4120 * is compared, and the type which contains the "older" buffer will be
4123 static arc_buf_contents_t
4124 arc_adjust_type(arc_state_t *state)
4126 multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
4127 multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
4128 int data_idx = multilist_get_random_index(data_ml);
4129 int meta_idx = multilist_get_random_index(meta_ml);
4130 multilist_sublist_t *data_mls;
4131 multilist_sublist_t *meta_mls;
4132 arc_buf_contents_t type;
4133 arc_buf_hdr_t *data_hdr;
4134 arc_buf_hdr_t *meta_hdr;
4137 * We keep the sublist lock until we're finished, to prevent
4138 * the headers from being destroyed via arc_evict_state().
4140 data_mls = multilist_sublist_lock(data_ml, data_idx);
4141 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4144 * These two loops are to ensure we skip any markers that
4145 * might be at the tail of the lists due to arc_evict_state().
4148 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4149 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4150 if (data_hdr->b_spa != 0)
4154 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4155 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4156 if (meta_hdr->b_spa != 0)
4160 if (data_hdr == NULL && meta_hdr == NULL) {
4161 type = ARC_BUFC_DATA;
4162 } else if (data_hdr == NULL) {
4163 ASSERT3P(meta_hdr, !=, NULL);
4164 type = ARC_BUFC_METADATA;
4165 } else if (meta_hdr == NULL) {
4166 ASSERT3P(data_hdr, !=, NULL);
4167 type = ARC_BUFC_DATA;
4169 ASSERT3P(data_hdr, !=, NULL);
4170 ASSERT3P(meta_hdr, !=, NULL);
4172 /* The headers can't be on the sublist without an L1 header */
4173 ASSERT(HDR_HAS_L1HDR(data_hdr));
4174 ASSERT(HDR_HAS_L1HDR(meta_hdr));
4176 if (data_hdr->b_l1hdr.b_arc_access <
4177 meta_hdr->b_l1hdr.b_arc_access) {
4178 type = ARC_BUFC_DATA;
4180 type = ARC_BUFC_METADATA;
4184 multilist_sublist_unlock(meta_mls);
4185 multilist_sublist_unlock(data_mls);
4191 * Evict buffers from the cache, such that arc_size is capped by arc_c.
4196 uint64_t total_evicted = 0;
4199 uint64_t asize = aggsum_value(&arc_size);
4200 uint64_t ameta = aggsum_value(&arc_meta_used);
4203 * If we're over arc_meta_limit, we want to correct that before
4204 * potentially evicting data buffers below.
4206 total_evicted += arc_adjust_meta(ameta);
4211 * If we're over the target cache size, we want to evict enough
4212 * from the list to get back to our target size. We don't want
4213 * to evict too much from the MRU, such that it drops below
4214 * arc_p. So, if we're over our target cache size more than
4215 * the MRU is over arc_p, we'll evict enough to get back to
4216 * arc_p here, and then evict more from the MFU below.
4218 target = MIN((int64_t)(asize - arc_c),
4219 (int64_t)(refcount_count(&arc_anon->arcs_size) +
4220 refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4223 * If we're below arc_meta_min, always prefer to evict data.
4224 * Otherwise, try to satisfy the requested number of bytes to
4225 * evict from the type which contains older buffers; in an
4226 * effort to keep newer buffers in the cache regardless of their
4227 * type. If we cannot satisfy the number of bytes from this
4228 * type, spill over into the next type.
4230 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
4231 ameta > arc_meta_min) {
4232 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4233 total_evicted += bytes;
4236 * If we couldn't evict our target number of bytes from
4237 * metadata, we try to get the rest from data.
4242 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4244 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4245 total_evicted += bytes;
4248 * If we couldn't evict our target number of bytes from
4249 * data, we try to get the rest from metadata.
4254 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4260 * Now that we've tried to evict enough from the MRU to get its
4261 * size back to arc_p, if we're still above the target cache
4262 * size, we evict the rest from the MFU.
4264 target = asize - arc_c;
4266 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4267 ameta > arc_meta_min) {
4268 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4269 total_evicted += bytes;
4272 * If we couldn't evict our target number of bytes from
4273 * metadata, we try to get the rest from data.
4278 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4280 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4281 total_evicted += bytes;
4284 * If we couldn't evict our target number of bytes from
4285 * data, we try to get the rest from data.
4290 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4294 * Adjust ghost lists
4296 * In addition to the above, the ARC also defines target values
4297 * for the ghost lists. The sum of the mru list and mru ghost
4298 * list should never exceed the target size of the cache, and
4299 * the sum of the mru list, mfu list, mru ghost list, and mfu
4300 * ghost list should never exceed twice the target size of the
4301 * cache. The following logic enforces these limits on the ghost
4302 * caches, and evicts from them as needed.
4304 target = refcount_count(&arc_mru->arcs_size) +
4305 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4307 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4308 total_evicted += bytes;
4313 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4316 * We assume the sum of the mru list and mfu list is less than
4317 * or equal to arc_c (we enforced this above), which means we
4318 * can use the simpler of the two equations below:
4320 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4321 * mru ghost + mfu ghost <= arc_c
4323 target = refcount_count(&arc_mru_ghost->arcs_size) +
4324 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4326 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4327 total_evicted += bytes;
4332 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4334 return (total_evicted);
4338 arc_flush(spa_t *spa, boolean_t retry)
4343 * If retry is B_TRUE, a spa must not be specified since we have
4344 * no good way to determine if all of a spa's buffers have been
4345 * evicted from an arc state.
4347 ASSERT(!retry || spa == 0);
4350 guid = spa_load_guid(spa);
4352 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4353 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4355 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4356 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4358 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4359 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4361 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4362 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4366 arc_shrink(int64_t to_free)
4368 uint64_t asize = aggsum_value(&arc_size);
4369 if (arc_c > arc_c_min) {
4370 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4371 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4372 if (arc_c > arc_c_min + to_free)
4373 atomic_add_64(&arc_c, -to_free);
4377 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4379 arc_c = MAX(asize, arc_c_min);
4381 arc_p = (arc_c >> 1);
4383 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4386 ASSERT(arc_c >= arc_c_min);
4387 ASSERT((int64_t)arc_p >= 0);
4390 if (asize > arc_c) {
4391 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, asize,
4393 (void) arc_adjust();
4397 typedef enum free_memory_reason_t {
4402 FMR_PAGES_PP_MAXIMUM,
4405 } free_memory_reason_t;
4407 int64_t last_free_memory;
4408 free_memory_reason_t last_free_reason;
4411 * Additional reserve of pages for pp_reserve.
4413 int64_t arc_pages_pp_reserve = 64;
4416 * Additional reserve of pages for swapfs.
4418 int64_t arc_swapfs_reserve = 64;
4421 * Return the amount of memory that can be consumed before reclaim will be
4422 * needed. Positive if there is sufficient free memory, negative indicates
4423 * the amount of memory that needs to be freed up.
4426 arc_available_memory(void)
4428 int64_t lowest = INT64_MAX;
4430 free_memory_reason_t r = FMR_UNKNOWN;
4435 * Cooperate with pagedaemon when it's time for it to scan
4436 * and reclaim some pages.
4438 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4446 n = PAGESIZE * (-needfree);
4454 * check that we're out of range of the pageout scanner. It starts to
4455 * schedule paging if freemem is less than lotsfree and needfree.
4456 * lotsfree is the high-water mark for pageout, and needfree is the
4457 * number of needed free pages. We add extra pages here to make sure
4458 * the scanner doesn't start up while we're freeing memory.
4460 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4467 * check to make sure that swapfs has enough space so that anon
4468 * reservations can still succeed. anon_resvmem() checks that the
4469 * availrmem is greater than swapfs_minfree, and the number of reserved
4470 * swap pages. We also add a bit of extra here just to prevent
4471 * circumstances from getting really dire.
4473 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4474 desfree - arc_swapfs_reserve);
4477 r = FMR_SWAPFS_MINFREE;
4482 * Check that we have enough availrmem that memory locking (e.g., via
4483 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
4484 * stores the number of pages that cannot be locked; when availrmem
4485 * drops below pages_pp_maximum, page locking mechanisms such as
4486 * page_pp_lock() will fail.)
4488 n = PAGESIZE * (availrmem - pages_pp_maximum -
4489 arc_pages_pp_reserve);
4492 r = FMR_PAGES_PP_MAXIMUM;
4495 #endif /* __FreeBSD__ */
4496 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4498 * If we're on an i386 platform, it's possible that we'll exhaust the
4499 * kernel heap space before we ever run out of available physical
4500 * memory. Most checks of the size of the heap_area compare against
4501 * tune.t_minarmem, which is the minimum available real memory that we
4502 * can have in the system. However, this is generally fixed at 25 pages
4503 * which is so low that it's useless. In this comparison, we seek to
4504 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4505 * heap is allocated. (Or, in the calculation, if less than 1/4th is
4508 n = uma_avail() - (long)(uma_limit() / 4);
4516 * If zio data pages are being allocated out of a separate heap segment,
4517 * then enforce that the size of available vmem for this arena remains
4518 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4520 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4521 * memory (in the zio_arena) free, which can avoid memory
4522 * fragmentation issues.
4524 if (zio_arena != NULL) {
4525 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4526 (vmem_size(zio_arena, VMEM_ALLOC) >>
4527 arc_zio_arena_free_shift);
4535 /* Every 100 calls, free a small amount */
4536 if (spa_get_random(100) == 0)
4538 #endif /* _KERNEL */
4540 last_free_memory = lowest;
4541 last_free_reason = r;
4542 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4548 * Determine if the system is under memory pressure and is asking
4549 * to reclaim memory. A return value of B_TRUE indicates that the system
4550 * is under memory pressure and that the arc should adjust accordingly.
4553 arc_reclaim_needed(void)
4555 return (arc_available_memory() < 0);
4558 extern kmem_cache_t *zio_buf_cache[];
4559 extern kmem_cache_t *zio_data_buf_cache[];
4560 extern kmem_cache_t *range_seg_cache;
4561 extern kmem_cache_t *abd_chunk_cache;
4563 static __noinline void
4564 arc_kmem_reap_now(void)
4567 kmem_cache_t *prev_cache = NULL;
4568 kmem_cache_t *prev_data_cache = NULL;
4570 DTRACE_PROBE(arc__kmem_reap_start);
4572 if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4574 * We are exceeding our meta-data cache limit.
4575 * Purge some DNLC entries to release holds on meta-data.
4577 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4581 * Reclaim unused memory from all kmem caches.
4588 * If a kmem reap is already active, don't schedule more. We must
4589 * check for this because kmem_cache_reap_soon() won't actually
4590 * block on the cache being reaped (this is to prevent callers from
4591 * becoming implicitly blocked by a system-wide kmem reap -- which,
4592 * on a system with many, many full magazines, can take minutes).
4594 if (kmem_cache_reap_active())
4597 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4598 if (zio_buf_cache[i] != prev_cache) {
4599 prev_cache = zio_buf_cache[i];
4600 kmem_cache_reap_soon(zio_buf_cache[i]);
4602 if (zio_data_buf_cache[i] != prev_data_cache) {
4603 prev_data_cache = zio_data_buf_cache[i];
4604 kmem_cache_reap_soon(zio_data_buf_cache[i]);
4607 kmem_cache_reap_soon(abd_chunk_cache);
4608 kmem_cache_reap_soon(buf_cache);
4609 kmem_cache_reap_soon(hdr_full_cache);
4610 kmem_cache_reap_soon(hdr_l2only_cache);
4611 kmem_cache_reap_soon(range_seg_cache);
4614 if (zio_arena != NULL) {
4616 * Ask the vmem arena to reclaim unused memory from its
4619 vmem_qcache_reap(zio_arena);
4622 DTRACE_PROBE(arc__kmem_reap_end);
4626 * Threads can block in arc_get_data_impl() waiting for this thread to evict
4627 * enough data and signal them to proceed. When this happens, the threads in
4628 * arc_get_data_impl() are sleeping while holding the hash lock for their
4629 * particular arc header. Thus, we must be careful to never sleep on a
4630 * hash lock in this thread. This is to prevent the following deadlock:
4632 * - Thread A sleeps on CV in arc_get_data_impl() holding hash lock "L",
4633 * waiting for the reclaim thread to signal it.
4635 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4636 * fails, and goes to sleep forever.
4638 * This possible deadlock is avoided by always acquiring a hash lock
4639 * using mutex_tryenter() from arc_reclaim_thread().
4643 arc_reclaim_thread(void *unused __unused)
4645 hrtime_t growtime = 0;
4646 hrtime_t kmem_reap_time = 0;
4649 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4651 mutex_enter(&arc_reclaim_lock);
4652 while (!arc_reclaim_thread_exit) {
4653 uint64_t evicted = 0;
4656 * This is necessary in order for the mdb ::arc dcmd to
4657 * show up to date information. Since the ::arc command
4658 * does not call the kstat's update function, without
4659 * this call, the command may show stale stats for the
4660 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4661 * with this change, the data might be up to 1 second
4662 * out of date; but that should suffice. The arc_state_t
4663 * structures can be queried directly if more accurate
4664 * information is needed.
4666 if (arc_ksp != NULL)
4667 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4669 mutex_exit(&arc_reclaim_lock);
4672 * We call arc_adjust() before (possibly) calling
4673 * arc_kmem_reap_now(), so that we can wake up
4674 * arc_get_data_impl() sooner.
4676 evicted = arc_adjust();
4678 int64_t free_memory = arc_available_memory();
4679 if (free_memory < 0) {
4680 hrtime_t curtime = gethrtime();
4681 arc_no_grow = B_TRUE;
4685 * Wait at least zfs_grow_retry (default 60) seconds
4686 * before considering growing.
4688 growtime = curtime + SEC2NSEC(arc_grow_retry);
4691 * Wait at least arc_kmem_cache_reap_retry_ms
4692 * between arc_kmem_reap_now() calls. Without
4693 * this check it is possible to end up in a
4694 * situation where we spend lots of time
4695 * reaping caches, while we're near arc_c_min.
4697 if (curtime >= kmem_reap_time) {
4698 arc_kmem_reap_now();
4699 kmem_reap_time = gethrtime() +
4700 MSEC2NSEC(arc_kmem_cache_reap_retry_ms);
4704 * If we are still low on memory, shrink the ARC
4705 * so that we have arc_shrink_min free space.
4707 free_memory = arc_available_memory();
4710 (arc_c >> arc_shrink_shift) - free_memory;
4714 to_free = MAX(to_free, ptob(needfree));
4717 arc_shrink(to_free);
4719 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4720 arc_no_grow = B_TRUE;
4721 } else if (gethrtime() >= growtime) {
4722 arc_no_grow = B_FALSE;
4725 mutex_enter(&arc_reclaim_lock);
4728 * If evicted is zero, we couldn't evict anything via
4729 * arc_adjust(). This could be due to hash lock
4730 * collisions, but more likely due to the majority of
4731 * arc buffers being unevictable. Therefore, even if
4732 * arc_size is above arc_c, another pass is unlikely to
4733 * be helpful and could potentially cause us to enter an
4736 if (aggsum_compare(&arc_size, arc_c) <= 0|| evicted == 0) {
4738 * We're either no longer overflowing, or we
4739 * can't evict anything more, so we should wake
4740 * up any threads before we go to sleep.
4742 cv_broadcast(&arc_reclaim_waiters_cv);
4745 * Block until signaled, or after one second (we
4746 * might need to perform arc_kmem_reap_now()
4747 * even if we aren't being signalled)
4749 CALLB_CPR_SAFE_BEGIN(&cpr);
4750 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4751 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4752 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4756 arc_reclaim_thread_exit = B_FALSE;
4757 cv_broadcast(&arc_reclaim_thread_cv);
4758 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
4762 static u_int arc_dnlc_evicts_arg;
4763 extern struct vfsops zfs_vfsops;
4766 arc_dnlc_evicts_thread(void *dummy __unused)
4771 CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
4773 mutex_enter(&arc_dnlc_evicts_lock);
4774 while (!arc_dnlc_evicts_thread_exit) {
4775 CALLB_CPR_SAFE_BEGIN(&cpr);
4776 (void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
4777 CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
4778 if (arc_dnlc_evicts_arg != 0) {
4779 percent = arc_dnlc_evicts_arg;
4780 mutex_exit(&arc_dnlc_evicts_lock);
4782 vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
4784 mutex_enter(&arc_dnlc_evicts_lock);
4786 * Clear our token only after vnlru_free()
4787 * pass is done, to avoid false queueing of
4790 arc_dnlc_evicts_arg = 0;
4793 arc_dnlc_evicts_thread_exit = FALSE;
4794 cv_broadcast(&arc_dnlc_evicts_cv);
4795 CALLB_CPR_EXIT(&cpr);
4800 dnlc_reduce_cache(void *arg)
4804 percent = (u_int)(uintptr_t)arg;
4805 mutex_enter(&arc_dnlc_evicts_lock);
4806 if (arc_dnlc_evicts_arg == 0) {
4807 arc_dnlc_evicts_arg = percent;
4808 cv_broadcast(&arc_dnlc_evicts_cv);
4810 mutex_exit(&arc_dnlc_evicts_lock);
4814 * Adapt arc info given the number of bytes we are trying to add and
4815 * the state that we are comming from. This function is only called
4816 * when we are adding new content to the cache.
4819 arc_adapt(int bytes, arc_state_t *state)
4822 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4823 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4824 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4826 if (state == arc_l2c_only)
4831 * Adapt the target size of the MRU list:
4832 * - if we just hit in the MRU ghost list, then increase
4833 * the target size of the MRU list.
4834 * - if we just hit in the MFU ghost list, then increase
4835 * the target size of the MFU list by decreasing the
4836 * target size of the MRU list.
4838 if (state == arc_mru_ghost) {
4839 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4840 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4842 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4843 } else if (state == arc_mfu_ghost) {
4846 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4847 mult = MIN(mult, 10);
4849 delta = MIN(bytes * mult, arc_p);
4850 arc_p = MAX(arc_p_min, arc_p - delta);
4852 ASSERT((int64_t)arc_p >= 0);
4854 if (arc_reclaim_needed()) {
4855 cv_signal(&arc_reclaim_thread_cv);
4862 if (arc_c >= arc_c_max)
4866 * If we're within (2 * maxblocksize) bytes of the target
4867 * cache size, increment the target cache size
4869 if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
4871 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
4872 atomic_add_64(&arc_c, (int64_t)bytes);
4873 if (arc_c > arc_c_max)
4875 else if (state == arc_anon)
4876 atomic_add_64(&arc_p, (int64_t)bytes);
4880 ASSERT((int64_t)arc_p >= 0);
4884 * Check if arc_size has grown past our upper threshold, determined by
4885 * zfs_arc_overflow_shift.
4888 arc_is_overflowing(void)
4890 /* Always allow at least one block of overflow */
4891 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4892 arc_c >> zfs_arc_overflow_shift);
4895 * We just compare the lower bound here for performance reasons. Our
4896 * primary goals are to make sure that the arc never grows without
4897 * bound, and that it can reach its maximum size. This check
4898 * accomplishes both goals. The maximum amount we could run over by is
4899 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4900 * in the ARC. In practice, that's in the tens of MB, which is low
4901 * enough to be safe.
4903 return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4907 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4909 arc_buf_contents_t type = arc_buf_type(hdr);
4911 arc_get_data_impl(hdr, size, tag);
4912 if (type == ARC_BUFC_METADATA) {
4913 return (abd_alloc(size, B_TRUE));
4915 ASSERT(type == ARC_BUFC_DATA);
4916 return (abd_alloc(size, B_FALSE));
4921 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4923 arc_buf_contents_t type = arc_buf_type(hdr);
4925 arc_get_data_impl(hdr, size, tag);
4926 if (type == ARC_BUFC_METADATA) {
4927 return (zio_buf_alloc(size));
4929 ASSERT(type == ARC_BUFC_DATA);
4930 return (zio_data_buf_alloc(size));
4935 * Allocate a block and return it to the caller. If we are hitting the
4936 * hard limit for the cache size, we must sleep, waiting for the eviction
4937 * thread to catch up. If we're past the target size but below the hard
4938 * limit, we'll only signal the reclaim thread and continue on.
4941 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4943 arc_state_t *state = hdr->b_l1hdr.b_state;
4944 arc_buf_contents_t type = arc_buf_type(hdr);
4946 arc_adapt(size, state);
4949 * If arc_size is currently overflowing, and has grown past our
4950 * upper limit, we must be adding data faster than the evict
4951 * thread can evict. Thus, to ensure we don't compound the
4952 * problem by adding more data and forcing arc_size to grow even
4953 * further past it's target size, we halt and wait for the
4954 * eviction thread to catch up.
4956 * It's also possible that the reclaim thread is unable to evict
4957 * enough buffers to get arc_size below the overflow limit (e.g.
4958 * due to buffers being un-evictable, or hash lock collisions).
4959 * In this case, we want to proceed regardless if we're
4960 * overflowing; thus we don't use a while loop here.
4962 if (arc_is_overflowing()) {
4963 mutex_enter(&arc_reclaim_lock);
4966 * Now that we've acquired the lock, we may no longer be
4967 * over the overflow limit, lets check.
4969 * We're ignoring the case of spurious wake ups. If that
4970 * were to happen, it'd let this thread consume an ARC
4971 * buffer before it should have (i.e. before we're under
4972 * the overflow limit and were signalled by the reclaim
4973 * thread). As long as that is a rare occurrence, it
4974 * shouldn't cause any harm.
4976 if (arc_is_overflowing()) {
4977 cv_signal(&arc_reclaim_thread_cv);
4978 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4981 mutex_exit(&arc_reclaim_lock);
4984 VERIFY3U(hdr->b_type, ==, type);
4985 if (type == ARC_BUFC_METADATA) {
4986 arc_space_consume(size, ARC_SPACE_META);
4988 arc_space_consume(size, ARC_SPACE_DATA);
4992 * Update the state size. Note that ghost states have a
4993 * "ghost size" and so don't need to be updated.
4995 if (!GHOST_STATE(state)) {
4997 (void) refcount_add_many(&state->arcs_size, size, tag);
5000 * If this is reached via arc_read, the link is
5001 * protected by the hash lock. If reached via
5002 * arc_buf_alloc, the header should not be accessed by
5003 * any other thread. And, if reached via arc_read_done,
5004 * the hash lock will protect it if it's found in the
5005 * hash table; otherwise no other thread should be
5006 * trying to [add|remove]_reference it.
5008 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5009 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5010 (void) refcount_add_many(&state->arcs_esize[type],
5015 * If we are growing the cache, and we are adding anonymous
5016 * data, and we have outgrown arc_p, update arc_p
5018 if (aggsum_compare(&arc_size, arc_c) < 0 &&
5019 hdr->b_l1hdr.b_state == arc_anon &&
5020 (refcount_count(&arc_anon->arcs_size) +
5021 refcount_count(&arc_mru->arcs_size) > arc_p))
5022 arc_p = MIN(arc_c, arc_p + size);
5024 ARCSTAT_BUMP(arcstat_allocated);
5028 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5030 arc_free_data_impl(hdr, size, tag);
5035 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5037 arc_buf_contents_t type = arc_buf_type(hdr);
5039 arc_free_data_impl(hdr, size, tag);
5040 if (type == ARC_BUFC_METADATA) {
5041 zio_buf_free(buf, size);
5043 ASSERT(type == ARC_BUFC_DATA);
5044 zio_data_buf_free(buf, size);
5049 * Free the arc data buffer.
5052 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5054 arc_state_t *state = hdr->b_l1hdr.b_state;
5055 arc_buf_contents_t type = arc_buf_type(hdr);
5057 /* protected by hash lock, if in the hash table */
5058 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5059 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5060 ASSERT(state != arc_anon && state != arc_l2c_only);
5062 (void) refcount_remove_many(&state->arcs_esize[type],
5065 (void) refcount_remove_many(&state->arcs_size, size, tag);
5067 VERIFY3U(hdr->b_type, ==, type);
5068 if (type == ARC_BUFC_METADATA) {
5069 arc_space_return(size, ARC_SPACE_META);
5071 ASSERT(type == ARC_BUFC_DATA);
5072 arc_space_return(size, ARC_SPACE_DATA);
5077 * This routine is called whenever a buffer is accessed.
5078 * NOTE: the hash lock is dropped in this function.
5081 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5085 ASSERT(MUTEX_HELD(hash_lock));
5086 ASSERT(HDR_HAS_L1HDR(hdr));
5088 if (hdr->b_l1hdr.b_state == arc_anon) {
5090 * This buffer is not in the cache, and does not
5091 * appear in our "ghost" list. Add the new buffer
5095 ASSERT0(hdr->b_l1hdr.b_arc_access);
5096 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5097 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5098 arc_change_state(arc_mru, hdr, hash_lock);
5100 } else if (hdr->b_l1hdr.b_state == arc_mru) {
5101 now = ddi_get_lbolt();
5104 * If this buffer is here because of a prefetch, then either:
5105 * - clear the flag if this is a "referencing" read
5106 * (any subsequent access will bump this into the MFU state).
5108 * - move the buffer to the head of the list if this is
5109 * another prefetch (to make it less likely to be evicted).
5111 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5112 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5113 /* link protected by hash lock */
5114 ASSERT(multilist_link_active(
5115 &hdr->b_l1hdr.b_arc_node));
5117 arc_hdr_clear_flags(hdr,
5119 ARC_FLAG_PRESCIENT_PREFETCH);
5120 ARCSTAT_BUMP(arcstat_mru_hits);
5122 hdr->b_l1hdr.b_arc_access = now;
5127 * This buffer has been "accessed" only once so far,
5128 * but it is still in the cache. Move it to the MFU
5131 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5133 * More than 125ms have passed since we
5134 * instantiated this buffer. Move it to the
5135 * most frequently used state.
5137 hdr->b_l1hdr.b_arc_access = now;
5138 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5139 arc_change_state(arc_mfu, hdr, hash_lock);
5141 ARCSTAT_BUMP(arcstat_mru_hits);
5142 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5143 arc_state_t *new_state;
5145 * This buffer has been "accessed" recently, but
5146 * was evicted from the cache. Move it to the
5150 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5151 new_state = arc_mru;
5152 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5153 arc_hdr_clear_flags(hdr,
5155 ARC_FLAG_PRESCIENT_PREFETCH);
5157 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5159 new_state = arc_mfu;
5160 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5163 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5164 arc_change_state(new_state, hdr, hash_lock);
5166 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5167 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
5169 * This buffer has been accessed more than once and is
5170 * still in the cache. Keep it in the MFU state.
5172 * NOTE: an add_reference() that occurred when we did
5173 * the arc_read() will have kicked this off the list.
5174 * If it was a prefetch, we will explicitly move it to
5175 * the head of the list now.
5178 ARCSTAT_BUMP(arcstat_mfu_hits);
5179 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5180 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5181 arc_state_t *new_state = arc_mfu;
5183 * This buffer has been accessed more than once but has
5184 * been evicted from the cache. Move it back to the
5188 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5190 * This is a prefetch access...
5191 * move this block back to the MRU state.
5193 new_state = arc_mru;
5196 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5197 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5198 arc_change_state(new_state, hdr, hash_lock);
5200 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5201 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5203 * This buffer is on the 2nd Level ARC.
5206 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5207 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5208 arc_change_state(arc_mfu, hdr, hash_lock);
5210 ASSERT(!"invalid arc state");
5215 * This routine is called by dbuf_hold() to update the arc_access() state
5216 * which otherwise would be skipped for entries in the dbuf cache.
5219 arc_buf_access(arc_buf_t *buf)
5221 mutex_enter(&buf->b_evict_lock);
5222 arc_buf_hdr_t *hdr = buf->b_hdr;
5225 * Avoid taking the hash_lock when possible as an optimization.
5226 * The header must be checked again under the hash_lock in order
5227 * to handle the case where it is concurrently being released.
5229 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5230 mutex_exit(&buf->b_evict_lock);
5231 ARCSTAT_BUMP(arcstat_access_skip);
5235 kmutex_t *hash_lock = HDR_LOCK(hdr);
5236 mutex_enter(hash_lock);
5238 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5239 mutex_exit(hash_lock);
5240 mutex_exit(&buf->b_evict_lock);
5241 ARCSTAT_BUMP(arcstat_access_skip);
5245 mutex_exit(&buf->b_evict_lock);
5247 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5248 hdr->b_l1hdr.b_state == arc_mfu);
5250 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5251 arc_access(hdr, hash_lock);
5252 mutex_exit(hash_lock);
5254 ARCSTAT_BUMP(arcstat_hits);
5255 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5256 demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5259 /* a generic arc_read_done_func_t which you can use */
5262 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5263 arc_buf_t *buf, void *arg)
5268 bcopy(buf->b_data, arg, arc_buf_size(buf));
5269 arc_buf_destroy(buf, arg);
5272 /* a generic arc_read_done_func_t */
5275 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5276 arc_buf_t *buf, void *arg)
5278 arc_buf_t **bufp = arg;
5280 ASSERT(zio == NULL || zio->io_error != 0);
5283 ASSERT(zio == NULL || zio->io_error == 0);
5285 ASSERT(buf->b_data != NULL);
5290 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5292 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5293 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5294 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
5296 if (HDR_COMPRESSION_ENABLED(hdr)) {
5297 ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
5298 BP_GET_COMPRESS(bp));
5300 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5301 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5306 arc_read_done(zio_t *zio)
5308 arc_buf_hdr_t *hdr = zio->io_private;
5309 kmutex_t *hash_lock = NULL;
5310 arc_callback_t *callback_list;
5311 arc_callback_t *acb;
5312 boolean_t freeable = B_FALSE;
5313 boolean_t no_zio_error = (zio->io_error == 0);
5316 * The hdr was inserted into hash-table and removed from lists
5317 * prior to starting I/O. We should find this header, since
5318 * it's in the hash table, and it should be legit since it's
5319 * not possible to evict it during the I/O. The only possible
5320 * reason for it not to be found is if we were freed during the
5323 if (HDR_IN_HASH_TABLE(hdr)) {
5324 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5325 ASSERT3U(hdr->b_dva.dva_word[0], ==,
5326 BP_IDENTITY(zio->io_bp)->dva_word[0]);
5327 ASSERT3U(hdr->b_dva.dva_word[1], ==,
5328 BP_IDENTITY(zio->io_bp)->dva_word[1]);
5330 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
5333 ASSERT((found == hdr &&
5334 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5335 (found == hdr && HDR_L2_READING(hdr)));
5336 ASSERT3P(hash_lock, !=, NULL);
5340 /* byteswap if necessary */
5341 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5342 if (BP_GET_LEVEL(zio->io_bp) > 0) {
5343 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5345 hdr->b_l1hdr.b_byteswap =
5346 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5349 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5353 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5354 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5355 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5357 callback_list = hdr->b_l1hdr.b_acb;
5358 ASSERT3P(callback_list, !=, NULL);
5360 if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5362 * Only call arc_access on anonymous buffers. This is because
5363 * if we've issued an I/O for an evicted buffer, we've already
5364 * called arc_access (to prevent any simultaneous readers from
5365 * getting confused).
5367 arc_access(hdr, hash_lock);
5371 * If a read request has a callback (i.e. acb_done is not NULL), then we
5372 * make a buf containing the data according to the parameters which were
5373 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5374 * aren't needlessly decompressing the data multiple times.
5376 int callback_cnt = 0;
5377 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5384 int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5385 acb->acb_compressed, zio->io_error == 0,
5389 * Decompression failed. Set io_error
5390 * so that when we call acb_done (below),
5391 * we will indicate that the read failed.
5392 * Note that in the unusual case where one
5393 * callback is compressed and another
5394 * uncompressed, we will mark all of them
5395 * as failed, even though the uncompressed
5396 * one can't actually fail. In this case,
5397 * the hdr will not be anonymous, because
5398 * if there are multiple callbacks, it's
5399 * because multiple threads found the same
5400 * arc buf in the hash table.
5402 zio->io_error = error;
5407 * If there are multiple callbacks, we must have the hash lock,
5408 * because the only way for multiple threads to find this hdr is
5409 * in the hash table. This ensures that if there are multiple
5410 * callbacks, the hdr is not anonymous. If it were anonymous,
5411 * we couldn't use arc_buf_destroy() in the error case below.
5413 ASSERT(callback_cnt < 2 || hash_lock != NULL);
5415 hdr->b_l1hdr.b_acb = NULL;
5416 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5417 if (callback_cnt == 0) {
5418 ASSERT(HDR_PREFETCH(hdr));
5419 ASSERT0(hdr->b_l1hdr.b_bufcnt);
5420 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5423 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5424 callback_list != NULL);
5427 arc_hdr_verify(hdr, zio->io_bp);
5429 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5430 if (hdr->b_l1hdr.b_state != arc_anon)
5431 arc_change_state(arc_anon, hdr, hash_lock);
5432 if (HDR_IN_HASH_TABLE(hdr))
5433 buf_hash_remove(hdr);
5434 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5438 * Broadcast before we drop the hash_lock to avoid the possibility
5439 * that the hdr (and hence the cv) might be freed before we get to
5440 * the cv_broadcast().
5442 cv_broadcast(&hdr->b_l1hdr.b_cv);
5444 if (hash_lock != NULL) {
5445 mutex_exit(hash_lock);
5448 * This block was freed while we waited for the read to
5449 * complete. It has been removed from the hash table and
5450 * moved to the anonymous state (so that it won't show up
5453 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5454 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5457 /* execute each callback and free its structure */
5458 while ((acb = callback_list) != NULL) {
5459 if (acb->acb_done != NULL) {
5460 if (zio->io_error != 0 && acb->acb_buf != NULL) {
5462 * If arc_buf_alloc_impl() fails during
5463 * decompression, the buf will still be
5464 * allocated, and needs to be freed here.
5466 arc_buf_destroy(acb->acb_buf, acb->acb_private);
5467 acb->acb_buf = NULL;
5469 acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5470 acb->acb_buf, acb->acb_private);
5473 if (acb->acb_zio_dummy != NULL) {
5474 acb->acb_zio_dummy->io_error = zio->io_error;
5475 zio_nowait(acb->acb_zio_dummy);
5478 callback_list = acb->acb_next;
5479 kmem_free(acb, sizeof (arc_callback_t));
5483 arc_hdr_destroy(hdr);
5487 * "Read" the block at the specified DVA (in bp) via the
5488 * cache. If the block is found in the cache, invoke the provided
5489 * callback immediately and return. Note that the `zio' parameter
5490 * in the callback will be NULL in this case, since no IO was
5491 * required. If the block is not in the cache pass the read request
5492 * on to the spa with a substitute callback function, so that the
5493 * requested block will be added to the cache.
5495 * If a read request arrives for a block that has a read in-progress,
5496 * either wait for the in-progress read to complete (and return the
5497 * results); or, if this is a read with a "done" func, add a record
5498 * to the read to invoke the "done" func when the read completes,
5499 * and return; or just return.
5501 * arc_read_done() will invoke all the requested "done" functions
5502 * for readers of this block.
5505 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_read_done_func_t *done,
5506 void *private, zio_priority_t priority, int zio_flags,
5507 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5509 arc_buf_hdr_t *hdr = NULL;
5510 kmutex_t *hash_lock = NULL;
5512 uint64_t guid = spa_load_guid(spa);
5513 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5516 ASSERT(!BP_IS_EMBEDDED(bp) ||
5517 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5520 if (!BP_IS_EMBEDDED(bp)) {
5522 * Embedded BP's have no DVA and require no I/O to "read".
5523 * Create an anonymous arc buf to back it.
5525 hdr = buf_hash_find(guid, bp, &hash_lock);
5528 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
5529 arc_buf_t *buf = NULL;
5530 *arc_flags |= ARC_FLAG_CACHED;
5532 if (HDR_IO_IN_PROGRESS(hdr)) {
5533 zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5535 ASSERT3P(head_zio, !=, NULL);
5536 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5537 priority == ZIO_PRIORITY_SYNC_READ) {
5539 * This is a sync read that needs to wait for
5540 * an in-flight async read. Request that the
5541 * zio have its priority upgraded.
5543 zio_change_priority(head_zio, priority);
5544 DTRACE_PROBE1(arc__async__upgrade__sync,
5545 arc_buf_hdr_t *, hdr);
5546 ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5548 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5549 arc_hdr_clear_flags(hdr,
5550 ARC_FLAG_PREDICTIVE_PREFETCH);
5553 if (*arc_flags & ARC_FLAG_WAIT) {
5554 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5555 mutex_exit(hash_lock);
5558 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5561 arc_callback_t *acb = NULL;
5563 acb = kmem_zalloc(sizeof (arc_callback_t),
5565 acb->acb_done = done;
5566 acb->acb_private = private;
5567 acb->acb_compressed = compressed_read;
5569 acb->acb_zio_dummy = zio_null(pio,
5570 spa, NULL, NULL, NULL, zio_flags);
5572 ASSERT3P(acb->acb_done, !=, NULL);
5573 acb->acb_zio_head = head_zio;
5574 acb->acb_next = hdr->b_l1hdr.b_acb;
5575 hdr->b_l1hdr.b_acb = acb;
5576 mutex_exit(hash_lock);
5579 mutex_exit(hash_lock);
5583 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5584 hdr->b_l1hdr.b_state == arc_mfu);
5587 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5589 * This is a demand read which does not have to
5590 * wait for i/o because we did a predictive
5591 * prefetch i/o for it, which has completed.
5594 arc__demand__hit__predictive__prefetch,
5595 arc_buf_hdr_t *, hdr);
5597 arcstat_demand_hit_predictive_prefetch);
5598 arc_hdr_clear_flags(hdr,
5599 ARC_FLAG_PREDICTIVE_PREFETCH);
5602 if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5604 arcstat_demand_hit_prescient_prefetch);
5605 arc_hdr_clear_flags(hdr,
5606 ARC_FLAG_PRESCIENT_PREFETCH);
5609 ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5610 /* Get a buf with the desired data in it. */
5611 rc = arc_buf_alloc_impl(hdr, private,
5612 compressed_read, B_TRUE, &buf);
5614 arc_buf_destroy(buf, private);
5617 ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
5618 rc == 0 || rc != ENOENT);
5619 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
5620 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5621 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5623 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5624 arc_access(hdr, hash_lock);
5625 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5626 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5627 if (*arc_flags & ARC_FLAG_L2CACHE)
5628 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5629 mutex_exit(hash_lock);
5630 ARCSTAT_BUMP(arcstat_hits);
5631 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5632 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5633 data, metadata, hits);
5636 done(NULL, zb, bp, buf, private);
5638 uint64_t lsize = BP_GET_LSIZE(bp);
5639 uint64_t psize = BP_GET_PSIZE(bp);
5640 arc_callback_t *acb;
5643 boolean_t devw = B_FALSE;
5647 /* this block is not in the cache */
5648 arc_buf_hdr_t *exists = NULL;
5649 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5650 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5651 BP_GET_COMPRESS(bp), type);
5653 if (!BP_IS_EMBEDDED(bp)) {
5654 hdr->b_dva = *BP_IDENTITY(bp);
5655 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5656 exists = buf_hash_insert(hdr, &hash_lock);
5658 if (exists != NULL) {
5659 /* somebody beat us to the hash insert */
5660 mutex_exit(hash_lock);
5661 buf_discard_identity(hdr);
5662 arc_hdr_destroy(hdr);
5663 goto top; /* restart the IO request */
5667 * This block is in the ghost cache. If it was L2-only
5668 * (and thus didn't have an L1 hdr), we realloc the
5669 * header to add an L1 hdr.
5671 if (!HDR_HAS_L1HDR(hdr)) {
5672 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5675 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5676 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5677 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5678 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5679 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5680 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5683 * This is a delicate dance that we play here.
5684 * This hdr is in the ghost list so we access it
5685 * to move it out of the ghost list before we
5686 * initiate the read. If it's a prefetch then
5687 * it won't have a callback so we'll remove the
5688 * reference that arc_buf_alloc_impl() created. We
5689 * do this after we've called arc_access() to
5690 * avoid hitting an assert in remove_reference().
5692 arc_access(hdr, hash_lock);
5693 arc_hdr_alloc_pabd(hdr);
5695 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5696 size = arc_hdr_size(hdr);
5699 * If compression is enabled on the hdr, then will do
5700 * RAW I/O and will store the compressed data in the hdr's
5701 * data block. Otherwise, the hdr's data block will contain
5702 * the uncompressed data.
5704 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5705 zio_flags |= ZIO_FLAG_RAW;
5708 if (*arc_flags & ARC_FLAG_PREFETCH)
5709 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5710 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5711 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5713 if (*arc_flags & ARC_FLAG_L2CACHE)
5714 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5715 if (BP_GET_LEVEL(bp) > 0)
5716 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5717 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5718 arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5719 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5721 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5722 acb->acb_done = done;
5723 acb->acb_private = private;
5724 acb->acb_compressed = compressed_read;
5726 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5727 hdr->b_l1hdr.b_acb = acb;
5728 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5730 if (HDR_HAS_L2HDR(hdr) &&
5731 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5732 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5733 addr = hdr->b_l2hdr.b_daddr;
5735 * Lock out L2ARC device removal.
5737 if (vdev_is_dead(vd) ||
5738 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5743 * We count both async reads and scrub IOs as asynchronous so
5744 * that both can be upgraded in the event of a cache hit while
5745 * the read IO is still in-flight.
5747 if (priority == ZIO_PRIORITY_ASYNC_READ ||
5748 priority == ZIO_PRIORITY_SCRUB)
5749 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5751 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5754 * At this point, we have a level 1 cache miss. Try again in
5755 * L2ARC if possible.
5757 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5759 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5760 uint64_t, lsize, zbookmark_phys_t *, zb);
5761 ARCSTAT_BUMP(arcstat_misses);
5762 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5763 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5764 data, metadata, misses);
5769 racct_add_force(curproc, RACCT_READBPS, size);
5770 racct_add_force(curproc, RACCT_READIOPS, 1);
5771 PROC_UNLOCK(curproc);
5774 curthread->td_ru.ru_inblock++;
5777 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5779 * Read from the L2ARC if the following are true:
5780 * 1. The L2ARC vdev was previously cached.
5781 * 2. This buffer still has L2ARC metadata.
5782 * 3. This buffer isn't currently writing to the L2ARC.
5783 * 4. The L2ARC entry wasn't evicted, which may
5784 * also have invalidated the vdev.
5785 * 5. This isn't prefetch and l2arc_noprefetch is set.
5787 if (HDR_HAS_L2HDR(hdr) &&
5788 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5789 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5790 l2arc_read_callback_t *cb;
5794 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5795 ARCSTAT_BUMP(arcstat_l2_hits);
5797 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5799 cb->l2rcb_hdr = hdr;
5802 cb->l2rcb_flags = zio_flags;
5804 asize = vdev_psize_to_asize(vd, size);
5805 if (asize != size) {
5806 abd = abd_alloc_for_io(asize,
5807 HDR_ISTYPE_METADATA(hdr));
5808 cb->l2rcb_abd = abd;
5810 abd = hdr->b_l1hdr.b_pabd;
5813 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5814 addr + asize <= vd->vdev_psize -
5815 VDEV_LABEL_END_SIZE);
5818 * l2arc read. The SCL_L2ARC lock will be
5819 * released by l2arc_read_done().
5820 * Issue a null zio if the underlying buffer
5821 * was squashed to zero size by compression.
5823 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5824 ZIO_COMPRESS_EMPTY);
5825 rzio = zio_read_phys(pio, vd, addr,
5828 l2arc_read_done, cb, priority,
5829 zio_flags | ZIO_FLAG_DONT_CACHE |
5831 ZIO_FLAG_DONT_PROPAGATE |
5832 ZIO_FLAG_DONT_RETRY, B_FALSE);
5833 acb->acb_zio_head = rzio;
5835 if (hash_lock != NULL)
5836 mutex_exit(hash_lock);
5838 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5840 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5842 if (*arc_flags & ARC_FLAG_NOWAIT) {
5847 ASSERT(*arc_flags & ARC_FLAG_WAIT);
5848 if (zio_wait(rzio) == 0)
5851 /* l2arc read error; goto zio_read() */
5852 if (hash_lock != NULL)
5853 mutex_enter(hash_lock);
5855 DTRACE_PROBE1(l2arc__miss,
5856 arc_buf_hdr_t *, hdr);
5857 ARCSTAT_BUMP(arcstat_l2_misses);
5858 if (HDR_L2_WRITING(hdr))
5859 ARCSTAT_BUMP(arcstat_l2_rw_clash);
5860 spa_config_exit(spa, SCL_L2ARC, vd);
5864 spa_config_exit(spa, SCL_L2ARC, vd);
5865 if (l2arc_ndev != 0) {
5866 DTRACE_PROBE1(l2arc__miss,
5867 arc_buf_hdr_t *, hdr);
5868 ARCSTAT_BUMP(arcstat_l2_misses);
5872 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5873 arc_read_done, hdr, priority, zio_flags, zb);
5874 acb->acb_zio_head = rzio;
5876 if (hash_lock != NULL)
5877 mutex_exit(hash_lock);
5879 if (*arc_flags & ARC_FLAG_WAIT)
5880 return (zio_wait(rzio));
5882 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5889 arc_add_prune_callback(arc_prune_func_t *func, void *private)
5893 p = kmem_alloc(sizeof (*p), KM_SLEEP);
5895 p->p_private = private;
5896 list_link_init(&p->p_node);
5897 refcount_create(&p->p_refcnt);
5899 mutex_enter(&arc_prune_mtx);
5900 refcount_add(&p->p_refcnt, &arc_prune_list);
5901 list_insert_head(&arc_prune_list, p);
5902 mutex_exit(&arc_prune_mtx);
5908 arc_remove_prune_callback(arc_prune_t *p)
5910 boolean_t wait = B_FALSE;
5911 mutex_enter(&arc_prune_mtx);
5912 list_remove(&arc_prune_list, p);
5913 if (refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
5915 mutex_exit(&arc_prune_mtx);
5917 /* wait for arc_prune_task to finish */
5919 taskq_wait(arc_prune_taskq);
5920 ASSERT0(refcount_count(&p->p_refcnt));
5921 refcount_destroy(&p->p_refcnt);
5922 kmem_free(p, sizeof (*p));
5926 * Notify the arc that a block was freed, and thus will never be used again.
5929 arc_freed(spa_t *spa, const blkptr_t *bp)
5932 kmutex_t *hash_lock;
5933 uint64_t guid = spa_load_guid(spa);
5935 ASSERT(!BP_IS_EMBEDDED(bp));
5937 hdr = buf_hash_find(guid, bp, &hash_lock);
5942 * We might be trying to free a block that is still doing I/O
5943 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5944 * dmu_sync-ed block). If this block is being prefetched, then it
5945 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5946 * until the I/O completes. A block may also have a reference if it is
5947 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5948 * have written the new block to its final resting place on disk but
5949 * without the dedup flag set. This would have left the hdr in the MRU
5950 * state and discoverable. When the txg finally syncs it detects that
5951 * the block was overridden in open context and issues an override I/O.
5952 * Since this is a dedup block, the override I/O will determine if the
5953 * block is already in the DDT. If so, then it will replace the io_bp
5954 * with the bp from the DDT and allow the I/O to finish. When the I/O
5955 * reaches the done callback, dbuf_write_override_done, it will
5956 * check to see if the io_bp and io_bp_override are identical.
5957 * If they are not, then it indicates that the bp was replaced with
5958 * the bp in the DDT and the override bp is freed. This allows
5959 * us to arrive here with a reference on a block that is being
5960 * freed. So if we have an I/O in progress, or a reference to
5961 * this hdr, then we don't destroy the hdr.
5963 if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5964 refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5965 arc_change_state(arc_anon, hdr, hash_lock);
5966 arc_hdr_destroy(hdr);
5967 mutex_exit(hash_lock);
5969 mutex_exit(hash_lock);
5975 * Release this buffer from the cache, making it an anonymous buffer. This
5976 * must be done after a read and prior to modifying the buffer contents.
5977 * If the buffer has more than one reference, we must make
5978 * a new hdr for the buffer.
5981 arc_release(arc_buf_t *buf, void *tag)
5983 arc_buf_hdr_t *hdr = buf->b_hdr;
5986 * It would be nice to assert that if it's DMU metadata (level >
5987 * 0 || it's the dnode file), then it must be syncing context.
5988 * But we don't know that information at this level.
5991 mutex_enter(&buf->b_evict_lock);
5993 ASSERT(HDR_HAS_L1HDR(hdr));
5996 * We don't grab the hash lock prior to this check, because if
5997 * the buffer's header is in the arc_anon state, it won't be
5998 * linked into the hash table.
6000 if (hdr->b_l1hdr.b_state == arc_anon) {
6001 mutex_exit(&buf->b_evict_lock);
6002 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6003 ASSERT(!HDR_IN_HASH_TABLE(hdr));
6004 ASSERT(!HDR_HAS_L2HDR(hdr));
6005 ASSERT(HDR_EMPTY(hdr));
6006 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6007 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6008 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6010 hdr->b_l1hdr.b_arc_access = 0;
6013 * If the buf is being overridden then it may already
6014 * have a hdr that is not empty.
6016 buf_discard_identity(hdr);
6022 kmutex_t *hash_lock = HDR_LOCK(hdr);
6023 mutex_enter(hash_lock);
6026 * This assignment is only valid as long as the hash_lock is
6027 * held, we must be careful not to reference state or the
6028 * b_state field after dropping the lock.
6030 arc_state_t *state = hdr->b_l1hdr.b_state;
6031 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6032 ASSERT3P(state, !=, arc_anon);
6034 /* this buffer is not on any list */
6035 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6037 if (HDR_HAS_L2HDR(hdr)) {
6038 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6041 * We have to recheck this conditional again now that
6042 * we're holding the l2ad_mtx to prevent a race with
6043 * another thread which might be concurrently calling
6044 * l2arc_evict(). In that case, l2arc_evict() might have
6045 * destroyed the header's L2 portion as we were waiting
6046 * to acquire the l2ad_mtx.
6048 if (HDR_HAS_L2HDR(hdr)) {
6050 arc_hdr_l2hdr_destroy(hdr);
6053 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6057 * Do we have more than one buf?
6059 if (hdr->b_l1hdr.b_bufcnt > 1) {
6060 arc_buf_hdr_t *nhdr;
6061 uint64_t spa = hdr->b_spa;
6062 uint64_t psize = HDR_GET_PSIZE(hdr);
6063 uint64_t lsize = HDR_GET_LSIZE(hdr);
6064 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
6065 arc_buf_contents_t type = arc_buf_type(hdr);
6066 VERIFY3U(hdr->b_type, ==, type);
6068 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6069 (void) remove_reference(hdr, hash_lock, tag);
6071 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6072 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6073 ASSERT(ARC_BUF_LAST(buf));
6077 * Pull the data off of this hdr and attach it to
6078 * a new anonymous hdr. Also find the last buffer
6079 * in the hdr's buffer list.
6081 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6082 ASSERT3P(lastbuf, !=, NULL);
6085 * If the current arc_buf_t and the hdr are sharing their data
6086 * buffer, then we must stop sharing that block.
6088 if (arc_buf_is_shared(buf)) {
6089 VERIFY(!arc_buf_is_shared(lastbuf));
6092 * First, sever the block sharing relationship between
6093 * buf and the arc_buf_hdr_t.
6095 arc_unshare_buf(hdr, buf);
6098 * Now we need to recreate the hdr's b_pabd. Since we
6099 * have lastbuf handy, we try to share with it, but if
6100 * we can't then we allocate a new b_pabd and copy the
6101 * data from buf into it.
6103 if (arc_can_share(hdr, lastbuf)) {
6104 arc_share_buf(hdr, lastbuf);
6106 arc_hdr_alloc_pabd(hdr);
6107 abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6108 buf->b_data, psize);
6110 VERIFY3P(lastbuf->b_data, !=, NULL);
6111 } else if (HDR_SHARED_DATA(hdr)) {
6113 * Uncompressed shared buffers are always at the end
6114 * of the list. Compressed buffers don't have the
6115 * same requirements. This makes it hard to
6116 * simply assert that the lastbuf is shared so
6117 * we rely on the hdr's compression flags to determine
6118 * if we have a compressed, shared buffer.
6120 ASSERT(arc_buf_is_shared(lastbuf) ||
6121 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
6122 ASSERT(!ARC_BUF_SHARED(buf));
6124 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6125 ASSERT3P(state, !=, arc_l2c_only);
6127 (void) refcount_remove_many(&state->arcs_size,
6128 arc_buf_size(buf), buf);
6130 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6131 ASSERT3P(state, !=, arc_l2c_only);
6132 (void) refcount_remove_many(&state->arcs_esize[type],
6133 arc_buf_size(buf), buf);
6136 hdr->b_l1hdr.b_bufcnt -= 1;
6137 arc_cksum_verify(buf);
6139 arc_buf_unwatch(buf);
6142 mutex_exit(hash_lock);
6145 * Allocate a new hdr. The new hdr will contain a b_pabd
6146 * buffer which will be freed in arc_write().
6148 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
6149 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6150 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6151 ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
6152 VERIFY3U(nhdr->b_type, ==, type);
6153 ASSERT(!HDR_SHARED_DATA(nhdr));
6155 nhdr->b_l1hdr.b_buf = buf;
6156 nhdr->b_l1hdr.b_bufcnt = 1;
6157 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6160 mutex_exit(&buf->b_evict_lock);
6161 (void) refcount_add_many(&arc_anon->arcs_size,
6162 arc_buf_size(buf), buf);
6164 mutex_exit(&buf->b_evict_lock);
6165 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6166 /* protected by hash lock, or hdr is on arc_anon */
6167 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6168 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6169 arc_change_state(arc_anon, hdr, hash_lock);
6170 hdr->b_l1hdr.b_arc_access = 0;
6171 mutex_exit(hash_lock);
6173 buf_discard_identity(hdr);
6179 arc_released(arc_buf_t *buf)
6183 mutex_enter(&buf->b_evict_lock);
6184 released = (buf->b_data != NULL &&
6185 buf->b_hdr->b_l1hdr.b_state == arc_anon);
6186 mutex_exit(&buf->b_evict_lock);
6192 arc_referenced(arc_buf_t *buf)
6196 mutex_enter(&buf->b_evict_lock);
6197 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6198 mutex_exit(&buf->b_evict_lock);
6199 return (referenced);
6204 arc_write_ready(zio_t *zio)
6206 arc_write_callback_t *callback = zio->io_private;
6207 arc_buf_t *buf = callback->awcb_buf;
6208 arc_buf_hdr_t *hdr = buf->b_hdr;
6209 uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
6211 ASSERT(HDR_HAS_L1HDR(hdr));
6212 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6213 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6216 * If we're reexecuting this zio because the pool suspended, then
6217 * cleanup any state that was previously set the first time the
6218 * callback was invoked.
6220 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6221 arc_cksum_free(hdr);
6223 arc_buf_unwatch(buf);
6225 if (hdr->b_l1hdr.b_pabd != NULL) {
6226 if (arc_buf_is_shared(buf)) {
6227 arc_unshare_buf(hdr, buf);
6229 arc_hdr_free_pabd(hdr);
6233 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6234 ASSERT(!HDR_SHARED_DATA(hdr));
6235 ASSERT(!arc_buf_is_shared(buf));
6237 callback->awcb_ready(zio, buf, callback->awcb_private);
6239 if (HDR_IO_IN_PROGRESS(hdr))
6240 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6242 arc_cksum_compute(buf);
6243 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6245 enum zio_compress compress;
6246 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6247 compress = ZIO_COMPRESS_OFF;
6249 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
6250 compress = BP_GET_COMPRESS(zio->io_bp);
6252 HDR_SET_PSIZE(hdr, psize);
6253 arc_hdr_set_compress(hdr, compress);
6257 * Fill the hdr with data. If the hdr is compressed, the data we want
6258 * is available from the zio, otherwise we can take it from the buf.
6260 * We might be able to share the buf's data with the hdr here. However,
6261 * doing so would cause the ARC to be full of linear ABDs if we write a
6262 * lot of shareable data. As a compromise, we check whether scattered
6263 * ABDs are allowed, and assume that if they are then the user wants
6264 * the ARC to be primarily filled with them regardless of the data being
6265 * written. Therefore, if they're allowed then we allocate one and copy
6266 * the data into it; otherwise, we share the data directly if we can.
6268 if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6269 arc_hdr_alloc_pabd(hdr);
6272 * Ideally, we would always copy the io_abd into b_pabd, but the
6273 * user may have disabled compressed ARC, thus we must check the
6274 * hdr's compression setting rather than the io_bp's.
6276 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
6277 ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
6279 ASSERT3U(psize, >, 0);
6281 abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6283 ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6285 abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6289 ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6290 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6291 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6293 arc_share_buf(hdr, buf);
6296 arc_hdr_verify(hdr, zio->io_bp);
6300 arc_write_children_ready(zio_t *zio)
6302 arc_write_callback_t *callback = zio->io_private;
6303 arc_buf_t *buf = callback->awcb_buf;
6305 callback->awcb_children_ready(zio, buf, callback->awcb_private);
6309 * The SPA calls this callback for each physical write that happens on behalf
6310 * of a logical write. See the comment in dbuf_write_physdone() for details.
6313 arc_write_physdone(zio_t *zio)
6315 arc_write_callback_t *cb = zio->io_private;
6316 if (cb->awcb_physdone != NULL)
6317 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6321 arc_write_done(zio_t *zio)
6323 arc_write_callback_t *callback = zio->io_private;
6324 arc_buf_t *buf = callback->awcb_buf;
6325 arc_buf_hdr_t *hdr = buf->b_hdr;
6327 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6329 if (zio->io_error == 0) {
6330 arc_hdr_verify(hdr, zio->io_bp);
6332 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6333 buf_discard_identity(hdr);
6335 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6336 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6339 ASSERT(HDR_EMPTY(hdr));
6343 * If the block to be written was all-zero or compressed enough to be
6344 * embedded in the BP, no write was performed so there will be no
6345 * dva/birth/checksum. The buffer must therefore remain anonymous
6348 if (!HDR_EMPTY(hdr)) {
6349 arc_buf_hdr_t *exists;
6350 kmutex_t *hash_lock;
6352 ASSERT3U(zio->io_error, ==, 0);
6354 arc_cksum_verify(buf);
6356 exists = buf_hash_insert(hdr, &hash_lock);
6357 if (exists != NULL) {
6359 * This can only happen if we overwrite for
6360 * sync-to-convergence, because we remove
6361 * buffers from the hash table when we arc_free().
6363 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6364 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6365 panic("bad overwrite, hdr=%p exists=%p",
6366 (void *)hdr, (void *)exists);
6367 ASSERT(refcount_is_zero(
6368 &exists->b_l1hdr.b_refcnt));
6369 arc_change_state(arc_anon, exists, hash_lock);
6370 mutex_exit(hash_lock);
6371 arc_hdr_destroy(exists);
6372 exists = buf_hash_insert(hdr, &hash_lock);
6373 ASSERT3P(exists, ==, NULL);
6374 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6376 ASSERT(zio->io_prop.zp_nopwrite);
6377 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6378 panic("bad nopwrite, hdr=%p exists=%p",
6379 (void *)hdr, (void *)exists);
6382 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6383 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6384 ASSERT(BP_GET_DEDUP(zio->io_bp));
6385 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6388 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6389 /* if it's not anon, we are doing a scrub */
6390 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6391 arc_access(hdr, hash_lock);
6392 mutex_exit(hash_lock);
6394 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6397 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6398 callback->awcb_done(zio, buf, callback->awcb_private);
6400 abd_put(zio->io_abd);
6401 kmem_free(callback, sizeof (arc_write_callback_t));
6405 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6406 boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6407 arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6408 arc_write_done_func_t *done, void *private, zio_priority_t priority,
6409 int zio_flags, const zbookmark_phys_t *zb)
6411 arc_buf_hdr_t *hdr = buf->b_hdr;
6412 arc_write_callback_t *callback;
6414 zio_prop_t localprop = *zp;
6416 ASSERT3P(ready, !=, NULL);
6417 ASSERT3P(done, !=, NULL);
6418 ASSERT(!HDR_IO_ERROR(hdr));
6419 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6420 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6421 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6423 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6424 if (ARC_BUF_COMPRESSED(buf)) {
6426 * We're writing a pre-compressed buffer. Make the
6427 * compression algorithm requested by the zio_prop_t match
6428 * the pre-compressed buffer's compression algorithm.
6430 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6432 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6433 zio_flags |= ZIO_FLAG_RAW;
6435 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6436 callback->awcb_ready = ready;
6437 callback->awcb_children_ready = children_ready;
6438 callback->awcb_physdone = physdone;
6439 callback->awcb_done = done;
6440 callback->awcb_private = private;
6441 callback->awcb_buf = buf;
6444 * The hdr's b_pabd is now stale, free it now. A new data block
6445 * will be allocated when the zio pipeline calls arc_write_ready().
6447 if (hdr->b_l1hdr.b_pabd != NULL) {
6449 * If the buf is currently sharing the data block with
6450 * the hdr then we need to break that relationship here.
6451 * The hdr will remain with a NULL data pointer and the
6452 * buf will take sole ownership of the block.
6454 if (arc_buf_is_shared(buf)) {
6455 arc_unshare_buf(hdr, buf);
6457 arc_hdr_free_pabd(hdr);
6459 VERIFY3P(buf->b_data, !=, NULL);
6460 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6462 ASSERT(!arc_buf_is_shared(buf));
6463 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6465 zio = zio_write(pio, spa, txg, bp,
6466 abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6467 HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6468 (children_ready != NULL) ? arc_write_children_ready : NULL,
6469 arc_write_physdone, arc_write_done, callback,
6470 priority, zio_flags, zb);
6476 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
6479 uint64_t available_memory = ptob(freemem);
6481 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
6482 available_memory = MIN(available_memory, uma_avail());
6485 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
6488 if (txg > spa->spa_lowmem_last_txg) {
6489 spa->spa_lowmem_last_txg = txg;
6490 spa->spa_lowmem_page_load = 0;
6493 * If we are in pageout, we know that memory is already tight,
6494 * the arc is already going to be evicting, so we just want to
6495 * continue to let page writes occur as quickly as possible.
6497 if (curproc == pageproc) {
6498 if (spa->spa_lowmem_page_load >
6499 MAX(ptob(minfree), available_memory) / 4)
6500 return (SET_ERROR(ERESTART));
6501 /* Note: reserve is inflated, so we deflate */
6502 atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
6504 } else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
6505 /* memory is low, delay before restarting */
6506 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6507 return (SET_ERROR(EAGAIN));
6509 spa->spa_lowmem_page_load = 0;
6510 #endif /* _KERNEL */
6515 arc_tempreserve_clear(uint64_t reserve)
6517 atomic_add_64(&arc_tempreserve, -reserve);
6518 ASSERT((int64_t)arc_tempreserve >= 0);
6522 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
6527 if (reserve > arc_c/4 && !arc_no_grow) {
6528 arc_c = MIN(arc_c_max, reserve * 4);
6529 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
6531 if (reserve > arc_c)
6532 return (SET_ERROR(ENOMEM));
6535 * Don't count loaned bufs as in flight dirty data to prevent long
6536 * network delays from blocking transactions that are ready to be
6537 * assigned to a txg.
6540 /* assert that it has not wrapped around */
6541 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6543 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
6544 arc_loaned_bytes), 0);
6547 * Writes will, almost always, require additional memory allocations
6548 * in order to compress/encrypt/etc the data. We therefore need to
6549 * make sure that there is sufficient available memory for this.
6551 error = arc_memory_throttle(spa, reserve, txg);
6556 * Throttle writes when the amount of dirty data in the cache
6557 * gets too large. We try to keep the cache less than half full
6558 * of dirty blocks so that our sync times don't grow too large.
6560 * In the case of one pool being built on another pool, we want
6561 * to make sure we don't end up throttling the lower (backing)
6562 * pool when the upper pool is the majority contributor to dirty
6563 * data. To insure we make forward progress during throttling, we
6564 * also check the current pool's net dirty data and only throttle
6565 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6566 * data in the cache.
6568 * Note: if two requests come in concurrently, we might let them
6569 * both succeed, when one of them should fail. Not a huge deal.
6571 uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6572 uint64_t spa_dirty_anon = spa_dirty_data(spa);
6574 if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
6575 anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
6576 spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
6577 uint64_t meta_esize =
6578 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6579 uint64_t data_esize =
6580 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6581 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6582 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6583 arc_tempreserve >> 10, meta_esize >> 10,
6584 data_esize >> 10, reserve >> 10, arc_c >> 10);
6585 return (SET_ERROR(ERESTART));
6587 atomic_add_64(&arc_tempreserve, reserve);
6592 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6593 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6595 size->value.ui64 = refcount_count(&state->arcs_size);
6596 evict_data->value.ui64 =
6597 refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6598 evict_metadata->value.ui64 =
6599 refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6603 arc_kstat_update(kstat_t *ksp, int rw)
6605 arc_stats_t *as = ksp->ks_data;
6607 if (rw == KSTAT_WRITE) {
6610 arc_kstat_update_state(arc_anon,
6611 &as->arcstat_anon_size,
6612 &as->arcstat_anon_evictable_data,
6613 &as->arcstat_anon_evictable_metadata);
6614 arc_kstat_update_state(arc_mru,
6615 &as->arcstat_mru_size,
6616 &as->arcstat_mru_evictable_data,
6617 &as->arcstat_mru_evictable_metadata);
6618 arc_kstat_update_state(arc_mru_ghost,
6619 &as->arcstat_mru_ghost_size,
6620 &as->arcstat_mru_ghost_evictable_data,
6621 &as->arcstat_mru_ghost_evictable_metadata);
6622 arc_kstat_update_state(arc_mfu,
6623 &as->arcstat_mfu_size,
6624 &as->arcstat_mfu_evictable_data,
6625 &as->arcstat_mfu_evictable_metadata);
6626 arc_kstat_update_state(arc_mfu_ghost,
6627 &as->arcstat_mfu_ghost_size,
6628 &as->arcstat_mfu_ghost_evictable_data,
6629 &as->arcstat_mfu_ghost_evictable_metadata);
6631 ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6632 ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6633 ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6634 ARCSTAT(arcstat_metadata_size) =
6635 aggsum_value(&astat_metadata_size);
6636 ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6637 ARCSTAT(arcstat_bonus_size) = aggsum_value(&astat_bonus_size);
6638 ARCSTAT(arcstat_dnode_size) = aggsum_value(&astat_dnode_size);
6639 ARCSTAT(arcstat_dbuf_size) = aggsum_value(&astat_dbuf_size);
6640 ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6647 * This function *must* return indices evenly distributed between all
6648 * sublists of the multilist. This is needed due to how the ARC eviction
6649 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6650 * distributed between all sublists and uses this assumption when
6651 * deciding which sublist to evict from and how much to evict from it.
6654 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6656 arc_buf_hdr_t *hdr = obj;
6659 * We rely on b_dva to generate evenly distributed index
6660 * numbers using buf_hash below. So, as an added precaution,
6661 * let's make sure we never add empty buffers to the arc lists.
6663 ASSERT(!HDR_EMPTY(hdr));
6666 * The assumption here, is the hash value for a given
6667 * arc_buf_hdr_t will remain constant throughout it's lifetime
6668 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6669 * Thus, we don't need to store the header's sublist index
6670 * on insertion, as this index can be recalculated on removal.
6672 * Also, the low order bits of the hash value are thought to be
6673 * distributed evenly. Otherwise, in the case that the multilist
6674 * has a power of two number of sublists, each sublists' usage
6675 * would not be evenly distributed.
6677 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6678 multilist_get_num_sublists(ml));
6682 static eventhandler_tag arc_event_lowmem = NULL;
6685 arc_lowmem(void *arg __unused, int howto __unused)
6688 mutex_enter(&arc_reclaim_lock);
6689 DTRACE_PROBE1(arc__needfree, int64_t, ((int64_t)freemem - zfs_arc_free_target) * PAGESIZE);
6690 cv_signal(&arc_reclaim_thread_cv);
6693 * It is unsafe to block here in arbitrary threads, because we can come
6694 * here from ARC itself and may hold ARC locks and thus risk a deadlock
6695 * with ARC reclaim thread.
6697 if (curproc == pageproc)
6698 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
6699 mutex_exit(&arc_reclaim_lock);
6704 arc_state_init(void)
6706 arc_anon = &ARC_anon;
6708 arc_mru_ghost = &ARC_mru_ghost;
6710 arc_mfu_ghost = &ARC_mfu_ghost;
6711 arc_l2c_only = &ARC_l2c_only;
6713 arc_mru->arcs_list[ARC_BUFC_METADATA] =
6714 multilist_create(sizeof (arc_buf_hdr_t),
6715 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6716 arc_state_multilist_index_func);
6717 arc_mru->arcs_list[ARC_BUFC_DATA] =
6718 multilist_create(sizeof (arc_buf_hdr_t),
6719 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6720 arc_state_multilist_index_func);
6721 arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6722 multilist_create(sizeof (arc_buf_hdr_t),
6723 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6724 arc_state_multilist_index_func);
6725 arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6726 multilist_create(sizeof (arc_buf_hdr_t),
6727 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6728 arc_state_multilist_index_func);
6729 arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6730 multilist_create(sizeof (arc_buf_hdr_t),
6731 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6732 arc_state_multilist_index_func);
6733 arc_mfu->arcs_list[ARC_BUFC_DATA] =
6734 multilist_create(sizeof (arc_buf_hdr_t),
6735 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6736 arc_state_multilist_index_func);
6737 arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6738 multilist_create(sizeof (arc_buf_hdr_t),
6739 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6740 arc_state_multilist_index_func);
6741 arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6742 multilist_create(sizeof (arc_buf_hdr_t),
6743 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6744 arc_state_multilist_index_func);
6745 arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6746 multilist_create(sizeof (arc_buf_hdr_t),
6747 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6748 arc_state_multilist_index_func);
6749 arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6750 multilist_create(sizeof (arc_buf_hdr_t),
6751 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6752 arc_state_multilist_index_func);
6754 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6755 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6756 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6757 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6758 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6759 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6760 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6761 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6762 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6763 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6764 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6765 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6767 refcount_create(&arc_anon->arcs_size);
6768 refcount_create(&arc_mru->arcs_size);
6769 refcount_create(&arc_mru_ghost->arcs_size);
6770 refcount_create(&arc_mfu->arcs_size);
6771 refcount_create(&arc_mfu_ghost->arcs_size);
6772 refcount_create(&arc_l2c_only->arcs_size);
6774 aggsum_init(&arc_meta_used, 0);
6775 aggsum_init(&arc_size, 0);
6776 aggsum_init(&astat_data_size, 0);
6777 aggsum_init(&astat_metadata_size, 0);
6778 aggsum_init(&astat_hdr_size, 0);
6779 aggsum_init(&astat_bonus_size, 0);
6780 aggsum_init(&astat_dnode_size, 0);
6781 aggsum_init(&astat_dbuf_size, 0);
6782 aggsum_init(&astat_l2_hdr_size, 0);
6786 arc_state_fini(void)
6788 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6789 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6790 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6791 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6792 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6793 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6794 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6795 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6796 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6797 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6798 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6799 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6801 refcount_destroy(&arc_anon->arcs_size);
6802 refcount_destroy(&arc_mru->arcs_size);
6803 refcount_destroy(&arc_mru_ghost->arcs_size);
6804 refcount_destroy(&arc_mfu->arcs_size);
6805 refcount_destroy(&arc_mfu_ghost->arcs_size);
6806 refcount_destroy(&arc_l2c_only->arcs_size);
6808 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6809 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6810 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6811 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
6812 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
6813 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
6814 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
6815 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6827 int i, prefetch_tunable_set = 0;
6830 * allmem is "all memory that we could possibly use".
6834 uint64_t allmem = ptob(physmem - swapfs_minfree);
6836 uint64_t allmem = (physmem * PAGESIZE) / 2;
6839 uint64_t allmem = kmem_size();
6843 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
6844 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
6845 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
6847 mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
6848 cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
6850 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
6851 arc_c_min = MAX(allmem / 32, arc_abs_min);
6852 /* set max to 5/8 of all memory, or all but 1GB, whichever is more */
6853 if (allmem >= 1 << 30)
6854 arc_c_max = allmem - (1 << 30);
6856 arc_c_max = arc_c_min;
6857 arc_c_max = MAX(allmem * 5 / 8, arc_c_max);
6860 * In userland, there's only the memory pressure that we artificially
6861 * create (see arc_available_memory()). Don't let arc_c get too
6862 * small, because it can cause transactions to be larger than
6863 * arc_c, causing arc_tempreserve_space() to fail.
6866 arc_c_min = arc_c_max / 2;
6871 * Allow the tunables to override our calculations if they are
6874 if (zfs_arc_max > arc_abs_min && zfs_arc_max < allmem) {
6875 arc_c_max = zfs_arc_max;
6876 arc_c_min = MIN(arc_c_min, arc_c_max);
6878 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
6879 arc_c_min = zfs_arc_min;
6883 arc_p = (arc_c >> 1);
6885 /* limit meta-data to 1/4 of the arc capacity */
6886 arc_meta_limit = arc_c_max / 4;
6890 * Metadata is stored in the kernel's heap. Don't let us
6891 * use more than half the heap for the ARC.
6894 arc_meta_limit = MIN(arc_meta_limit, uma_limit() / 2);
6895 arc_dnode_limit = arc_meta_limit / 10;
6897 arc_meta_limit = MIN(arc_meta_limit,
6898 vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6902 /* Allow the tunable to override if it is reasonable */
6903 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6904 arc_meta_limit = zfs_arc_meta_limit;
6906 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6907 arc_c_min = arc_meta_limit / 2;
6909 if (zfs_arc_meta_min > 0) {
6910 arc_meta_min = zfs_arc_meta_min;
6912 arc_meta_min = arc_c_min / 2;
6915 /* Valid range: <arc_meta_min> - <arc_c_max> */
6916 if ((zfs_arc_dnode_limit) && (zfs_arc_dnode_limit != arc_dnode_limit) &&
6917 (zfs_arc_dnode_limit >= zfs_arc_meta_min) &&
6918 (zfs_arc_dnode_limit <= arc_c_max))
6919 arc_dnode_limit = zfs_arc_dnode_limit;
6921 if (zfs_arc_grow_retry > 0)
6922 arc_grow_retry = zfs_arc_grow_retry;
6924 if (zfs_arc_shrink_shift > 0)
6925 arc_shrink_shift = zfs_arc_shrink_shift;
6927 if (zfs_arc_no_grow_shift > 0)
6928 arc_no_grow_shift = zfs_arc_no_grow_shift;
6930 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6932 if (arc_no_grow_shift >= arc_shrink_shift)
6933 arc_no_grow_shift = arc_shrink_shift - 1;
6935 if (zfs_arc_p_min_shift > 0)
6936 arc_p_min_shift = zfs_arc_p_min_shift;
6938 /* if kmem_flags are set, lets try to use less memory */
6939 if (kmem_debugging())
6941 if (arc_c < arc_c_min)
6944 zfs_arc_min = arc_c_min;
6945 zfs_arc_max = arc_c_max;
6950 list_create(&arc_prune_list, sizeof (arc_prune_t),
6951 offsetof(arc_prune_t, p_node));
6952 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
6954 arc_prune_taskq = taskq_create("arc_prune", max_ncpus, minclsyspri,
6955 max_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
6957 arc_reclaim_thread_exit = B_FALSE;
6958 arc_dnlc_evicts_thread_exit = FALSE;
6960 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6961 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6963 if (arc_ksp != NULL) {
6964 arc_ksp->ks_data = &arc_stats;
6965 arc_ksp->ks_update = arc_kstat_update;
6966 kstat_install(arc_ksp);
6969 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6970 TS_RUN, minclsyspri);
6973 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
6974 EVENTHANDLER_PRI_FIRST);
6977 (void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
6978 TS_RUN, minclsyspri);
6984 * Calculate maximum amount of dirty data per pool.
6986 * If it has been set by /etc/system, take that.
6987 * Otherwise, use a percentage of physical memory defined by
6988 * zfs_dirty_data_max_percent (default 10%) with a cap at
6989 * zfs_dirty_data_max_max (default 4GB).
6991 if (zfs_dirty_data_max == 0) {
6992 zfs_dirty_data_max = ptob(physmem) *
6993 zfs_dirty_data_max_percent / 100;
6994 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6995 zfs_dirty_data_max_max);
6999 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
7000 prefetch_tunable_set = 1;
7003 if (prefetch_tunable_set == 0) {
7004 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
7006 printf(" add \"vfs.zfs.prefetch_disable=0\" "
7007 "to /boot/loader.conf.\n");
7008 zfs_prefetch_disable = 1;
7011 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
7012 prefetch_tunable_set == 0) {
7013 printf("ZFS NOTICE: Prefetch is disabled by default if less "
7014 "than 4GB of RAM is present;\n"
7015 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
7016 "to /boot/loader.conf.\n");
7017 zfs_prefetch_disable = 1;
7020 /* Warn about ZFS memory and address space requirements. */
7021 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
7022 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
7023 "expect unstable behavior.\n");
7025 if (allmem < 512 * (1 << 20)) {
7026 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
7027 "expect unstable behavior.\n");
7028 printf(" Consider tuning vm.kmem_size and "
7029 "vm.kmem_size_max\n");
7030 printf(" in /boot/loader.conf.\n");
7041 if (arc_event_lowmem != NULL)
7042 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
7045 mutex_enter(&arc_reclaim_lock);
7046 arc_reclaim_thread_exit = B_TRUE;
7048 * The reclaim thread will set arc_reclaim_thread_exit back to
7049 * B_FALSE when it is finished exiting; we're waiting for that.
7051 while (arc_reclaim_thread_exit) {
7052 cv_signal(&arc_reclaim_thread_cv);
7053 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
7055 mutex_exit(&arc_reclaim_lock);
7057 /* Use B_TRUE to ensure *all* buffers are evicted */
7058 arc_flush(NULL, B_TRUE);
7060 mutex_enter(&arc_dnlc_evicts_lock);
7061 arc_dnlc_evicts_thread_exit = TRUE;
7063 * The user evicts thread will set arc_user_evicts_thread_exit
7064 * to FALSE when it is finished exiting; we're waiting for that.
7066 while (arc_dnlc_evicts_thread_exit) {
7067 cv_signal(&arc_dnlc_evicts_cv);
7068 cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
7070 mutex_exit(&arc_dnlc_evicts_lock);
7074 if (arc_ksp != NULL) {
7075 kstat_delete(arc_ksp);
7079 taskq_wait(arc_prune_taskq);
7080 taskq_destroy(arc_prune_taskq);
7082 mutex_enter(&arc_prune_mtx);
7083 while ((p = list_head(&arc_prune_list)) != NULL) {
7084 list_remove(&arc_prune_list, p);
7085 refcount_remove(&p->p_refcnt, &arc_prune_list);
7086 refcount_destroy(&p->p_refcnt);
7087 kmem_free(p, sizeof (*p));
7089 mutex_exit(&arc_prune_mtx);
7091 list_destroy(&arc_prune_list);
7092 mutex_destroy(&arc_prune_mtx);
7093 mutex_destroy(&arc_reclaim_lock);
7094 cv_destroy(&arc_reclaim_thread_cv);
7095 cv_destroy(&arc_reclaim_waiters_cv);
7097 mutex_destroy(&arc_dnlc_evicts_lock);
7098 cv_destroy(&arc_dnlc_evicts_cv);
7103 ASSERT0(arc_loaned_bytes);
7109 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7110 * It uses dedicated storage devices to hold cached data, which are populated
7111 * using large infrequent writes. The main role of this cache is to boost
7112 * the performance of random read workloads. The intended L2ARC devices
7113 * include short-stroked disks, solid state disks, and other media with
7114 * substantially faster read latency than disk.
7116 * +-----------------------+
7118 * +-----------------------+
7121 * l2arc_feed_thread() arc_read()
7125 * +---------------+ |
7127 * +---------------+ |
7132 * +-------+ +-------+
7134 * | cache | | cache |
7135 * +-------+ +-------+
7136 * +=========+ .-----.
7137 * : L2ARC : |-_____-|
7138 * : devices : | Disks |
7139 * +=========+ `-_____-'
7141 * Read requests are satisfied from the following sources, in order:
7144 * 2) vdev cache of L2ARC devices
7146 * 4) vdev cache of disks
7149 * Some L2ARC device types exhibit extremely slow write performance.
7150 * To accommodate for this there are some significant differences between
7151 * the L2ARC and traditional cache design:
7153 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
7154 * the ARC behave as usual, freeing buffers and placing headers on ghost
7155 * lists. The ARC does not send buffers to the L2ARC during eviction as
7156 * this would add inflated write latencies for all ARC memory pressure.
7158 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7159 * It does this by periodically scanning buffers from the eviction-end of
7160 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7161 * not already there. It scans until a headroom of buffers is satisfied,
7162 * which itself is a buffer for ARC eviction. If a compressible buffer is
7163 * found during scanning and selected for writing to an L2ARC device, we
7164 * temporarily boost scanning headroom during the next scan cycle to make
7165 * sure we adapt to compression effects (which might significantly reduce
7166 * the data volume we write to L2ARC). The thread that does this is
7167 * l2arc_feed_thread(), illustrated below; example sizes are included to
7168 * provide a better sense of ratio than this diagram:
7171 * +---------------------+----------+
7172 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
7173 * +---------------------+----------+ | o L2ARC eligible
7174 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
7175 * +---------------------+----------+ |
7176 * 15.9 Gbytes ^ 32 Mbytes |
7178 * l2arc_feed_thread()
7180 * l2arc write hand <--[oooo]--'
7184 * +==============================+
7185 * L2ARC dev |####|#|###|###| |####| ... |
7186 * +==============================+
7189 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7190 * evicted, then the L2ARC has cached a buffer much sooner than it probably
7191 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
7192 * safe to say that this is an uncommon case, since buffers at the end of
7193 * the ARC lists have moved there due to inactivity.
7195 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7196 * then the L2ARC simply misses copying some buffers. This serves as a
7197 * pressure valve to prevent heavy read workloads from both stalling the ARC
7198 * with waits and clogging the L2ARC with writes. This also helps prevent
7199 * the potential for the L2ARC to churn if it attempts to cache content too
7200 * quickly, such as during backups of the entire pool.
7202 * 5. After system boot and before the ARC has filled main memory, there are
7203 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7204 * lists can remain mostly static. Instead of searching from tail of these
7205 * lists as pictured, the l2arc_feed_thread() will search from the list heads
7206 * for eligible buffers, greatly increasing its chance of finding them.
7208 * The L2ARC device write speed is also boosted during this time so that
7209 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
7210 * there are no L2ARC reads, and no fear of degrading read performance
7211 * through increased writes.
7213 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7214 * the vdev queue can aggregate them into larger and fewer writes. Each
7215 * device is written to in a rotor fashion, sweeping writes through
7216 * available space then repeating.
7218 * 7. The L2ARC does not store dirty content. It never needs to flush
7219 * write buffers back to disk based storage.
7221 * 8. If an ARC buffer is written (and dirtied) which also exists in the
7222 * L2ARC, the now stale L2ARC buffer is immediately dropped.
7224 * The performance of the L2ARC can be tweaked by a number of tunables, which
7225 * may be necessary for different workloads:
7227 * l2arc_write_max max write bytes per interval
7228 * l2arc_write_boost extra write bytes during device warmup
7229 * l2arc_noprefetch skip caching prefetched buffers
7230 * l2arc_headroom number of max device writes to precache
7231 * l2arc_headroom_boost when we find compressed buffers during ARC
7232 * scanning, we multiply headroom by this
7233 * percentage factor for the next scan cycle,
7234 * since more compressed buffers are likely to
7236 * l2arc_feed_secs seconds between L2ARC writing
7238 * Tunables may be removed or added as future performance improvements are
7239 * integrated, and also may become zpool properties.
7241 * There are three key functions that control how the L2ARC warms up:
7243 * l2arc_write_eligible() check if a buffer is eligible to cache
7244 * l2arc_write_size() calculate how much to write
7245 * l2arc_write_interval() calculate sleep delay between writes
7247 * These three functions determine what to write, how much, and how quickly
7252 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7255 * A buffer is *not* eligible for the L2ARC if it:
7256 * 1. belongs to a different spa.
7257 * 2. is already cached on the L2ARC.
7258 * 3. has an I/O in progress (it may be an incomplete read).
7259 * 4. is flagged not eligible (zfs property).
7261 if (hdr->b_spa != spa_guid) {
7262 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
7265 if (HDR_HAS_L2HDR(hdr)) {
7266 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
7269 if (HDR_IO_IN_PROGRESS(hdr)) {
7270 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
7273 if (!HDR_L2CACHE(hdr)) {
7274 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
7282 l2arc_write_size(void)
7287 * Make sure our globals have meaningful values in case the user
7290 size = l2arc_write_max;
7292 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7293 "be greater than zero, resetting it to the default (%d)",
7295 size = l2arc_write_max = L2ARC_WRITE_SIZE;
7298 if (arc_warm == B_FALSE)
7299 size += l2arc_write_boost;
7306 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7308 clock_t interval, next, now;
7311 * If the ARC lists are busy, increase our write rate; if the
7312 * lists are stale, idle back. This is achieved by checking
7313 * how much we previously wrote - if it was more than half of
7314 * what we wanted, schedule the next write much sooner.
7316 if (l2arc_feed_again && wrote > (wanted / 2))
7317 interval = (hz * l2arc_feed_min_ms) / 1000;
7319 interval = hz * l2arc_feed_secs;
7321 now = ddi_get_lbolt();
7322 next = MAX(now, MIN(now + interval, began + interval));
7328 * Cycle through L2ARC devices. This is how L2ARC load balances.
7329 * If a device is returned, this also returns holding the spa config lock.
7331 static l2arc_dev_t *
7332 l2arc_dev_get_next(void)
7334 l2arc_dev_t *first, *next = NULL;
7337 * Lock out the removal of spas (spa_namespace_lock), then removal
7338 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
7339 * both locks will be dropped and a spa config lock held instead.
7341 mutex_enter(&spa_namespace_lock);
7342 mutex_enter(&l2arc_dev_mtx);
7344 /* if there are no vdevs, there is nothing to do */
7345 if (l2arc_ndev == 0)
7349 next = l2arc_dev_last;
7351 /* loop around the list looking for a non-faulted vdev */
7353 next = list_head(l2arc_dev_list);
7355 next = list_next(l2arc_dev_list, next);
7357 next = list_head(l2arc_dev_list);
7360 /* if we have come back to the start, bail out */
7363 else if (next == first)
7366 } while (vdev_is_dead(next->l2ad_vdev));
7368 /* if we were unable to find any usable vdevs, return NULL */
7369 if (vdev_is_dead(next->l2ad_vdev))
7372 l2arc_dev_last = next;
7375 mutex_exit(&l2arc_dev_mtx);
7378 * Grab the config lock to prevent the 'next' device from being
7379 * removed while we are writing to it.
7382 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7383 mutex_exit(&spa_namespace_lock);
7389 * Free buffers that were tagged for destruction.
7392 l2arc_do_free_on_write()
7395 l2arc_data_free_t *df, *df_prev;
7397 mutex_enter(&l2arc_free_on_write_mtx);
7398 buflist = l2arc_free_on_write;
7400 for (df = list_tail(buflist); df; df = df_prev) {
7401 df_prev = list_prev(buflist, df);
7402 ASSERT3P(df->l2df_abd, !=, NULL);
7403 abd_free(df->l2df_abd);
7404 list_remove(buflist, df);
7405 kmem_free(df, sizeof (l2arc_data_free_t));
7408 mutex_exit(&l2arc_free_on_write_mtx);
7412 * A write to a cache device has completed. Update all headers to allow
7413 * reads from these buffers to begin.
7416 l2arc_write_done(zio_t *zio)
7418 l2arc_write_callback_t *cb;
7421 arc_buf_hdr_t *head, *hdr, *hdr_prev;
7422 kmutex_t *hash_lock;
7423 int64_t bytes_dropped = 0;
7425 cb = zio->io_private;
7426 ASSERT3P(cb, !=, NULL);
7427 dev = cb->l2wcb_dev;
7428 ASSERT3P(dev, !=, NULL);
7429 head = cb->l2wcb_head;
7430 ASSERT3P(head, !=, NULL);
7431 buflist = &dev->l2ad_buflist;
7432 ASSERT3P(buflist, !=, NULL);
7433 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7434 l2arc_write_callback_t *, cb);
7436 if (zio->io_error != 0)
7437 ARCSTAT_BUMP(arcstat_l2_writes_error);
7440 * All writes completed, or an error was hit.
7443 mutex_enter(&dev->l2ad_mtx);
7444 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7445 hdr_prev = list_prev(buflist, hdr);
7447 hash_lock = HDR_LOCK(hdr);
7450 * We cannot use mutex_enter or else we can deadlock
7451 * with l2arc_write_buffers (due to swapping the order
7452 * the hash lock and l2ad_mtx are taken).
7454 if (!mutex_tryenter(hash_lock)) {
7456 * Missed the hash lock. We must retry so we
7457 * don't leave the ARC_FLAG_L2_WRITING bit set.
7459 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7462 * We don't want to rescan the headers we've
7463 * already marked as having been written out, so
7464 * we reinsert the head node so we can pick up
7465 * where we left off.
7467 list_remove(buflist, head);
7468 list_insert_after(buflist, hdr, head);
7470 mutex_exit(&dev->l2ad_mtx);
7473 * We wait for the hash lock to become available
7474 * to try and prevent busy waiting, and increase
7475 * the chance we'll be able to acquire the lock
7476 * the next time around.
7478 mutex_enter(hash_lock);
7479 mutex_exit(hash_lock);
7484 * We could not have been moved into the arc_l2c_only
7485 * state while in-flight due to our ARC_FLAG_L2_WRITING
7486 * bit being set. Let's just ensure that's being enforced.
7488 ASSERT(HDR_HAS_L1HDR(hdr));
7490 if (zio->io_error != 0) {
7492 * Error - drop L2ARC entry.
7494 list_remove(buflist, hdr);
7496 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7498 ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
7499 ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
7501 bytes_dropped += arc_hdr_size(hdr);
7502 (void) refcount_remove_many(&dev->l2ad_alloc,
7503 arc_hdr_size(hdr), hdr);
7507 * Allow ARC to begin reads and ghost list evictions to
7510 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7512 mutex_exit(hash_lock);
7515 atomic_inc_64(&l2arc_writes_done);
7516 list_remove(buflist, head);
7517 ASSERT(!HDR_HAS_L1HDR(head));
7518 kmem_cache_free(hdr_l2only_cache, head);
7519 mutex_exit(&dev->l2ad_mtx);
7521 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7523 l2arc_do_free_on_write();
7525 kmem_free(cb, sizeof (l2arc_write_callback_t));
7529 * A read to a cache device completed. Validate buffer contents before
7530 * handing over to the regular ARC routines.
7533 l2arc_read_done(zio_t *zio)
7535 l2arc_read_callback_t *cb;
7537 kmutex_t *hash_lock;
7538 boolean_t valid_cksum;
7540 ASSERT3P(zio->io_vd, !=, NULL);
7541 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7543 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7545 cb = zio->io_private;
7546 ASSERT3P(cb, !=, NULL);
7547 hdr = cb->l2rcb_hdr;
7548 ASSERT3P(hdr, !=, NULL);
7550 hash_lock = HDR_LOCK(hdr);
7551 mutex_enter(hash_lock);
7552 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7555 * If the data was read into a temporary buffer,
7556 * move it and free the buffer.
7558 if (cb->l2rcb_abd != NULL) {
7559 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7560 if (zio->io_error == 0) {
7561 abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
7566 * The following must be done regardless of whether
7567 * there was an error:
7568 * - free the temporary buffer
7569 * - point zio to the real ARC buffer
7570 * - set zio size accordingly
7571 * These are required because zio is either re-used for
7572 * an I/O of the block in the case of the error
7573 * or the zio is passed to arc_read_done() and it
7576 abd_free(cb->l2rcb_abd);
7577 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7578 zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
7581 ASSERT3P(zio->io_abd, !=, NULL);
7584 * Check this survived the L2ARC journey.
7586 ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
7587 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
7588 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
7590 valid_cksum = arc_cksum_is_equal(hdr, zio);
7591 if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7592 mutex_exit(hash_lock);
7593 zio->io_private = hdr;
7596 mutex_exit(hash_lock);
7598 * Buffer didn't survive caching. Increment stats and
7599 * reissue to the original storage device.
7601 if (zio->io_error != 0) {
7602 ARCSTAT_BUMP(arcstat_l2_io_error);
7604 zio->io_error = SET_ERROR(EIO);
7607 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7610 * If there's no waiter, issue an async i/o to the primary
7611 * storage now. If there *is* a waiter, the caller must
7612 * issue the i/o in a context where it's OK to block.
7614 if (zio->io_waiter == NULL) {
7615 zio_t *pio = zio_unique_parent(zio);
7617 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7619 zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7620 hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
7621 hdr, zio->io_priority, cb->l2rcb_flags,
7626 kmem_free(cb, sizeof (l2arc_read_callback_t));
7630 * This is the list priority from which the L2ARC will search for pages to
7631 * cache. This is used within loops (0..3) to cycle through lists in the
7632 * desired order. This order can have a significant effect on cache
7635 * Currently the metadata lists are hit first, MFU then MRU, followed by
7636 * the data lists. This function returns a locked list, and also returns
7639 static multilist_sublist_t *
7640 l2arc_sublist_lock(int list_num)
7642 multilist_t *ml = NULL;
7645 ASSERT(list_num >= 0 && list_num <= 3);
7649 ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
7652 ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
7655 ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
7658 ml = arc_mru->arcs_list[ARC_BUFC_DATA];
7663 * Return a randomly-selected sublist. This is acceptable
7664 * because the caller feeds only a little bit of data for each
7665 * call (8MB). Subsequent calls will result in different
7666 * sublists being selected.
7668 idx = multilist_get_random_index(ml);
7669 return (multilist_sublist_lock(ml, idx));
7673 * Evict buffers from the device write hand to the distance specified in
7674 * bytes. This distance may span populated buffers, it may span nothing.
7675 * This is clearing a region on the L2ARC device ready for writing.
7676 * If the 'all' boolean is set, every buffer is evicted.
7679 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7682 arc_buf_hdr_t *hdr, *hdr_prev;
7683 kmutex_t *hash_lock;
7686 buflist = &dev->l2ad_buflist;
7688 if (!all && dev->l2ad_first) {
7690 * This is the first sweep through the device. There is
7696 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7698 * When nearing the end of the device, evict to the end
7699 * before the device write hand jumps to the start.
7701 taddr = dev->l2ad_end;
7703 taddr = dev->l2ad_hand + distance;
7705 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7706 uint64_t, taddr, boolean_t, all);
7709 mutex_enter(&dev->l2ad_mtx);
7710 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
7711 hdr_prev = list_prev(buflist, hdr);
7713 hash_lock = HDR_LOCK(hdr);
7716 * We cannot use mutex_enter or else we can deadlock
7717 * with l2arc_write_buffers (due to swapping the order
7718 * the hash lock and l2ad_mtx are taken).
7720 if (!mutex_tryenter(hash_lock)) {
7722 * Missed the hash lock. Retry.
7724 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
7725 mutex_exit(&dev->l2ad_mtx);
7726 mutex_enter(hash_lock);
7727 mutex_exit(hash_lock);
7732 * A header can't be on this list if it doesn't have L2 header.
7734 ASSERT(HDR_HAS_L2HDR(hdr));
7736 /* Ensure this header has finished being written. */
7737 ASSERT(!HDR_L2_WRITING(hdr));
7738 ASSERT(!HDR_L2_WRITE_HEAD(hdr));
7740 if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
7741 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
7743 * We've evicted to the target address,
7744 * or the end of the device.
7746 mutex_exit(hash_lock);
7750 if (!HDR_HAS_L1HDR(hdr)) {
7751 ASSERT(!HDR_L2_READING(hdr));
7753 * This doesn't exist in the ARC. Destroy.
7754 * arc_hdr_destroy() will call list_remove()
7755 * and decrement arcstat_l2_lsize.
7757 arc_change_state(arc_anon, hdr, hash_lock);
7758 arc_hdr_destroy(hdr);
7760 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
7761 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
7763 * Invalidate issued or about to be issued
7764 * reads, since we may be about to write
7765 * over this location.
7767 if (HDR_L2_READING(hdr)) {
7768 ARCSTAT_BUMP(arcstat_l2_evict_reading);
7769 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7772 arc_hdr_l2hdr_destroy(hdr);
7774 mutex_exit(hash_lock);
7776 mutex_exit(&dev->l2ad_mtx);
7780 * Find and write ARC buffers to the L2ARC device.
7782 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7783 * for reading until they have completed writing.
7784 * The headroom_boost is an in-out parameter used to maintain headroom boost
7785 * state between calls to this function.
7787 * Returns the number of bytes actually written (which may be smaller than
7788 * the delta by which the device hand has changed due to alignment).
7791 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7793 arc_buf_hdr_t *hdr, *hdr_prev, *head;
7794 uint64_t write_asize, write_psize, write_lsize, headroom;
7796 l2arc_write_callback_t *cb;
7798 uint64_t guid = spa_load_guid(spa);
7801 ASSERT3P(dev->l2ad_vdev, !=, NULL);
7804 write_lsize = write_asize = write_psize = 0;
7806 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7807 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7809 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
7811 * Copy buffers for L2ARC writing.
7813 for (try = 0; try <= 3; try++) {
7814 multilist_sublist_t *mls = l2arc_sublist_lock(try);
7815 uint64_t passed_sz = 0;
7817 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
7820 * L2ARC fast warmup.
7822 * Until the ARC is warm and starts to evict, read from the
7823 * head of the ARC lists rather than the tail.
7825 if (arc_warm == B_FALSE)
7826 hdr = multilist_sublist_head(mls);
7828 hdr = multilist_sublist_tail(mls);
7830 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
7832 headroom = target_sz * l2arc_headroom;
7833 if (zfs_compressed_arc_enabled)
7834 headroom = (headroom * l2arc_headroom_boost) / 100;
7836 for (; hdr; hdr = hdr_prev) {
7837 kmutex_t *hash_lock;
7839 if (arc_warm == B_FALSE)
7840 hdr_prev = multilist_sublist_next(mls, hdr);
7842 hdr_prev = multilist_sublist_prev(mls, hdr);
7843 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
7844 HDR_GET_LSIZE(hdr));
7846 hash_lock = HDR_LOCK(hdr);
7847 if (!mutex_tryenter(hash_lock)) {
7848 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
7850 * Skip this buffer rather than waiting.
7855 passed_sz += HDR_GET_LSIZE(hdr);
7856 if (passed_sz > headroom) {
7860 mutex_exit(hash_lock);
7861 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
7865 if (!l2arc_write_eligible(guid, hdr)) {
7866 mutex_exit(hash_lock);
7871 * We rely on the L1 portion of the header below, so
7872 * it's invalid for this header to have been evicted out
7873 * of the ghost cache, prior to being written out. The
7874 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7876 ASSERT(HDR_HAS_L1HDR(hdr));
7878 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7879 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7880 ASSERT3U(arc_hdr_size(hdr), >, 0);
7881 uint64_t psize = arc_hdr_size(hdr);
7882 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7885 if ((write_asize + asize) > target_sz) {
7887 mutex_exit(hash_lock);
7888 ARCSTAT_BUMP(arcstat_l2_write_full);
7894 * Insert a dummy header on the buflist so
7895 * l2arc_write_done() can find where the
7896 * write buffers begin without searching.
7898 mutex_enter(&dev->l2ad_mtx);
7899 list_insert_head(&dev->l2ad_buflist, head);
7900 mutex_exit(&dev->l2ad_mtx);
7903 sizeof (l2arc_write_callback_t), KM_SLEEP);
7904 cb->l2wcb_dev = dev;
7905 cb->l2wcb_head = head;
7906 pio = zio_root(spa, l2arc_write_done, cb,
7908 ARCSTAT_BUMP(arcstat_l2_write_pios);
7911 hdr->b_l2hdr.b_dev = dev;
7912 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7913 arc_hdr_set_flags(hdr,
7914 ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7916 mutex_enter(&dev->l2ad_mtx);
7917 list_insert_head(&dev->l2ad_buflist, hdr);
7918 mutex_exit(&dev->l2ad_mtx);
7920 (void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
7923 * Normally the L2ARC can use the hdr's data, but if
7924 * we're sharing data between the hdr and one of its
7925 * bufs, L2ARC needs its own copy of the data so that
7926 * the ZIO below can't race with the buf consumer.
7927 * Another case where we need to create a copy of the
7928 * data is when the buffer size is not device-aligned
7929 * and we need to pad the block to make it such.
7930 * That also keeps the clock hand suitably aligned.
7932 * To ensure that the copy will be available for the
7933 * lifetime of the ZIO and be cleaned up afterwards, we
7934 * add it to the l2arc_free_on_write queue.
7937 if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7938 to_write = hdr->b_l1hdr.b_pabd;
7940 to_write = abd_alloc_for_io(asize,
7941 HDR_ISTYPE_METADATA(hdr));
7942 abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
7943 if (asize != psize) {
7944 abd_zero_off(to_write, psize,
7947 l2arc_free_abd_on_write(to_write, asize,
7950 wzio = zio_write_phys(pio, dev->l2ad_vdev,
7951 hdr->b_l2hdr.b_daddr, asize, to_write,
7952 ZIO_CHECKSUM_OFF, NULL, hdr,
7953 ZIO_PRIORITY_ASYNC_WRITE,
7954 ZIO_FLAG_CANFAIL, B_FALSE);
7956 write_lsize += HDR_GET_LSIZE(hdr);
7957 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7960 write_psize += psize;
7961 write_asize += asize;
7962 dev->l2ad_hand += asize;
7964 mutex_exit(hash_lock);
7966 (void) zio_nowait(wzio);
7969 multilist_sublist_unlock(mls);
7975 /* No buffers selected for writing? */
7977 ASSERT0(write_lsize);
7978 ASSERT(!HDR_HAS_L1HDR(head));
7979 kmem_cache_free(hdr_l2only_cache, head);
7983 ASSERT3U(write_psize, <=, target_sz);
7984 ARCSTAT_BUMP(arcstat_l2_writes_sent);
7985 ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
7986 ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
7987 ARCSTAT_INCR(arcstat_l2_psize, write_psize);
7988 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7991 * Bump device hand to the device start if it is approaching the end.
7992 * l2arc_evict() will already have evicted ahead for this case.
7994 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7995 dev->l2ad_hand = dev->l2ad_start;
7996 dev->l2ad_first = B_FALSE;
7999 dev->l2ad_writing = B_TRUE;
8000 (void) zio_wait(pio);
8001 dev->l2ad_writing = B_FALSE;
8003 return (write_asize);
8007 * This thread feeds the L2ARC at regular intervals. This is the beating
8008 * heart of the L2ARC.
8012 l2arc_feed_thread(void *unused __unused)
8017 uint64_t size, wrote;
8018 clock_t begin, next = ddi_get_lbolt();
8020 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
8022 mutex_enter(&l2arc_feed_thr_lock);
8024 while (l2arc_thread_exit == 0) {
8025 CALLB_CPR_SAFE_BEGIN(&cpr);
8026 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
8027 next - ddi_get_lbolt());
8028 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
8029 next = ddi_get_lbolt() + hz;
8032 * Quick check for L2ARC devices.
8034 mutex_enter(&l2arc_dev_mtx);
8035 if (l2arc_ndev == 0) {
8036 mutex_exit(&l2arc_dev_mtx);
8039 mutex_exit(&l2arc_dev_mtx);
8040 begin = ddi_get_lbolt();
8043 * This selects the next l2arc device to write to, and in
8044 * doing so the next spa to feed from: dev->l2ad_spa. This
8045 * will return NULL if there are now no l2arc devices or if
8046 * they are all faulted.
8048 * If a device is returned, its spa's config lock is also
8049 * held to prevent device removal. l2arc_dev_get_next()
8050 * will grab and release l2arc_dev_mtx.
8052 if ((dev = l2arc_dev_get_next()) == NULL)
8055 spa = dev->l2ad_spa;
8056 ASSERT3P(spa, !=, NULL);
8059 * If the pool is read-only then force the feed thread to
8060 * sleep a little longer.
8062 if (!spa_writeable(spa)) {
8063 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
8064 spa_config_exit(spa, SCL_L2ARC, dev);
8069 * Avoid contributing to memory pressure.
8071 if (arc_reclaim_needed()) {
8072 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
8073 spa_config_exit(spa, SCL_L2ARC, dev);
8077 ARCSTAT_BUMP(arcstat_l2_feeds);
8079 size = l2arc_write_size();
8082 * Evict L2ARC buffers that will be overwritten.
8084 l2arc_evict(dev, size, B_FALSE);
8087 * Write ARC buffers.
8089 wrote = l2arc_write_buffers(spa, dev, size);
8092 * Calculate interval between writes.
8094 next = l2arc_write_interval(begin, size, wrote);
8095 spa_config_exit(spa, SCL_L2ARC, dev);
8098 l2arc_thread_exit = 0;
8099 cv_broadcast(&l2arc_feed_thr_cv);
8100 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
8105 l2arc_vdev_present(vdev_t *vd)
8109 mutex_enter(&l2arc_dev_mtx);
8110 for (dev = list_head(l2arc_dev_list); dev != NULL;
8111 dev = list_next(l2arc_dev_list, dev)) {
8112 if (dev->l2ad_vdev == vd)
8115 mutex_exit(&l2arc_dev_mtx);
8117 return (dev != NULL);
8121 * Add a vdev for use by the L2ARC. By this point the spa has already
8122 * validated the vdev and opened it.
8125 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
8127 l2arc_dev_t *adddev;
8129 ASSERT(!l2arc_vdev_present(vd));
8131 vdev_ashift_optimize(vd);
8134 * Create a new l2arc device entry.
8136 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
8137 adddev->l2ad_spa = spa;
8138 adddev->l2ad_vdev = vd;
8139 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
8140 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
8141 adddev->l2ad_hand = adddev->l2ad_start;
8142 adddev->l2ad_first = B_TRUE;
8143 adddev->l2ad_writing = B_FALSE;
8145 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
8147 * This is a list of all ARC buffers that are still valid on the
8150 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
8151 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
8153 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
8154 refcount_create(&adddev->l2ad_alloc);
8157 * Add device to global list
8159 mutex_enter(&l2arc_dev_mtx);
8160 list_insert_head(l2arc_dev_list, adddev);
8161 atomic_inc_64(&l2arc_ndev);
8162 mutex_exit(&l2arc_dev_mtx);
8166 * Remove a vdev from the L2ARC.
8169 l2arc_remove_vdev(vdev_t *vd)
8171 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
8174 * Find the device by vdev
8176 mutex_enter(&l2arc_dev_mtx);
8177 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
8178 nextdev = list_next(l2arc_dev_list, dev);
8179 if (vd == dev->l2ad_vdev) {
8184 ASSERT3P(remdev, !=, NULL);
8187 * Remove device from global list
8189 list_remove(l2arc_dev_list, remdev);
8190 l2arc_dev_last = NULL; /* may have been invalidated */
8191 atomic_dec_64(&l2arc_ndev);
8192 mutex_exit(&l2arc_dev_mtx);
8195 * Clear all buflists and ARC references. L2ARC device flush.
8197 l2arc_evict(remdev, 0, B_TRUE);
8198 list_destroy(&remdev->l2ad_buflist);
8199 mutex_destroy(&remdev->l2ad_mtx);
8200 refcount_destroy(&remdev->l2ad_alloc);
8201 kmem_free(remdev, sizeof (l2arc_dev_t));
8207 l2arc_thread_exit = 0;
8209 l2arc_writes_sent = 0;
8210 l2arc_writes_done = 0;
8212 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
8213 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
8214 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
8215 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
8217 l2arc_dev_list = &L2ARC_dev_list;
8218 l2arc_free_on_write = &L2ARC_free_on_write;
8219 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
8220 offsetof(l2arc_dev_t, l2ad_node));
8221 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
8222 offsetof(l2arc_data_free_t, l2df_list_node));
8229 * This is called from dmu_fini(), which is called from spa_fini();
8230 * Because of this, we can assume that all l2arc devices have
8231 * already been removed when the pools themselves were removed.
8234 l2arc_do_free_on_write();
8236 mutex_destroy(&l2arc_feed_thr_lock);
8237 cv_destroy(&l2arc_feed_thr_cv);
8238 mutex_destroy(&l2arc_dev_mtx);
8239 mutex_destroy(&l2arc_free_on_write_mtx);
8241 list_destroy(l2arc_dev_list);
8242 list_destroy(l2arc_free_on_write);
8248 if (!(spa_mode_global & FWRITE))
8251 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
8252 TS_RUN, minclsyspri);
8258 if (!(spa_mode_global & FWRITE))
8261 mutex_enter(&l2arc_feed_thr_lock);
8262 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
8263 l2arc_thread_exit = 1;
8264 while (l2arc_thread_exit != 0)
8265 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
8266 mutex_exit(&l2arc_feed_thr_lock);