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 * Note that the majority of the performance stats are manipulated
103 * with atomic operations.
105 * The L2ARC uses the l2ad_mtx on each vdev for the following:
107 * - L2ARC buflist creation
108 * - L2ARC buflist eviction
109 * - L2ARC write completion, which walks L2ARC buflists
110 * - ARC header destruction, as it removes from L2ARC buflists
111 * - ARC header release, as it removes from L2ARC buflists
117 * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
118 * This structure can point either to a block that is still in the cache or to
119 * one that is only accessible in an L2 ARC device, or it can provide
120 * information about a block that was recently evicted. If a block is
121 * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
122 * information to retrieve it from the L2ARC device. This information is
123 * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
124 * that is in this state cannot access the data directly.
126 * Blocks that are actively being referenced or have not been evicted
127 * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
128 * the arc_buf_hdr_t that will point to the data block in memory. A block can
129 * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
130 * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
131 * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
133 * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
134 * ability to store the physical data (b_pabd) associated with the DVA of the
135 * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
136 * it will match its on-disk compression characteristics. This behavior can be
137 * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
138 * compressed ARC functionality is disabled, the b_pabd will point to an
139 * uncompressed version of the on-disk data.
141 * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
142 * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
143 * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
144 * consumer. The ARC will provide references to this data and will keep it
145 * cached until it is no longer in use. The ARC caches only the L1ARC's physical
146 * data block and will evict any arc_buf_t that is no longer referenced. The
147 * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
148 * "overhead_size" kstat.
150 * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
151 * compressed form. The typical case is that consumers will want uncompressed
152 * data, and when that happens a new data buffer is allocated where the data is
153 * decompressed for them to use. Currently the only consumer who wants
154 * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
155 * exists on disk. When this happens, the arc_buf_t's data buffer is shared
156 * with the arc_buf_hdr_t.
158 * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
159 * first one is owned by a compressed send consumer (and therefore references
160 * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
161 * used by any other consumer (and has its own uncompressed copy of the data
176 * | b_buf +------------>+-----------+ arc_buf_t
177 * | b_pabd +-+ |b_next +---->+-----------+
178 * +-----------+ | |-----------| |b_next +-->NULL
179 * | |b_comp = T | +-----------+
180 * | |b_data +-+ |b_comp = F |
181 * | +-----------+ | |b_data +-+
182 * +->+------+ | +-----------+ |
184 * data | |<--------------+ | uncompressed
185 * +------+ compressed, | data
186 * shared +-->+------+
191 * When a consumer reads a block, the ARC must first look to see if the
192 * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
193 * arc_buf_t and either copies uncompressed data into a new data buffer from an
194 * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
195 * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
196 * hdr is compressed and the desired compression characteristics of the
197 * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
198 * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
199 * the last buffer in the hdr's b_buf list, however a shared compressed buf can
200 * be anywhere in the hdr's list.
202 * The diagram below shows an example of an uncompressed ARC hdr that is
203 * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
204 * the last element in the buf list):
216 * | | arc_buf_t (shared)
217 * | b_buf +------------>+---------+ arc_buf_t
218 * | | |b_next +---->+---------+
219 * | b_pabd +-+ |---------| |b_next +-->NULL
220 * +-----------+ | | | +---------+
222 * | +---------+ | |b_data +-+
223 * +->+------+ | +---------+ |
225 * uncompressed | | | |
228 * | uncompressed | | |
231 * +---------------------------------+
233 * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
234 * since the physical block is about to be rewritten. The new data contents
235 * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
236 * it may compress the data before writing it to disk. The ARC will be called
237 * with the transformed data and will bcopy the transformed on-disk block into
238 * a newly allocated b_pabd. Writes are always done into buffers which have
239 * either been loaned (and hence are new and don't have other readers) or
240 * buffers which have been released (and hence have their own hdr, if there
241 * were originally other readers of the buf's original hdr). This ensures that
242 * the ARC only needs to update a single buf and its hdr after a write occurs.
244 * When the L2ARC is in use, it will also take advantage of the b_pabd. The
245 * L2ARC will always write the contents of b_pabd to the L2ARC. This means
246 * that when compressed ARC is enabled that the L2ARC blocks are identical
247 * to the on-disk block in the main data pool. This provides a significant
248 * advantage since the ARC can leverage the bp's checksum when reading from the
249 * L2ARC to determine if the contents are valid. However, if the compressed
250 * ARC is disabled, then the L2ARC's block must be transformed to look
251 * like the physical block in the main data pool before comparing the
252 * checksum and determining its validity.
257 #include <sys/spa_impl.h>
258 #include <sys/zio_compress.h>
259 #include <sys/zio_checksum.h>
260 #include <sys/zfs_context.h>
262 #include <sys/refcount.h>
263 #include <sys/vdev.h>
264 #include <sys/vdev_impl.h>
265 #include <sys/dsl_pool.h>
266 #include <sys/zio_checksum.h>
267 #include <sys/multilist.h>
270 #include <sys/dnlc.h>
271 #include <sys/racct.h>
273 #include <sys/callb.h>
274 #include <sys/kstat.h>
275 #include <sys/trim_map.h>
276 #include <zfs_fletcher.h>
278 #include <sys/aggsum.h>
279 #include <sys/cityhash.h>
281 #include <machine/vmparam.h>
285 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
286 boolean_t arc_watch = B_FALSE;
291 static kmutex_t arc_reclaim_lock;
292 static kcondvar_t arc_reclaim_thread_cv;
293 static boolean_t arc_reclaim_thread_exit;
294 static kcondvar_t arc_reclaim_waiters_cv;
296 static kmutex_t arc_dnlc_evicts_lock;
297 static kcondvar_t arc_dnlc_evicts_cv;
298 static boolean_t arc_dnlc_evicts_thread_exit;
300 uint_t arc_reduce_dnlc_percent = 3;
303 * The number of headers to evict in arc_evict_state_impl() before
304 * dropping the sublist lock and evicting from another sublist. A lower
305 * value means we're more likely to evict the "correct" header (i.e. the
306 * oldest header in the arc state), but comes with higher overhead
307 * (i.e. more invocations of arc_evict_state_impl()).
309 int zfs_arc_evict_batch_limit = 10;
311 /* number of seconds before growing cache again */
312 static int arc_grow_retry = 60;
314 /* number of milliseconds before attempting a kmem-cache-reap */
315 static int arc_kmem_cache_reap_retry_ms = 1000;
317 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
318 int zfs_arc_overflow_shift = 8;
320 /* shift of arc_c for calculating both min and max arc_p */
321 static int arc_p_min_shift = 4;
323 /* log2(fraction of arc to reclaim) */
324 static int arc_shrink_shift = 7;
327 * log2(fraction of ARC which must be free to allow growing).
328 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
329 * when reading a new block into the ARC, we will evict an equal-sized block
332 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
333 * we will still not allow it to grow.
335 int arc_no_grow_shift = 5;
339 * minimum lifespan of a prefetch block in clock ticks
340 * (initialized in arc_init())
342 static int zfs_arc_min_prefetch_ms = 1;
343 static int zfs_arc_min_prescient_prefetch_ms = 6;
346 * If this percent of memory is free, don't throttle.
348 int arc_lotsfree_percent = 10;
351 extern boolean_t zfs_prefetch_disable;
354 * The arc has filled available memory and has now warmed up.
356 static boolean_t arc_warm;
359 * log2 fraction of the zio arena to keep free.
361 int arc_zio_arena_free_shift = 2;
364 * These tunables are for performance analysis.
366 uint64_t zfs_arc_max;
367 uint64_t zfs_arc_min;
368 uint64_t zfs_arc_meta_limit = 0;
369 uint64_t zfs_arc_meta_min = 0;
370 int zfs_arc_grow_retry = 0;
371 int zfs_arc_shrink_shift = 0;
372 int zfs_arc_no_grow_shift = 0;
373 int zfs_arc_p_min_shift = 0;
374 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
375 u_int zfs_arc_free_target = 0;
377 /* Absolute min for arc min / max is 16MB. */
378 static uint64_t arc_abs_min = 16 << 20;
381 * ARC dirty data constraints for arc_tempreserve_space() throttle
383 uint_t zfs_arc_dirty_limit_percent = 50; /* total dirty data limit */
384 uint_t zfs_arc_anon_limit_percent = 25; /* anon block dirty limit */
385 uint_t zfs_arc_pool_dirty_percent = 20; /* each pool's anon allowance */
387 boolean_t zfs_compressed_arc_enabled = B_TRUE;
389 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
390 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
391 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
392 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
393 static int sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS);
395 #if defined(__FreeBSD__) && defined(_KERNEL)
397 arc_free_target_init(void *unused __unused)
400 zfs_arc_free_target = vm_cnt.v_free_target;
402 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
403 arc_free_target_init, NULL);
405 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
406 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
407 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
408 TUNABLE_INT("vfs.zfs.arc_grow_retry", &zfs_arc_grow_retry);
409 TUNABLE_INT("vfs.zfs.arc_no_grow_shift", &zfs_arc_no_grow_shift);
410 SYSCTL_DECL(_vfs_zfs);
411 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
412 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
413 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
414 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
415 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_no_grow_shift, CTLTYPE_U32 | CTLFLAG_RWTUN,
416 0, sizeof(uint32_t), sysctl_vfs_zfs_arc_no_grow_shift, "U",
417 "log2(fraction of ARC which must be free to allow growing)");
418 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
419 &zfs_arc_average_blocksize, 0,
420 "ARC average blocksize");
421 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
422 &arc_shrink_shift, 0,
423 "log2(fraction of arc to reclaim)");
424 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_grow_retry, CTLFLAG_RW,
426 "Wait in seconds before considering growing ARC");
427 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
428 &zfs_compressed_arc_enabled, 0, "Enable compressed ARC");
431 * We don't have a tunable for arc_free_target due to the dependency on
432 * pagedaemon initialisation.
434 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
435 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
436 sysctl_vfs_zfs_arc_free_target, "IU",
437 "Desired number of free pages below which ARC triggers reclaim");
440 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
445 val = zfs_arc_free_target;
446 err = sysctl_handle_int(oidp, &val, 0, req);
447 if (err != 0 || req->newptr == NULL)
452 if (val > vm_cnt.v_page_count)
455 zfs_arc_free_target = val;
461 * Must be declared here, before the definition of corresponding kstat
462 * macro which uses the same names will confuse the compiler.
464 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
465 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
466 sysctl_vfs_zfs_arc_meta_limit, "QU",
467 "ARC metadata limit");
471 * Note that buffers can be in one of 6 states:
472 * ARC_anon - anonymous (discussed below)
473 * ARC_mru - recently used, currently cached
474 * ARC_mru_ghost - recentely used, no longer in cache
475 * ARC_mfu - frequently used, currently cached
476 * ARC_mfu_ghost - frequently used, no longer in cache
477 * ARC_l2c_only - exists in L2ARC but not other states
478 * When there are no active references to the buffer, they are
479 * are linked onto a list in one of these arc states. These are
480 * the only buffers that can be evicted or deleted. Within each
481 * state there are multiple lists, one for meta-data and one for
482 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
483 * etc.) is tracked separately so that it can be managed more
484 * explicitly: favored over data, limited explicitly.
486 * Anonymous buffers are buffers that are not associated with
487 * a DVA. These are buffers that hold dirty block copies
488 * before they are written to stable storage. By definition,
489 * they are "ref'd" and are considered part of arc_mru
490 * that cannot be freed. Generally, they will aquire a DVA
491 * as they are written and migrate onto the arc_mru list.
493 * The ARC_l2c_only state is for buffers that are in the second
494 * level ARC but no longer in any of the ARC_m* lists. The second
495 * level ARC itself may also contain buffers that are in any of
496 * the ARC_m* states - meaning that a buffer can exist in two
497 * places. The reason for the ARC_l2c_only state is to keep the
498 * buffer header in the hash table, so that reads that hit the
499 * second level ARC benefit from these fast lookups.
502 typedef struct arc_state {
504 * list of evictable buffers
506 multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
508 * total amount of evictable data in this state
510 refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
512 * total amount of data in this state; this includes: evictable,
513 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
515 refcount_t arcs_size;
519 static arc_state_t ARC_anon;
520 static arc_state_t ARC_mru;
521 static arc_state_t ARC_mru_ghost;
522 static arc_state_t ARC_mfu;
523 static arc_state_t ARC_mfu_ghost;
524 static arc_state_t ARC_l2c_only;
526 typedef struct arc_stats {
527 kstat_named_t arcstat_hits;
528 kstat_named_t arcstat_misses;
529 kstat_named_t arcstat_demand_data_hits;
530 kstat_named_t arcstat_demand_data_misses;
531 kstat_named_t arcstat_demand_metadata_hits;
532 kstat_named_t arcstat_demand_metadata_misses;
533 kstat_named_t arcstat_prefetch_data_hits;
534 kstat_named_t arcstat_prefetch_data_misses;
535 kstat_named_t arcstat_prefetch_metadata_hits;
536 kstat_named_t arcstat_prefetch_metadata_misses;
537 kstat_named_t arcstat_mru_hits;
538 kstat_named_t arcstat_mru_ghost_hits;
539 kstat_named_t arcstat_mfu_hits;
540 kstat_named_t arcstat_mfu_ghost_hits;
541 kstat_named_t arcstat_allocated;
542 kstat_named_t arcstat_deleted;
544 * Number of buffers that could not be evicted because the hash lock
545 * was held by another thread. The lock may not necessarily be held
546 * by something using the same buffer, since hash locks are shared
547 * by multiple buffers.
549 kstat_named_t arcstat_mutex_miss;
551 * Number of buffers skipped when updating the access state due to the
552 * header having already been released after acquiring the hash lock.
554 kstat_named_t arcstat_access_skip;
556 * Number of buffers skipped because they have I/O in progress, are
557 * indirect prefetch buffers that have not lived long enough, or are
558 * not from the spa we're trying to evict from.
560 kstat_named_t arcstat_evict_skip;
562 * Number of times arc_evict_state() was unable to evict enough
563 * buffers to reach it's target amount.
565 kstat_named_t arcstat_evict_not_enough;
566 kstat_named_t arcstat_evict_l2_cached;
567 kstat_named_t arcstat_evict_l2_eligible;
568 kstat_named_t arcstat_evict_l2_ineligible;
569 kstat_named_t arcstat_evict_l2_skip;
570 kstat_named_t arcstat_hash_elements;
571 kstat_named_t arcstat_hash_elements_max;
572 kstat_named_t arcstat_hash_collisions;
573 kstat_named_t arcstat_hash_chains;
574 kstat_named_t arcstat_hash_chain_max;
575 kstat_named_t arcstat_p;
576 kstat_named_t arcstat_c;
577 kstat_named_t arcstat_c_min;
578 kstat_named_t arcstat_c_max;
579 /* Not updated directly; only synced in arc_kstat_update. */
580 kstat_named_t arcstat_size;
582 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
583 * Note that the compressed bytes may match the uncompressed bytes
584 * if the block is either not compressed or compressed arc is disabled.
586 kstat_named_t arcstat_compressed_size;
588 * Uncompressed size of the data stored in b_pabd. If compressed
589 * arc is disabled then this value will be identical to the stat
592 kstat_named_t arcstat_uncompressed_size;
594 * Number of bytes stored in all the arc_buf_t's. This is classified
595 * as "overhead" since this data is typically short-lived and will
596 * be evicted from the arc when it becomes unreferenced unless the
597 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
598 * values have been set (see comment in dbuf.c for more information).
600 kstat_named_t arcstat_overhead_size;
602 * Number of bytes consumed by internal ARC structures necessary
603 * for tracking purposes; these structures are not actually
604 * backed by ARC buffers. This includes arc_buf_hdr_t structures
605 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
606 * caches), and arc_buf_t structures (allocated via arc_buf_t
608 * Not updated directly; only synced in arc_kstat_update.
610 kstat_named_t arcstat_hdr_size;
612 * Number of bytes consumed by ARC buffers of type equal to
613 * ARC_BUFC_DATA. This is generally consumed by buffers backing
614 * on disk user data (e.g. plain file contents).
615 * Not updated directly; only synced in arc_kstat_update.
617 kstat_named_t arcstat_data_size;
619 * Number of bytes consumed by ARC buffers of type equal to
620 * ARC_BUFC_METADATA. This is generally consumed by buffers
621 * backing on disk data that is used for internal ZFS
622 * structures (e.g. ZAP, dnode, indirect blocks, etc).
623 * Not updated directly; only synced in arc_kstat_update.
625 kstat_named_t arcstat_metadata_size;
627 * Number of bytes consumed by various buffers and structures
628 * not actually backed with ARC buffers. This includes bonus
629 * buffers (allocated directly via zio_buf_* functions),
630 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
631 * cache), and dnode_t structures (allocated via dnode_t cache).
632 * Not updated directly; only synced in arc_kstat_update.
634 kstat_named_t arcstat_other_size;
636 * Total number of bytes consumed by ARC buffers residing in the
637 * arc_anon state. This includes *all* buffers in the arc_anon
638 * state; e.g. data, metadata, evictable, and unevictable buffers
639 * are all included in this value.
640 * Not updated directly; only synced in arc_kstat_update.
642 kstat_named_t arcstat_anon_size;
644 * Number of bytes consumed by ARC buffers that meet the
645 * following criteria: backing buffers of type ARC_BUFC_DATA,
646 * residing in the arc_anon state, and are eligible for eviction
647 * (e.g. have no outstanding holds on the buffer).
648 * Not updated directly; only synced in arc_kstat_update.
650 kstat_named_t arcstat_anon_evictable_data;
652 * Number of bytes consumed by ARC buffers that meet the
653 * following criteria: backing buffers of type ARC_BUFC_METADATA,
654 * residing in the arc_anon state, and are eligible for eviction
655 * (e.g. have no outstanding holds on the buffer).
656 * Not updated directly; only synced in arc_kstat_update.
658 kstat_named_t arcstat_anon_evictable_metadata;
660 * Total number of bytes consumed by ARC buffers residing in the
661 * arc_mru state. This includes *all* buffers in the arc_mru
662 * state; e.g. data, metadata, evictable, and unevictable buffers
663 * are all included in this value.
664 * Not updated directly; only synced in arc_kstat_update.
666 kstat_named_t arcstat_mru_size;
668 * Number of bytes consumed by ARC buffers that meet the
669 * following criteria: backing buffers of type ARC_BUFC_DATA,
670 * residing in the arc_mru state, and are eligible for eviction
671 * (e.g. have no outstanding holds on the buffer).
672 * Not updated directly; only synced in arc_kstat_update.
674 kstat_named_t arcstat_mru_evictable_data;
676 * Number of bytes consumed by ARC buffers that meet the
677 * following criteria: backing buffers of type ARC_BUFC_METADATA,
678 * residing in the arc_mru state, and are eligible for eviction
679 * (e.g. have no outstanding holds on the buffer).
680 * Not updated directly; only synced in arc_kstat_update.
682 kstat_named_t arcstat_mru_evictable_metadata;
684 * Total number of bytes that *would have been* consumed by ARC
685 * buffers in the arc_mru_ghost state. The key thing to note
686 * here, is the fact that this size doesn't actually indicate
687 * RAM consumption. The ghost lists only consist of headers and
688 * don't actually have ARC buffers linked off of these headers.
689 * Thus, *if* the headers had associated ARC buffers, these
690 * buffers *would have* consumed this number of bytes.
691 * Not updated directly; only synced in arc_kstat_update.
693 kstat_named_t arcstat_mru_ghost_size;
695 * Number of bytes that *would have been* consumed by ARC
696 * buffers that are eligible for eviction, of type
697 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
698 * Not updated directly; only synced in arc_kstat_update.
700 kstat_named_t arcstat_mru_ghost_evictable_data;
702 * Number of bytes that *would have been* consumed by ARC
703 * buffers that are eligible for eviction, of type
704 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
705 * Not updated directly; only synced in arc_kstat_update.
707 kstat_named_t arcstat_mru_ghost_evictable_metadata;
709 * Total number of bytes consumed by ARC buffers residing in the
710 * arc_mfu state. This includes *all* buffers in the arc_mfu
711 * state; e.g. data, metadata, evictable, and unevictable buffers
712 * are all included in this value.
713 * Not updated directly; only synced in arc_kstat_update.
715 kstat_named_t arcstat_mfu_size;
717 * Number of bytes consumed by ARC buffers that are eligible for
718 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
720 * Not updated directly; only synced in arc_kstat_update.
722 kstat_named_t arcstat_mfu_evictable_data;
724 * Number of bytes consumed by ARC buffers that are eligible for
725 * eviction, of type ARC_BUFC_METADATA, and reside in the
727 * Not updated directly; only synced in arc_kstat_update.
729 kstat_named_t arcstat_mfu_evictable_metadata;
731 * Total number of bytes that *would have been* consumed by ARC
732 * buffers in the arc_mfu_ghost state. See the comment above
733 * arcstat_mru_ghost_size for more details.
734 * Not updated directly; only synced in arc_kstat_update.
736 kstat_named_t arcstat_mfu_ghost_size;
738 * Number of bytes that *would have been* consumed by ARC
739 * buffers that are eligible for eviction, of type
740 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
741 * Not updated directly; only synced in arc_kstat_update.
743 kstat_named_t arcstat_mfu_ghost_evictable_data;
745 * Number of bytes that *would have been* consumed by ARC
746 * buffers that are eligible for eviction, of type
747 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
748 * Not updated directly; only synced in arc_kstat_update.
750 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
751 kstat_named_t arcstat_l2_hits;
752 kstat_named_t arcstat_l2_misses;
753 kstat_named_t arcstat_l2_feeds;
754 kstat_named_t arcstat_l2_rw_clash;
755 kstat_named_t arcstat_l2_read_bytes;
756 kstat_named_t arcstat_l2_write_bytes;
757 kstat_named_t arcstat_l2_writes_sent;
758 kstat_named_t arcstat_l2_writes_done;
759 kstat_named_t arcstat_l2_writes_error;
760 kstat_named_t arcstat_l2_writes_lock_retry;
761 kstat_named_t arcstat_l2_evict_lock_retry;
762 kstat_named_t arcstat_l2_evict_reading;
763 kstat_named_t arcstat_l2_evict_l1cached;
764 kstat_named_t arcstat_l2_free_on_write;
765 kstat_named_t arcstat_l2_abort_lowmem;
766 kstat_named_t arcstat_l2_cksum_bad;
767 kstat_named_t arcstat_l2_io_error;
768 kstat_named_t arcstat_l2_lsize;
769 kstat_named_t arcstat_l2_psize;
770 /* Not updated directly; only synced in arc_kstat_update. */
771 kstat_named_t arcstat_l2_hdr_size;
772 kstat_named_t arcstat_l2_write_trylock_fail;
773 kstat_named_t arcstat_l2_write_passed_headroom;
774 kstat_named_t arcstat_l2_write_spa_mismatch;
775 kstat_named_t arcstat_l2_write_in_l2;
776 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
777 kstat_named_t arcstat_l2_write_not_cacheable;
778 kstat_named_t arcstat_l2_write_full;
779 kstat_named_t arcstat_l2_write_buffer_iter;
780 kstat_named_t arcstat_l2_write_pios;
781 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
782 kstat_named_t arcstat_l2_write_buffer_list_iter;
783 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
784 kstat_named_t arcstat_memory_throttle_count;
785 /* Not updated directly; only synced in arc_kstat_update. */
786 kstat_named_t arcstat_meta_used;
787 kstat_named_t arcstat_meta_limit;
788 kstat_named_t arcstat_meta_max;
789 kstat_named_t arcstat_meta_min;
790 kstat_named_t arcstat_async_upgrade_sync;
791 kstat_named_t arcstat_demand_hit_predictive_prefetch;
792 kstat_named_t arcstat_demand_hit_prescient_prefetch;
795 static arc_stats_t arc_stats = {
796 { "hits", KSTAT_DATA_UINT64 },
797 { "misses", KSTAT_DATA_UINT64 },
798 { "demand_data_hits", KSTAT_DATA_UINT64 },
799 { "demand_data_misses", KSTAT_DATA_UINT64 },
800 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
801 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
802 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
803 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
804 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
805 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
806 { "mru_hits", KSTAT_DATA_UINT64 },
807 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
808 { "mfu_hits", KSTAT_DATA_UINT64 },
809 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
810 { "allocated", KSTAT_DATA_UINT64 },
811 { "deleted", KSTAT_DATA_UINT64 },
812 { "mutex_miss", KSTAT_DATA_UINT64 },
813 { "access_skip", KSTAT_DATA_UINT64 },
814 { "evict_skip", KSTAT_DATA_UINT64 },
815 { "evict_not_enough", KSTAT_DATA_UINT64 },
816 { "evict_l2_cached", KSTAT_DATA_UINT64 },
817 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
818 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
819 { "evict_l2_skip", KSTAT_DATA_UINT64 },
820 { "hash_elements", KSTAT_DATA_UINT64 },
821 { "hash_elements_max", KSTAT_DATA_UINT64 },
822 { "hash_collisions", KSTAT_DATA_UINT64 },
823 { "hash_chains", KSTAT_DATA_UINT64 },
824 { "hash_chain_max", KSTAT_DATA_UINT64 },
825 { "p", KSTAT_DATA_UINT64 },
826 { "c", KSTAT_DATA_UINT64 },
827 { "c_min", KSTAT_DATA_UINT64 },
828 { "c_max", KSTAT_DATA_UINT64 },
829 { "size", KSTAT_DATA_UINT64 },
830 { "compressed_size", KSTAT_DATA_UINT64 },
831 { "uncompressed_size", KSTAT_DATA_UINT64 },
832 { "overhead_size", KSTAT_DATA_UINT64 },
833 { "hdr_size", KSTAT_DATA_UINT64 },
834 { "data_size", KSTAT_DATA_UINT64 },
835 { "metadata_size", KSTAT_DATA_UINT64 },
836 { "other_size", KSTAT_DATA_UINT64 },
837 { "anon_size", KSTAT_DATA_UINT64 },
838 { "anon_evictable_data", KSTAT_DATA_UINT64 },
839 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
840 { "mru_size", KSTAT_DATA_UINT64 },
841 { "mru_evictable_data", KSTAT_DATA_UINT64 },
842 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
843 { "mru_ghost_size", KSTAT_DATA_UINT64 },
844 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
845 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
846 { "mfu_size", KSTAT_DATA_UINT64 },
847 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
848 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
849 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
850 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
851 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
852 { "l2_hits", KSTAT_DATA_UINT64 },
853 { "l2_misses", KSTAT_DATA_UINT64 },
854 { "l2_feeds", KSTAT_DATA_UINT64 },
855 { "l2_rw_clash", KSTAT_DATA_UINT64 },
856 { "l2_read_bytes", KSTAT_DATA_UINT64 },
857 { "l2_write_bytes", KSTAT_DATA_UINT64 },
858 { "l2_writes_sent", KSTAT_DATA_UINT64 },
859 { "l2_writes_done", KSTAT_DATA_UINT64 },
860 { "l2_writes_error", KSTAT_DATA_UINT64 },
861 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
862 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
863 { "l2_evict_reading", KSTAT_DATA_UINT64 },
864 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
865 { "l2_free_on_write", KSTAT_DATA_UINT64 },
866 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
867 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
868 { "l2_io_error", KSTAT_DATA_UINT64 },
869 { "l2_size", KSTAT_DATA_UINT64 },
870 { "l2_asize", KSTAT_DATA_UINT64 },
871 { "l2_hdr_size", KSTAT_DATA_UINT64 },
872 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
873 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
874 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
875 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
876 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
877 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
878 { "l2_write_full", KSTAT_DATA_UINT64 },
879 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
880 { "l2_write_pios", KSTAT_DATA_UINT64 },
881 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
882 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
883 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
884 { "memory_throttle_count", KSTAT_DATA_UINT64 },
885 { "arc_meta_used", KSTAT_DATA_UINT64 },
886 { "arc_meta_limit", KSTAT_DATA_UINT64 },
887 { "arc_meta_max", KSTAT_DATA_UINT64 },
888 { "arc_meta_min", KSTAT_DATA_UINT64 },
889 { "async_upgrade_sync", KSTAT_DATA_UINT64 },
890 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
891 { "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
894 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
896 #define ARCSTAT_INCR(stat, val) \
897 atomic_add_64(&arc_stats.stat.value.ui64, (val))
899 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
900 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
902 #define ARCSTAT_MAX(stat, val) { \
904 while ((val) > (m = arc_stats.stat.value.ui64) && \
905 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
909 #define ARCSTAT_MAXSTAT(stat) \
910 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
913 * We define a macro to allow ARC hits/misses to be easily broken down by
914 * two separate conditions, giving a total of four different subtypes for
915 * each of hits and misses (so eight statistics total).
917 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
920 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
922 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
926 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
928 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
933 static arc_state_t *arc_anon;
934 static arc_state_t *arc_mru;
935 static arc_state_t *arc_mru_ghost;
936 static arc_state_t *arc_mfu;
937 static arc_state_t *arc_mfu_ghost;
938 static arc_state_t *arc_l2c_only;
941 * There are several ARC variables that are critical to export as kstats --
942 * but we don't want to have to grovel around in the kstat whenever we wish to
943 * manipulate them. For these variables, we therefore define them to be in
944 * terms of the statistic variable. This assures that we are not introducing
945 * the possibility of inconsistency by having shadow copies of the variables,
946 * while still allowing the code to be readable.
948 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
949 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
950 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
951 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
952 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
953 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
954 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
956 /* compressed size of entire arc */
957 #define arc_compressed_size ARCSTAT(arcstat_compressed_size)
958 /* uncompressed size of entire arc */
959 #define arc_uncompressed_size ARCSTAT(arcstat_uncompressed_size)
960 /* number of bytes in the arc from arc_buf_t's */
961 #define arc_overhead_size ARCSTAT(arcstat_overhead_size)
964 * There are also some ARC variables that we want to export, but that are
965 * updated so often that having the canonical representation be the statistic
966 * variable causes a performance bottleneck. We want to use aggsum_t's for these
967 * instead, but still be able to export the kstat in the same way as before.
968 * The solution is to always use the aggsum version, except in the kstat update
972 aggsum_t arc_meta_used;
973 aggsum_t astat_data_size;
974 aggsum_t astat_metadata_size;
975 aggsum_t astat_hdr_size;
976 aggsum_t astat_other_size;
977 aggsum_t astat_l2_hdr_size;
979 static int arc_no_grow; /* Don't try to grow cache size */
980 static uint64_t arc_tempreserve;
981 static uint64_t arc_loaned_bytes;
983 typedef struct arc_callback arc_callback_t;
985 struct arc_callback {
987 arc_read_done_func_t *acb_done;
989 boolean_t acb_compressed;
990 zio_t *acb_zio_dummy;
992 arc_callback_t *acb_next;
995 typedef struct arc_write_callback arc_write_callback_t;
997 struct arc_write_callback {
999 arc_write_done_func_t *awcb_ready;
1000 arc_write_done_func_t *awcb_children_ready;
1001 arc_write_done_func_t *awcb_physdone;
1002 arc_write_done_func_t *awcb_done;
1003 arc_buf_t *awcb_buf;
1007 * ARC buffers are separated into multiple structs as a memory saving measure:
1008 * - Common fields struct, always defined, and embedded within it:
1009 * - L2-only fields, always allocated but undefined when not in L2ARC
1010 * - L1-only fields, only allocated when in L1ARC
1012 * Buffer in L1 Buffer only in L2
1013 * +------------------------+ +------------------------+
1014 * | arc_buf_hdr_t | | arc_buf_hdr_t |
1018 * +------------------------+ +------------------------+
1019 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
1020 * | (undefined if L1-only) | | |
1021 * +------------------------+ +------------------------+
1022 * | l1arc_buf_hdr_t |
1027 * +------------------------+
1029 * Because it's possible for the L2ARC to become extremely large, we can wind
1030 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
1031 * is minimized by only allocating the fields necessary for an L1-cached buffer
1032 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
1033 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
1034 * words in pointers. arc_hdr_realloc() is used to switch a header between
1035 * these two allocation states.
1037 typedef struct l1arc_buf_hdr {
1038 kmutex_t b_freeze_lock;
1039 zio_cksum_t *b_freeze_cksum;
1042 * Used for debugging with kmem_flags - by allocating and freeing
1043 * b_thawed when the buffer is thawed, we get a record of the stack
1044 * trace that thawed it.
1051 /* for waiting on writes to complete */
1055 /* protected by arc state mutex */
1056 arc_state_t *b_state;
1057 multilist_node_t b_arc_node;
1059 /* updated atomically */
1060 clock_t b_arc_access;
1062 /* self protecting */
1063 refcount_t b_refcnt;
1065 arc_callback_t *b_acb;
1069 typedef struct l2arc_dev l2arc_dev_t;
1071 typedef struct l2arc_buf_hdr {
1072 /* protected by arc_buf_hdr mutex */
1073 l2arc_dev_t *b_dev; /* L2ARC device */
1074 uint64_t b_daddr; /* disk address, offset byte */
1076 list_node_t b_l2node;
1079 struct arc_buf_hdr {
1080 /* protected by hash lock */
1084 arc_buf_contents_t b_type;
1085 arc_buf_hdr_t *b_hash_next;
1086 arc_flags_t b_flags;
1089 * This field stores the size of the data buffer after
1090 * compression, and is set in the arc's zio completion handlers.
1091 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1093 * While the block pointers can store up to 32MB in their psize
1094 * field, we can only store up to 32MB minus 512B. This is due
1095 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1096 * a field of zeros represents 512B in the bp). We can't use a
1097 * bias of 1 since we need to reserve a psize of zero, here, to
1098 * represent holes and embedded blocks.
1100 * This isn't a problem in practice, since the maximum size of a
1101 * buffer is limited to 16MB, so we never need to store 32MB in
1102 * this field. Even in the upstream illumos code base, the
1103 * maximum size of a buffer is limited to 16MB.
1108 * This field stores the size of the data buffer before
1109 * compression, and cannot change once set. It is in units
1110 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1112 uint16_t b_lsize; /* immutable */
1113 uint64_t b_spa; /* immutable */
1115 /* L2ARC fields. Undefined when not in L2ARC. */
1116 l2arc_buf_hdr_t b_l2hdr;
1117 /* L1ARC fields. Undefined when in l2arc_only state */
1118 l1arc_buf_hdr_t b_l1hdr;
1121 #if defined(__FreeBSD__) && defined(_KERNEL)
1123 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1128 val = arc_meta_limit;
1129 err = sysctl_handle_64(oidp, &val, 0, req);
1130 if (err != 0 || req->newptr == NULL)
1133 if (val <= 0 || val > arc_c_max)
1136 arc_meta_limit = val;
1141 sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS)
1146 val = arc_no_grow_shift;
1147 err = sysctl_handle_32(oidp, &val, 0, req);
1148 if (err != 0 || req->newptr == NULL)
1151 if (val >= arc_shrink_shift)
1154 arc_no_grow_shift = val;
1159 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1165 err = sysctl_handle_64(oidp, &val, 0, req);
1166 if (err != 0 || req->newptr == NULL)
1169 if (zfs_arc_max == 0) {
1170 /* Loader tunable so blindly set */
1175 if (val < arc_abs_min || val > kmem_size())
1177 if (val < arc_c_min)
1179 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1185 arc_p = (arc_c >> 1);
1187 if (zfs_arc_meta_limit == 0) {
1188 /* limit meta-data to 1/4 of the arc capacity */
1189 arc_meta_limit = arc_c_max / 4;
1192 /* if kmem_flags are set, lets try to use less memory */
1193 if (kmem_debugging())
1196 zfs_arc_max = arc_c;
1202 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1208 err = sysctl_handle_64(oidp, &val, 0, req);
1209 if (err != 0 || req->newptr == NULL)
1212 if (zfs_arc_min == 0) {
1213 /* Loader tunable so blindly set */
1218 if (val < arc_abs_min || val > arc_c_max)
1223 if (zfs_arc_meta_min == 0)
1224 arc_meta_min = arc_c_min / 2;
1226 if (arc_c < arc_c_min)
1229 zfs_arc_min = arc_c_min;
1235 #define GHOST_STATE(state) \
1236 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
1237 (state) == arc_l2c_only)
1239 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1240 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1241 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1242 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1243 #define HDR_PRESCIENT_PREFETCH(hdr) \
1244 ((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
1245 #define HDR_COMPRESSION_ENABLED(hdr) \
1246 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1248 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1249 #define HDR_L2_READING(hdr) \
1250 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1251 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1252 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1253 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1254 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1255 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1257 #define HDR_ISTYPE_METADATA(hdr) \
1258 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1259 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1261 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1262 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1264 /* For storing compression mode in b_flags */
1265 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1267 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1268 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1269 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1270 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1272 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
1273 #define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1274 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1280 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1281 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1284 * Hash table routines
1287 #define HT_LOCK_PAD CACHE_LINE_SIZE
1292 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1296 #define BUF_LOCKS 256
1297 typedef struct buf_hash_table {
1299 arc_buf_hdr_t **ht_table;
1300 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1303 static buf_hash_table_t buf_hash_table;
1305 #define BUF_HASH_INDEX(spa, dva, birth) \
1306 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1307 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1308 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1309 #define HDR_LOCK(hdr) \
1310 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1312 uint64_t zfs_crc64_table[256];
1318 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1319 #define L2ARC_HEADROOM 2 /* num of writes */
1321 * If we discover during ARC scan any buffers to be compressed, we boost
1322 * our headroom for the next scanning cycle by this percentage multiple.
1324 #define L2ARC_HEADROOM_BOOST 200
1325 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1326 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1328 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1329 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1331 /* L2ARC Performance Tunables */
1332 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1333 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1334 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1335 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1336 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1337 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1338 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1339 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1340 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1342 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1343 &l2arc_write_max, 0, "max write size");
1344 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1345 &l2arc_write_boost, 0, "extra write during warmup");
1346 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1347 &l2arc_headroom, 0, "number of dev writes");
1348 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1349 &l2arc_feed_secs, 0, "interval seconds");
1350 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1351 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1353 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1354 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1355 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1356 &l2arc_feed_again, 0, "turbo warmup");
1357 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1358 &l2arc_norw, 0, "no reads during writes");
1360 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1361 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1362 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1363 &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1364 "size of anonymous state");
1365 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1366 &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1367 "size of anonymous state");
1369 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1370 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1371 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1372 &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1373 "size of metadata in mru state");
1374 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1375 &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1376 "size of data in mru state");
1378 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1379 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1380 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1381 &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1382 "size of metadata in mru ghost state");
1383 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1384 &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1385 "size of data in mru ghost state");
1387 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1388 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1389 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1390 &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1391 "size of metadata in mfu state");
1392 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1393 &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1394 "size of data in mfu state");
1396 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1397 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1398 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1399 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1400 "size of metadata in mfu ghost state");
1401 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1402 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1403 "size of data in mfu ghost state");
1405 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1406 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1408 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prefetch_ms, CTLFLAG_RW,
1409 &zfs_arc_min_prefetch_ms, 0, "Min life of prefetch block in ms");
1410 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prescient_prefetch_ms, CTLFLAG_RW,
1411 &zfs_arc_min_prescient_prefetch_ms, 0, "Min life of prescient prefetched block in ms");
1417 vdev_t *l2ad_vdev; /* vdev */
1418 spa_t *l2ad_spa; /* spa */
1419 uint64_t l2ad_hand; /* next write location */
1420 uint64_t l2ad_start; /* first addr on device */
1421 uint64_t l2ad_end; /* last addr on device */
1422 boolean_t l2ad_first; /* first sweep through */
1423 boolean_t l2ad_writing; /* currently writing */
1424 kmutex_t l2ad_mtx; /* lock for buffer list */
1425 list_t l2ad_buflist; /* buffer list */
1426 list_node_t l2ad_node; /* device list node */
1427 refcount_t l2ad_alloc; /* allocated bytes */
1430 static list_t L2ARC_dev_list; /* device list */
1431 static list_t *l2arc_dev_list; /* device list pointer */
1432 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1433 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1434 static list_t L2ARC_free_on_write; /* free after write buf list */
1435 static list_t *l2arc_free_on_write; /* free after write list ptr */
1436 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1437 static uint64_t l2arc_ndev; /* number of devices */
1439 typedef struct l2arc_read_callback {
1440 arc_buf_hdr_t *l2rcb_hdr; /* read header */
1441 blkptr_t l2rcb_bp; /* original blkptr */
1442 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1443 int l2rcb_flags; /* original flags */
1444 abd_t *l2rcb_abd; /* temporary buffer */
1445 } l2arc_read_callback_t;
1447 typedef struct l2arc_write_callback {
1448 l2arc_dev_t *l2wcb_dev; /* device info */
1449 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1450 } l2arc_write_callback_t;
1452 typedef struct l2arc_data_free {
1453 /* protected by l2arc_free_on_write_mtx */
1456 arc_buf_contents_t l2df_type;
1457 list_node_t l2df_list_node;
1458 } l2arc_data_free_t;
1460 static kmutex_t l2arc_feed_thr_lock;
1461 static kcondvar_t l2arc_feed_thr_cv;
1462 static uint8_t l2arc_thread_exit;
1464 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1465 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1466 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1467 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1468 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1469 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1470 static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1471 static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
1472 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1473 static boolean_t arc_is_overflowing();
1474 static void arc_buf_watch(arc_buf_t *);
1476 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1477 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1478 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1479 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1481 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1482 static void l2arc_read_done(zio_t *);
1485 l2arc_trim(const arc_buf_hdr_t *hdr)
1487 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1489 ASSERT(HDR_HAS_L2HDR(hdr));
1490 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1492 if (HDR_GET_PSIZE(hdr) != 0) {
1493 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1494 HDR_GET_PSIZE(hdr), 0);
1499 * We use Cityhash for this. It's fast, and has good hash properties without
1500 * requiring any large static buffers.
1503 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1505 return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1508 #define HDR_EMPTY(hdr) \
1509 ((hdr)->b_dva.dva_word[0] == 0 && \
1510 (hdr)->b_dva.dva_word[1] == 0)
1512 #define HDR_EQUAL(spa, dva, birth, hdr) \
1513 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1514 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1515 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1518 buf_discard_identity(arc_buf_hdr_t *hdr)
1520 hdr->b_dva.dva_word[0] = 0;
1521 hdr->b_dva.dva_word[1] = 0;
1525 static arc_buf_hdr_t *
1526 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1528 const dva_t *dva = BP_IDENTITY(bp);
1529 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1530 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1531 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1534 mutex_enter(hash_lock);
1535 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1536 hdr = hdr->b_hash_next) {
1537 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1542 mutex_exit(hash_lock);
1548 * Insert an entry into the hash table. If there is already an element
1549 * equal to elem in the hash table, then the already existing element
1550 * will be returned and the new element will not be inserted.
1551 * Otherwise returns NULL.
1552 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1554 static arc_buf_hdr_t *
1555 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1557 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1558 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1559 arc_buf_hdr_t *fhdr;
1562 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1563 ASSERT(hdr->b_birth != 0);
1564 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1566 if (lockp != NULL) {
1568 mutex_enter(hash_lock);
1570 ASSERT(MUTEX_HELD(hash_lock));
1573 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1574 fhdr = fhdr->b_hash_next, i++) {
1575 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1579 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1580 buf_hash_table.ht_table[idx] = hdr;
1581 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1583 /* collect some hash table performance data */
1585 ARCSTAT_BUMP(arcstat_hash_collisions);
1587 ARCSTAT_BUMP(arcstat_hash_chains);
1589 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1592 ARCSTAT_BUMP(arcstat_hash_elements);
1593 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1599 buf_hash_remove(arc_buf_hdr_t *hdr)
1601 arc_buf_hdr_t *fhdr, **hdrp;
1602 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1604 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1605 ASSERT(HDR_IN_HASH_TABLE(hdr));
1607 hdrp = &buf_hash_table.ht_table[idx];
1608 while ((fhdr = *hdrp) != hdr) {
1609 ASSERT3P(fhdr, !=, NULL);
1610 hdrp = &fhdr->b_hash_next;
1612 *hdrp = hdr->b_hash_next;
1613 hdr->b_hash_next = NULL;
1614 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1616 /* collect some hash table performance data */
1617 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1619 if (buf_hash_table.ht_table[idx] &&
1620 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1621 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1625 * Global data structures and functions for the buf kmem cache.
1627 static kmem_cache_t *hdr_full_cache;
1628 static kmem_cache_t *hdr_l2only_cache;
1629 static kmem_cache_t *buf_cache;
1636 kmem_free(buf_hash_table.ht_table,
1637 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1638 for (i = 0; i < BUF_LOCKS; i++)
1639 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1640 kmem_cache_destroy(hdr_full_cache);
1641 kmem_cache_destroy(hdr_l2only_cache);
1642 kmem_cache_destroy(buf_cache);
1646 * Constructor callback - called when the cache is empty
1647 * and a new buf is requested.
1651 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1653 arc_buf_hdr_t *hdr = vbuf;
1655 bzero(hdr, HDR_FULL_SIZE);
1656 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1657 refcount_create(&hdr->b_l1hdr.b_refcnt);
1658 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1659 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1660 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1667 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1669 arc_buf_hdr_t *hdr = vbuf;
1671 bzero(hdr, HDR_L2ONLY_SIZE);
1672 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1679 buf_cons(void *vbuf, void *unused, int kmflag)
1681 arc_buf_t *buf = vbuf;
1683 bzero(buf, sizeof (arc_buf_t));
1684 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1685 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1691 * Destructor callback - called when a cached buf is
1692 * no longer required.
1696 hdr_full_dest(void *vbuf, void *unused)
1698 arc_buf_hdr_t *hdr = vbuf;
1700 ASSERT(HDR_EMPTY(hdr));
1701 cv_destroy(&hdr->b_l1hdr.b_cv);
1702 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1703 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1704 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1705 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1710 hdr_l2only_dest(void *vbuf, void *unused)
1712 arc_buf_hdr_t *hdr = vbuf;
1714 ASSERT(HDR_EMPTY(hdr));
1715 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1720 buf_dest(void *vbuf, void *unused)
1722 arc_buf_t *buf = vbuf;
1724 mutex_destroy(&buf->b_evict_lock);
1725 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1729 * Reclaim callback -- invoked when memory is low.
1733 hdr_recl(void *unused)
1735 dprintf("hdr_recl called\n");
1737 * umem calls the reclaim func when we destroy the buf cache,
1738 * which is after we do arc_fini().
1741 cv_signal(&arc_reclaim_thread_cv);
1748 uint64_t hsize = 1ULL << 12;
1752 * The hash table is big enough to fill all of physical memory
1753 * with an average block size of zfs_arc_average_blocksize (default 8K).
1754 * By default, the table will take up
1755 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1757 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1760 buf_hash_table.ht_mask = hsize - 1;
1761 buf_hash_table.ht_table =
1762 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1763 if (buf_hash_table.ht_table == NULL) {
1764 ASSERT(hsize > (1ULL << 8));
1769 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1770 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1771 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1772 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1774 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1775 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1777 for (i = 0; i < 256; i++)
1778 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1779 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1781 for (i = 0; i < BUF_LOCKS; i++) {
1782 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1783 NULL, MUTEX_DEFAULT, NULL);
1788 * This is the size that the buf occupies in memory. If the buf is compressed,
1789 * it will correspond to the compressed size. You should use this method of
1790 * getting the buf size unless you explicitly need the logical size.
1793 arc_buf_size(arc_buf_t *buf)
1795 return (ARC_BUF_COMPRESSED(buf) ?
1796 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1800 arc_buf_lsize(arc_buf_t *buf)
1802 return (HDR_GET_LSIZE(buf->b_hdr));
1806 arc_get_compression(arc_buf_t *buf)
1808 return (ARC_BUF_COMPRESSED(buf) ?
1809 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1812 #define ARC_MINTIME (hz>>4) /* 62 ms */
1814 static inline boolean_t
1815 arc_buf_is_shared(arc_buf_t *buf)
1817 boolean_t shared = (buf->b_data != NULL &&
1818 buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1819 abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1820 buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1821 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1822 IMPLY(shared, ARC_BUF_SHARED(buf));
1823 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1826 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1827 * already being shared" requirement prevents us from doing that.
1834 * Free the checksum associated with this header. If there is no checksum, this
1838 arc_cksum_free(arc_buf_hdr_t *hdr)
1840 ASSERT(HDR_HAS_L1HDR(hdr));
1841 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1842 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1843 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1844 hdr->b_l1hdr.b_freeze_cksum = NULL;
1846 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1850 * Return true iff at least one of the bufs on hdr is not compressed.
1853 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1855 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1856 if (!ARC_BUF_COMPRESSED(b)) {
1864 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1865 * matches the checksum that is stored in the hdr. If there is no checksum,
1866 * or if the buf is compressed, this is a no-op.
1869 arc_cksum_verify(arc_buf_t *buf)
1871 arc_buf_hdr_t *hdr = buf->b_hdr;
1874 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1877 if (ARC_BUF_COMPRESSED(buf)) {
1878 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1879 arc_hdr_has_uncompressed_buf(hdr));
1883 ASSERT(HDR_HAS_L1HDR(hdr));
1885 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1886 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1887 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1891 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1892 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1893 panic("buffer modified while frozen!");
1894 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1898 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1900 enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1901 boolean_t valid_cksum;
1903 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1904 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1907 * We rely on the blkptr's checksum to determine if the block
1908 * is valid or not. When compressed arc is enabled, the l2arc
1909 * writes the block to the l2arc just as it appears in the pool.
1910 * This allows us to use the blkptr's checksum to validate the
1911 * data that we just read off of the l2arc without having to store
1912 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1913 * arc is disabled, then the data written to the l2arc is always
1914 * uncompressed and won't match the block as it exists in the main
1915 * pool. When this is the case, we must first compress it if it is
1916 * compressed on the main pool before we can validate the checksum.
1918 if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1919 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1920 uint64_t lsize = HDR_GET_LSIZE(hdr);
1923 abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
1924 csize = zio_compress_data(compress, zio->io_abd,
1925 abd_to_buf(cdata), lsize);
1927 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1928 if (csize < HDR_GET_PSIZE(hdr)) {
1930 * Compressed blocks are always a multiple of the
1931 * smallest ashift in the pool. Ideally, we would
1932 * like to round up the csize to the next
1933 * spa_min_ashift but that value may have changed
1934 * since the block was last written. Instead,
1935 * we rely on the fact that the hdr's psize
1936 * was set to the psize of the block when it was
1937 * last written. We set the csize to that value
1938 * and zero out any part that should not contain
1941 abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1942 csize = HDR_GET_PSIZE(hdr);
1944 zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1948 * Block pointers always store the checksum for the logical data.
1949 * If the block pointer has the gang bit set, then the checksum
1950 * it represents is for the reconstituted data and not for an
1951 * individual gang member. The zio pipeline, however, must be able to
1952 * determine the checksum of each of the gang constituents so it
1953 * treats the checksum comparison differently than what we need
1954 * for l2arc blocks. This prevents us from using the
1955 * zio_checksum_error() interface directly. Instead we must call the
1956 * zio_checksum_error_impl() so that we can ensure the checksum is
1957 * generated using the correct checksum algorithm and accounts for the
1958 * logical I/O size and not just a gang fragment.
1960 valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1961 BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1962 zio->io_offset, NULL) == 0);
1963 zio_pop_transforms(zio);
1964 return (valid_cksum);
1968 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1969 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1970 * isn't modified later on. If buf is compressed or there is already a checksum
1971 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1974 arc_cksum_compute(arc_buf_t *buf)
1976 arc_buf_hdr_t *hdr = buf->b_hdr;
1978 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1981 ASSERT(HDR_HAS_L1HDR(hdr));
1983 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1984 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1985 ASSERT(arc_hdr_has_uncompressed_buf(hdr));
1986 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1988 } else if (ARC_BUF_COMPRESSED(buf)) {
1989 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1993 ASSERT(!ARC_BUF_COMPRESSED(buf));
1994 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1996 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1997 hdr->b_l1hdr.b_freeze_cksum);
1998 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2006 typedef struct procctl {
2014 arc_buf_unwatch(arc_buf_t *buf)
2021 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2022 ctl.prwatch.pr_size = 0;
2023 ctl.prwatch.pr_wflags = 0;
2024 result = write(arc_procfd, &ctl, sizeof (ctl));
2025 ASSERT3U(result, ==, sizeof (ctl));
2032 arc_buf_watch(arc_buf_t *buf)
2039 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2040 ctl.prwatch.pr_size = arc_buf_size(buf);
2041 ctl.prwatch.pr_wflags = WA_WRITE;
2042 result = write(arc_procfd, &ctl, sizeof (ctl));
2043 ASSERT3U(result, ==, sizeof (ctl));
2047 #endif /* illumos */
2049 static arc_buf_contents_t
2050 arc_buf_type(arc_buf_hdr_t *hdr)
2052 arc_buf_contents_t type;
2053 if (HDR_ISTYPE_METADATA(hdr)) {
2054 type = ARC_BUFC_METADATA;
2056 type = ARC_BUFC_DATA;
2058 VERIFY3U(hdr->b_type, ==, type);
2063 arc_is_metadata(arc_buf_t *buf)
2065 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
2069 arc_bufc_to_flags(arc_buf_contents_t type)
2073 /* metadata field is 0 if buffer contains normal data */
2075 case ARC_BUFC_METADATA:
2076 return (ARC_FLAG_BUFC_METADATA);
2080 panic("undefined ARC buffer type!");
2081 return ((uint32_t)-1);
2085 arc_buf_thaw(arc_buf_t *buf)
2087 arc_buf_hdr_t *hdr = buf->b_hdr;
2089 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2090 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2092 arc_cksum_verify(buf);
2095 * Compressed buffers do not manipulate the b_freeze_cksum or
2096 * allocate b_thawed.
2098 if (ARC_BUF_COMPRESSED(buf)) {
2099 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2100 arc_hdr_has_uncompressed_buf(hdr));
2104 ASSERT(HDR_HAS_L1HDR(hdr));
2105 arc_cksum_free(hdr);
2107 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
2109 if (zfs_flags & ZFS_DEBUG_MODIFY) {
2110 if (hdr->b_l1hdr.b_thawed != NULL)
2111 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2112 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
2116 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2119 arc_buf_unwatch(buf);
2124 arc_buf_freeze(arc_buf_t *buf)
2126 arc_buf_hdr_t *hdr = buf->b_hdr;
2127 kmutex_t *hash_lock;
2129 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2132 if (ARC_BUF_COMPRESSED(buf)) {
2133 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2134 arc_hdr_has_uncompressed_buf(hdr));
2138 hash_lock = HDR_LOCK(hdr);
2139 mutex_enter(hash_lock);
2141 ASSERT(HDR_HAS_L1HDR(hdr));
2142 ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2143 hdr->b_l1hdr.b_state == arc_anon);
2144 arc_cksum_compute(buf);
2145 mutex_exit(hash_lock);
2149 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2150 * the following functions should be used to ensure that the flags are
2151 * updated in a thread-safe way. When manipulating the flags either
2152 * the hash_lock must be held or the hdr must be undiscoverable. This
2153 * ensures that we're not racing with any other threads when updating
2157 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2159 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2160 hdr->b_flags |= flags;
2164 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2166 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2167 hdr->b_flags &= ~flags;
2171 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2172 * done in a special way since we have to clear and set bits
2173 * at the same time. Consumers that wish to set the compression bits
2174 * must use this function to ensure that the flags are updated in
2175 * thread-safe manner.
2178 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2180 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2183 * Holes and embedded blocks will always have a psize = 0 so
2184 * we ignore the compression of the blkptr and set the
2185 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2186 * Holes and embedded blocks remain anonymous so we don't
2187 * want to uncompress them. Mark them as uncompressed.
2189 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2190 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2191 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
2192 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2193 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2195 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2196 HDR_SET_COMPRESS(hdr, cmp);
2197 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2198 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2203 * Looks for another buf on the same hdr which has the data decompressed, copies
2204 * from it, and returns true. If no such buf exists, returns false.
2207 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
2209 arc_buf_hdr_t *hdr = buf->b_hdr;
2210 boolean_t copied = B_FALSE;
2212 ASSERT(HDR_HAS_L1HDR(hdr));
2213 ASSERT3P(buf->b_data, !=, NULL);
2214 ASSERT(!ARC_BUF_COMPRESSED(buf));
2216 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
2217 from = from->b_next) {
2218 /* can't use our own data buffer */
2223 if (!ARC_BUF_COMPRESSED(from)) {
2224 bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
2231 * There were no decompressed bufs, so there should not be a
2232 * checksum on the hdr either.
2234 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
2240 * Given a buf that has a data buffer attached to it, this function will
2241 * efficiently fill the buf with data of the specified compression setting from
2242 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2243 * are already sharing a data buf, no copy is performed.
2245 * If the buf is marked as compressed but uncompressed data was requested, this
2246 * will allocate a new data buffer for the buf, remove that flag, and fill the
2247 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2248 * uncompressed data, and (since we haven't added support for it yet) if you
2249 * want compressed data your buf must already be marked as compressed and have
2250 * the correct-sized data buffer.
2253 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
2255 arc_buf_hdr_t *hdr = buf->b_hdr;
2256 boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2257 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2259 ASSERT3P(buf->b_data, !=, NULL);
2260 IMPLY(compressed, hdr_compressed);
2261 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2263 if (hdr_compressed == compressed) {
2264 if (!arc_buf_is_shared(buf)) {
2265 abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
2269 ASSERT(hdr_compressed);
2270 ASSERT(!compressed);
2271 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2274 * If the buf is sharing its data with the hdr, unlink it and
2275 * allocate a new data buffer for the buf.
2277 if (arc_buf_is_shared(buf)) {
2278 ASSERT(ARC_BUF_COMPRESSED(buf));
2280 /* We need to give the buf it's own b_data */
2281 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2283 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2284 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2286 /* Previously overhead was 0; just add new overhead */
2287 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2288 } else if (ARC_BUF_COMPRESSED(buf)) {
2289 /* We need to reallocate the buf's b_data */
2290 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2293 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2295 /* We increased the size of b_data; update overhead */
2296 ARCSTAT_INCR(arcstat_overhead_size,
2297 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2301 * Regardless of the buf's previous compression settings, it
2302 * should not be compressed at the end of this function.
2304 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2307 * Try copying the data from another buf which already has a
2308 * decompressed version. If that's not possible, it's time to
2309 * bite the bullet and decompress the data from the hdr.
2311 if (arc_buf_try_copy_decompressed_data(buf)) {
2312 /* Skip byteswapping and checksumming (already done) */
2313 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
2316 int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2317 hdr->b_l1hdr.b_pabd, buf->b_data,
2318 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2321 * Absent hardware errors or software bugs, this should
2322 * be impossible, but log it anyway so we can debug it.
2326 "hdr %p, compress %d, psize %d, lsize %d",
2327 hdr, HDR_GET_COMPRESS(hdr),
2328 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2329 return (SET_ERROR(EIO));
2334 /* Byteswap the buf's data if necessary */
2335 if (bswap != DMU_BSWAP_NUMFUNCS) {
2336 ASSERT(!HDR_SHARED_DATA(hdr));
2337 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2338 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2341 /* Compute the hdr's checksum if necessary */
2342 arc_cksum_compute(buf);
2348 arc_decompress(arc_buf_t *buf)
2350 return (arc_buf_fill(buf, B_FALSE));
2354 * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2357 arc_hdr_size(arc_buf_hdr_t *hdr)
2361 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2362 HDR_GET_PSIZE(hdr) > 0) {
2363 size = HDR_GET_PSIZE(hdr);
2365 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2366 size = HDR_GET_LSIZE(hdr);
2372 * Increment the amount of evictable space in the arc_state_t's refcount.
2373 * We account for the space used by the hdr and the arc buf individually
2374 * so that we can add and remove them from the refcount individually.
2377 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2379 arc_buf_contents_t type = arc_buf_type(hdr);
2381 ASSERT(HDR_HAS_L1HDR(hdr));
2383 if (GHOST_STATE(state)) {
2384 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2385 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2386 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2387 (void) refcount_add_many(&state->arcs_esize[type],
2388 HDR_GET_LSIZE(hdr), hdr);
2392 ASSERT(!GHOST_STATE(state));
2393 if (hdr->b_l1hdr.b_pabd != NULL) {
2394 (void) refcount_add_many(&state->arcs_esize[type],
2395 arc_hdr_size(hdr), hdr);
2397 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2398 buf = buf->b_next) {
2399 if (arc_buf_is_shared(buf))
2401 (void) refcount_add_many(&state->arcs_esize[type],
2402 arc_buf_size(buf), buf);
2407 * Decrement the amount of evictable space in the arc_state_t's refcount.
2408 * We account for the space used by the hdr and the arc buf individually
2409 * so that we can add and remove them from the refcount individually.
2412 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2414 arc_buf_contents_t type = arc_buf_type(hdr);
2416 ASSERT(HDR_HAS_L1HDR(hdr));
2418 if (GHOST_STATE(state)) {
2419 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2420 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2421 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2422 (void) refcount_remove_many(&state->arcs_esize[type],
2423 HDR_GET_LSIZE(hdr), hdr);
2427 ASSERT(!GHOST_STATE(state));
2428 if (hdr->b_l1hdr.b_pabd != NULL) {
2429 (void) refcount_remove_many(&state->arcs_esize[type],
2430 arc_hdr_size(hdr), hdr);
2432 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2433 buf = buf->b_next) {
2434 if (arc_buf_is_shared(buf))
2436 (void) refcount_remove_many(&state->arcs_esize[type],
2437 arc_buf_size(buf), buf);
2442 * Add a reference to this hdr indicating that someone is actively
2443 * referencing that memory. When the refcount transitions from 0 to 1,
2444 * we remove it from the respective arc_state_t list to indicate that
2445 * it is not evictable.
2448 add_reference(arc_buf_hdr_t *hdr, void *tag)
2450 ASSERT(HDR_HAS_L1HDR(hdr));
2451 if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2452 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2453 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2454 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2457 arc_state_t *state = hdr->b_l1hdr.b_state;
2459 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2460 (state != arc_anon)) {
2461 /* We don't use the L2-only state list. */
2462 if (state != arc_l2c_only) {
2463 multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2465 arc_evictable_space_decrement(hdr, state);
2467 /* remove the prefetch flag if we get a reference */
2468 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2473 * Remove a reference from this hdr. When the reference transitions from
2474 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2475 * list making it eligible for eviction.
2478 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2481 arc_state_t *state = hdr->b_l1hdr.b_state;
2483 ASSERT(HDR_HAS_L1HDR(hdr));
2484 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2485 ASSERT(!GHOST_STATE(state));
2488 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2489 * check to prevent usage of the arc_l2c_only list.
2491 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2492 (state != arc_anon)) {
2493 multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2494 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2495 arc_evictable_space_increment(hdr, state);
2501 * Move the supplied buffer to the indicated state. The hash lock
2502 * for the buffer must be held by the caller.
2505 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2506 kmutex_t *hash_lock)
2508 arc_state_t *old_state;
2511 boolean_t update_old, update_new;
2512 arc_buf_contents_t buftype = arc_buf_type(hdr);
2515 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2516 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2517 * L1 hdr doesn't always exist when we change state to arc_anon before
2518 * destroying a header, in which case reallocating to add the L1 hdr is
2521 if (HDR_HAS_L1HDR(hdr)) {
2522 old_state = hdr->b_l1hdr.b_state;
2523 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2524 bufcnt = hdr->b_l1hdr.b_bufcnt;
2525 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
2527 old_state = arc_l2c_only;
2530 update_old = B_FALSE;
2532 update_new = update_old;
2534 ASSERT(MUTEX_HELD(hash_lock));
2535 ASSERT3P(new_state, !=, old_state);
2536 ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2537 ASSERT(old_state != arc_anon || bufcnt <= 1);
2540 * If this buffer is evictable, transfer it from the
2541 * old state list to the new state list.
2544 if (old_state != arc_anon && old_state != arc_l2c_only) {
2545 ASSERT(HDR_HAS_L1HDR(hdr));
2546 multilist_remove(old_state->arcs_list[buftype], hdr);
2548 if (GHOST_STATE(old_state)) {
2550 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2551 update_old = B_TRUE;
2553 arc_evictable_space_decrement(hdr, old_state);
2555 if (new_state != arc_anon && new_state != arc_l2c_only) {
2558 * An L1 header always exists here, since if we're
2559 * moving to some L1-cached state (i.e. not l2c_only or
2560 * anonymous), we realloc the header to add an L1hdr
2563 ASSERT(HDR_HAS_L1HDR(hdr));
2564 multilist_insert(new_state->arcs_list[buftype], hdr);
2566 if (GHOST_STATE(new_state)) {
2568 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2569 update_new = B_TRUE;
2571 arc_evictable_space_increment(hdr, new_state);
2575 ASSERT(!HDR_EMPTY(hdr));
2576 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2577 buf_hash_remove(hdr);
2579 /* adjust state sizes (ignore arc_l2c_only) */
2581 if (update_new && new_state != arc_l2c_only) {
2582 ASSERT(HDR_HAS_L1HDR(hdr));
2583 if (GHOST_STATE(new_state)) {
2587 * When moving a header to a ghost state, we first
2588 * remove all arc buffers. Thus, we'll have a
2589 * bufcnt of zero, and no arc buffer to use for
2590 * the reference. As a result, we use the arc
2591 * header pointer for the reference.
2593 (void) refcount_add_many(&new_state->arcs_size,
2594 HDR_GET_LSIZE(hdr), hdr);
2595 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2597 uint32_t buffers = 0;
2600 * Each individual buffer holds a unique reference,
2601 * thus we must remove each of these references one
2604 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2605 buf = buf->b_next) {
2606 ASSERT3U(bufcnt, !=, 0);
2610 * When the arc_buf_t is sharing the data
2611 * block with the hdr, the owner of the
2612 * reference belongs to the hdr. Only
2613 * add to the refcount if the arc_buf_t is
2616 if (arc_buf_is_shared(buf))
2619 (void) refcount_add_many(&new_state->arcs_size,
2620 arc_buf_size(buf), buf);
2622 ASSERT3U(bufcnt, ==, buffers);
2624 if (hdr->b_l1hdr.b_pabd != NULL) {
2625 (void) refcount_add_many(&new_state->arcs_size,
2626 arc_hdr_size(hdr), hdr);
2628 ASSERT(GHOST_STATE(old_state));
2633 if (update_old && old_state != arc_l2c_only) {
2634 ASSERT(HDR_HAS_L1HDR(hdr));
2635 if (GHOST_STATE(old_state)) {
2637 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2640 * When moving a header off of a ghost state,
2641 * the header will not contain any arc buffers.
2642 * We use the arc header pointer for the reference
2643 * which is exactly what we did when we put the
2644 * header on the ghost state.
2647 (void) refcount_remove_many(&old_state->arcs_size,
2648 HDR_GET_LSIZE(hdr), hdr);
2650 uint32_t buffers = 0;
2653 * Each individual buffer holds a unique reference,
2654 * thus we must remove each of these references one
2657 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2658 buf = buf->b_next) {
2659 ASSERT3U(bufcnt, !=, 0);
2663 * When the arc_buf_t is sharing the data
2664 * block with the hdr, the owner of the
2665 * reference belongs to the hdr. Only
2666 * add to the refcount if the arc_buf_t is
2669 if (arc_buf_is_shared(buf))
2672 (void) refcount_remove_many(
2673 &old_state->arcs_size, arc_buf_size(buf),
2676 ASSERT3U(bufcnt, ==, buffers);
2677 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2678 (void) refcount_remove_many(
2679 &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2683 if (HDR_HAS_L1HDR(hdr))
2684 hdr->b_l1hdr.b_state = new_state;
2687 * L2 headers should never be on the L2 state list since they don't
2688 * have L1 headers allocated.
2690 ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2691 multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2695 arc_space_consume(uint64_t space, arc_space_type_t type)
2697 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2700 case ARC_SPACE_DATA:
2701 aggsum_add(&astat_data_size, space);
2703 case ARC_SPACE_META:
2704 aggsum_add(&astat_metadata_size, space);
2706 case ARC_SPACE_OTHER:
2707 aggsum_add(&astat_other_size, space);
2709 case ARC_SPACE_HDRS:
2710 aggsum_add(&astat_hdr_size, space);
2712 case ARC_SPACE_L2HDRS:
2713 aggsum_add(&astat_l2_hdr_size, space);
2717 if (type != ARC_SPACE_DATA)
2718 aggsum_add(&arc_meta_used, space);
2720 aggsum_add(&arc_size, space);
2724 arc_space_return(uint64_t space, arc_space_type_t type)
2726 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2729 case ARC_SPACE_DATA:
2730 aggsum_add(&astat_data_size, -space);
2732 case ARC_SPACE_META:
2733 aggsum_add(&astat_metadata_size, -space);
2735 case ARC_SPACE_OTHER:
2736 aggsum_add(&astat_other_size, -space);
2738 case ARC_SPACE_HDRS:
2739 aggsum_add(&astat_hdr_size, -space);
2741 case ARC_SPACE_L2HDRS:
2742 aggsum_add(&astat_l2_hdr_size, -space);
2746 if (type != ARC_SPACE_DATA) {
2747 ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
2749 * We use the upper bound here rather than the precise value
2750 * because the arc_meta_max value doesn't need to be
2751 * precise. It's only consumed by humans via arcstats.
2753 if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
2754 arc_meta_max = aggsum_upper_bound(&arc_meta_used);
2755 aggsum_add(&arc_meta_used, -space);
2758 ASSERT(aggsum_compare(&arc_size, space) >= 0);
2759 aggsum_add(&arc_size, -space);
2763 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2764 * with the hdr's b_pabd.
2767 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2770 * The criteria for sharing a hdr's data are:
2771 * 1. the hdr's compression matches the buf's compression
2772 * 2. the hdr doesn't need to be byteswapped
2773 * 3. the hdr isn't already being shared
2774 * 4. the buf is either compressed or it is the last buf in the hdr list
2776 * Criterion #4 maintains the invariant that shared uncompressed
2777 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2778 * might ask, "if a compressed buf is allocated first, won't that be the
2779 * last thing in the list?", but in that case it's impossible to create
2780 * a shared uncompressed buf anyway (because the hdr must be compressed
2781 * to have the compressed buf). You might also think that #3 is
2782 * sufficient to make this guarantee, however it's possible
2783 * (specifically in the rare L2ARC write race mentioned in
2784 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2785 * is sharable, but wasn't at the time of its allocation. Rather than
2786 * allow a new shared uncompressed buf to be created and then shuffle
2787 * the list around to make it the last element, this simply disallows
2788 * sharing if the new buf isn't the first to be added.
2790 ASSERT3P(buf->b_hdr, ==, hdr);
2791 boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2792 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2793 return (buf_compressed == hdr_compressed &&
2794 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2795 !HDR_SHARED_DATA(hdr) &&
2796 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2800 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2801 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2802 * copy was made successfully, or an error code otherwise.
2805 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2806 boolean_t fill, arc_buf_t **ret)
2810 ASSERT(HDR_HAS_L1HDR(hdr));
2811 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2812 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2813 hdr->b_type == ARC_BUFC_METADATA);
2814 ASSERT3P(ret, !=, NULL);
2815 ASSERT3P(*ret, ==, NULL);
2817 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2820 buf->b_next = hdr->b_l1hdr.b_buf;
2823 add_reference(hdr, tag);
2826 * We're about to change the hdr's b_flags. We must either
2827 * hold the hash_lock or be undiscoverable.
2829 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2832 * Only honor requests for compressed bufs if the hdr is actually
2835 if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2836 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2839 * If the hdr's data can be shared then we share the data buffer and
2840 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2841 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2842 * buffer to store the buf's data.
2844 * There are two additional restrictions here because we're sharing
2845 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2846 * actively involved in an L2ARC write, because if this buf is used by
2847 * an arc_write() then the hdr's data buffer will be released when the
2848 * write completes, even though the L2ARC write might still be using it.
2849 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2850 * need to be ABD-aware.
2852 boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2853 abd_is_linear(hdr->b_l1hdr.b_pabd);
2855 /* Set up b_data and sharing */
2857 buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2858 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2859 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2862 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2863 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2865 VERIFY3P(buf->b_data, !=, NULL);
2867 hdr->b_l1hdr.b_buf = buf;
2868 hdr->b_l1hdr.b_bufcnt += 1;
2871 * If the user wants the data from the hdr, we need to either copy or
2872 * decompress the data.
2875 return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
2881 static char *arc_onloan_tag = "onloan";
2884 arc_loaned_bytes_update(int64_t delta)
2886 atomic_add_64(&arc_loaned_bytes, delta);
2888 /* assert that it did not wrap around */
2889 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2893 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2894 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2895 * buffers must be returned to the arc before they can be used by the DMU or
2899 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2901 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2902 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2904 arc_loaned_bytes_update(arc_buf_size(buf));
2910 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2911 enum zio_compress compression_type)
2913 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2914 psize, lsize, compression_type);
2916 arc_loaned_bytes_update(arc_buf_size(buf));
2923 * Return a loaned arc buffer to the arc.
2926 arc_return_buf(arc_buf_t *buf, void *tag)
2928 arc_buf_hdr_t *hdr = buf->b_hdr;
2930 ASSERT3P(buf->b_data, !=, NULL);
2931 ASSERT(HDR_HAS_L1HDR(hdr));
2932 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2933 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2935 arc_loaned_bytes_update(-arc_buf_size(buf));
2938 /* Detach an arc_buf from a dbuf (tag) */
2940 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2942 arc_buf_hdr_t *hdr = buf->b_hdr;
2944 ASSERT3P(buf->b_data, !=, NULL);
2945 ASSERT(HDR_HAS_L1HDR(hdr));
2946 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2947 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2949 arc_loaned_bytes_update(arc_buf_size(buf));
2953 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2955 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2958 df->l2df_size = size;
2959 df->l2df_type = type;
2960 mutex_enter(&l2arc_free_on_write_mtx);
2961 list_insert_head(l2arc_free_on_write, df);
2962 mutex_exit(&l2arc_free_on_write_mtx);
2966 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2968 arc_state_t *state = hdr->b_l1hdr.b_state;
2969 arc_buf_contents_t type = arc_buf_type(hdr);
2970 uint64_t size = arc_hdr_size(hdr);
2972 /* protected by hash lock, if in the hash table */
2973 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2974 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2975 ASSERT(state != arc_anon && state != arc_l2c_only);
2977 (void) refcount_remove_many(&state->arcs_esize[type],
2980 (void) refcount_remove_many(&state->arcs_size, size, hdr);
2981 if (type == ARC_BUFC_METADATA) {
2982 arc_space_return(size, ARC_SPACE_META);
2984 ASSERT(type == ARC_BUFC_DATA);
2985 arc_space_return(size, ARC_SPACE_DATA);
2988 l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2992 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2993 * data buffer, we transfer the refcount ownership to the hdr and update
2994 * the appropriate kstats.
2997 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2999 arc_state_t *state = hdr->b_l1hdr.b_state;
3001 ASSERT(arc_can_share(hdr, buf));
3002 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3003 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3006 * Start sharing the data buffer. We transfer the
3007 * refcount ownership to the hdr since it always owns
3008 * the refcount whenever an arc_buf_t is shared.
3010 refcount_transfer_ownership(&state->arcs_size, buf, hdr);
3011 hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3012 abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3013 HDR_ISTYPE_METADATA(hdr));
3014 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3015 buf->b_flags |= ARC_BUF_FLAG_SHARED;
3018 * Since we've transferred ownership to the hdr we need
3019 * to increment its compressed and uncompressed kstats and
3020 * decrement the overhead size.
3022 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3023 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3024 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3028 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3030 arc_state_t *state = hdr->b_l1hdr.b_state;
3032 ASSERT(arc_buf_is_shared(buf));
3033 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3034 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3037 * We are no longer sharing this buffer so we need
3038 * to transfer its ownership to the rightful owner.
3040 refcount_transfer_ownership(&state->arcs_size, hdr, buf);
3041 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3042 abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3043 abd_put(hdr->b_l1hdr.b_pabd);
3044 hdr->b_l1hdr.b_pabd = NULL;
3045 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3048 * Since the buffer is no longer shared between
3049 * the arc buf and the hdr, count it as overhead.
3051 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3052 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3053 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3057 * Remove an arc_buf_t from the hdr's buf list and return the last
3058 * arc_buf_t on the list. If no buffers remain on the list then return
3062 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3064 ASSERT(HDR_HAS_L1HDR(hdr));
3065 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3067 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3068 arc_buf_t *lastbuf = NULL;
3071 * Remove the buf from the hdr list and locate the last
3072 * remaining buffer on the list.
3074 while (*bufp != NULL) {
3076 *bufp = buf->b_next;
3079 * If we've removed a buffer in the middle of
3080 * the list then update the lastbuf and update
3083 if (*bufp != NULL) {
3085 bufp = &(*bufp)->b_next;
3089 ASSERT3P(lastbuf, !=, buf);
3090 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
3091 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
3092 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3098 * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
3102 arc_buf_destroy_impl(arc_buf_t *buf)
3104 arc_buf_hdr_t *hdr = buf->b_hdr;
3107 * Free up the data associated with the buf but only if we're not
3108 * sharing this with the hdr. If we are sharing it with the hdr, the
3109 * hdr is responsible for doing the free.
3111 if (buf->b_data != NULL) {
3113 * We're about to change the hdr's b_flags. We must either
3114 * hold the hash_lock or be undiscoverable.
3116 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3118 arc_cksum_verify(buf);
3120 arc_buf_unwatch(buf);
3123 if (arc_buf_is_shared(buf)) {
3124 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3126 uint64_t size = arc_buf_size(buf);
3127 arc_free_data_buf(hdr, buf->b_data, size, buf);
3128 ARCSTAT_INCR(arcstat_overhead_size, -size);
3132 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3133 hdr->b_l1hdr.b_bufcnt -= 1;
3136 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3138 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3140 * If the current arc_buf_t is sharing its data buffer with the
3141 * hdr, then reassign the hdr's b_pabd to share it with the new
3142 * buffer at the end of the list. The shared buffer is always
3143 * the last one on the hdr's buffer list.
3145 * There is an equivalent case for compressed bufs, but since
3146 * they aren't guaranteed to be the last buf in the list and
3147 * that is an exceedingly rare case, we just allow that space be
3148 * wasted temporarily.
3150 if (lastbuf != NULL) {
3151 /* Only one buf can be shared at once */
3152 VERIFY(!arc_buf_is_shared(lastbuf));
3153 /* hdr is uncompressed so can't have compressed buf */
3154 VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3156 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3157 arc_hdr_free_pabd(hdr);
3160 * We must setup a new shared block between the
3161 * last buffer and the hdr. The data would have
3162 * been allocated by the arc buf so we need to transfer
3163 * ownership to the hdr since it's now being shared.
3165 arc_share_buf(hdr, lastbuf);
3167 } else if (HDR_SHARED_DATA(hdr)) {
3169 * Uncompressed shared buffers are always at the end
3170 * of the list. Compressed buffers don't have the
3171 * same requirements. This makes it hard to
3172 * simply assert that the lastbuf is shared so
3173 * we rely on the hdr's compression flags to determine
3174 * if we have a compressed, shared buffer.
3176 ASSERT3P(lastbuf, !=, NULL);
3177 ASSERT(arc_buf_is_shared(lastbuf) ||
3178 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
3182 * Free the checksum if we're removing the last uncompressed buf from
3185 if (!arc_hdr_has_uncompressed_buf(hdr)) {
3186 arc_cksum_free(hdr);
3189 /* clean up the buf */
3191 kmem_cache_free(buf_cache, buf);
3195 arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
3197 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3198 ASSERT(HDR_HAS_L1HDR(hdr));
3199 ASSERT(!HDR_SHARED_DATA(hdr));
3201 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3202 hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
3203 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3204 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3206 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3207 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3211 arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
3213 ASSERT(HDR_HAS_L1HDR(hdr));
3214 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3217 * If the hdr is currently being written to the l2arc then
3218 * we defer freeing the data by adding it to the l2arc_free_on_write
3219 * list. The l2arc will free the data once it's finished
3220 * writing it to the l2arc device.
3222 if (HDR_L2_WRITING(hdr)) {
3223 arc_hdr_free_on_write(hdr);
3224 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3226 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
3227 arc_hdr_size(hdr), hdr);
3229 hdr->b_l1hdr.b_pabd = NULL;
3230 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3232 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3233 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3236 static arc_buf_hdr_t *
3237 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3238 enum zio_compress compression_type, arc_buf_contents_t type)
3242 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3244 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3245 ASSERT(HDR_EMPTY(hdr));
3246 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3247 ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3248 HDR_SET_PSIZE(hdr, psize);
3249 HDR_SET_LSIZE(hdr, lsize);
3253 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3254 arc_hdr_set_compress(hdr, compression_type);
3256 hdr->b_l1hdr.b_state = arc_anon;
3257 hdr->b_l1hdr.b_arc_access = 0;
3258 hdr->b_l1hdr.b_bufcnt = 0;
3259 hdr->b_l1hdr.b_buf = NULL;
3262 * Allocate the hdr's buffer. This will contain either
3263 * the compressed or uncompressed data depending on the block
3264 * it references and compressed arc enablement.
3266 arc_hdr_alloc_pabd(hdr);
3267 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3273 * Transition between the two allocation states for the arc_buf_hdr struct.
3274 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3275 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3276 * version is used when a cache buffer is only in the L2ARC in order to reduce
3279 static arc_buf_hdr_t *
3280 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3282 ASSERT(HDR_HAS_L2HDR(hdr));
3284 arc_buf_hdr_t *nhdr;
3285 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3287 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3288 (old == hdr_l2only_cache && new == hdr_full_cache));
3290 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3292 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3293 buf_hash_remove(hdr);
3295 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3297 if (new == hdr_full_cache) {
3298 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3300 * arc_access and arc_change_state need to be aware that a
3301 * header has just come out of L2ARC, so we set its state to
3302 * l2c_only even though it's about to change.
3304 nhdr->b_l1hdr.b_state = arc_l2c_only;
3306 /* Verify previous threads set to NULL before freeing */
3307 ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
3309 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3310 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3311 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3314 * If we've reached here, We must have been called from
3315 * arc_evict_hdr(), as such we should have already been
3316 * removed from any ghost list we were previously on
3317 * (which protects us from racing with arc_evict_state),
3318 * thus no locking is needed during this check.
3320 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3323 * A buffer must not be moved into the arc_l2c_only
3324 * state if it's not finished being written out to the
3325 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3326 * might try to be accessed, even though it was removed.
3328 VERIFY(!HDR_L2_WRITING(hdr));
3329 VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3332 if (hdr->b_l1hdr.b_thawed != NULL) {
3333 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3334 hdr->b_l1hdr.b_thawed = NULL;
3338 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3341 * The header has been reallocated so we need to re-insert it into any
3344 (void) buf_hash_insert(nhdr, NULL);
3346 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3348 mutex_enter(&dev->l2ad_mtx);
3351 * We must place the realloc'ed header back into the list at
3352 * the same spot. Otherwise, if it's placed earlier in the list,
3353 * l2arc_write_buffers() could find it during the function's
3354 * write phase, and try to write it out to the l2arc.
3356 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3357 list_remove(&dev->l2ad_buflist, hdr);
3359 mutex_exit(&dev->l2ad_mtx);
3362 * Since we're using the pointer address as the tag when
3363 * incrementing and decrementing the l2ad_alloc refcount, we
3364 * must remove the old pointer (that we're about to destroy) and
3365 * add the new pointer to the refcount. Otherwise we'd remove
3366 * the wrong pointer address when calling arc_hdr_destroy() later.
3369 (void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3370 (void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3372 buf_discard_identity(hdr);
3373 kmem_cache_free(old, hdr);
3379 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3380 * The buf is returned thawed since we expect the consumer to modify it.
3383 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3385 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3386 ZIO_COMPRESS_OFF, type);
3387 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3389 arc_buf_t *buf = NULL;
3390 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3397 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3398 * for bufs containing metadata.
3401 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3402 enum zio_compress compression_type)
3404 ASSERT3U(lsize, >, 0);
3405 ASSERT3U(lsize, >=, psize);
3406 ASSERT(compression_type > ZIO_COMPRESS_OFF);
3407 ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3409 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3410 compression_type, ARC_BUFC_DATA);
3411 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3413 arc_buf_t *buf = NULL;
3414 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3416 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3418 if (!arc_buf_is_shared(buf)) {
3420 * To ensure that the hdr has the correct data in it if we call
3421 * arc_decompress() on this buf before it's been written to
3422 * disk, it's easiest if we just set up sharing between the
3425 ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3426 arc_hdr_free_pabd(hdr);
3427 arc_share_buf(hdr, buf);
3434 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3436 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3437 l2arc_dev_t *dev = l2hdr->b_dev;
3438 uint64_t psize = arc_hdr_size(hdr);
3440 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3441 ASSERT(HDR_HAS_L2HDR(hdr));
3443 list_remove(&dev->l2ad_buflist, hdr);
3445 ARCSTAT_INCR(arcstat_l2_psize, -psize);
3446 ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3448 vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3450 (void) refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3451 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3455 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3457 if (HDR_HAS_L1HDR(hdr)) {
3458 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3459 hdr->b_l1hdr.b_bufcnt > 0);
3460 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3461 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3463 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3464 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3466 if (!HDR_EMPTY(hdr))
3467 buf_discard_identity(hdr);
3469 if (HDR_HAS_L2HDR(hdr)) {
3470 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3471 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3474 mutex_enter(&dev->l2ad_mtx);
3477 * Even though we checked this conditional above, we
3478 * need to check this again now that we have the
3479 * l2ad_mtx. This is because we could be racing with
3480 * another thread calling l2arc_evict() which might have
3481 * destroyed this header's L2 portion as we were waiting
3482 * to acquire the l2ad_mtx. If that happens, we don't
3483 * want to re-destroy the header's L2 portion.
3485 if (HDR_HAS_L2HDR(hdr)) {
3487 arc_hdr_l2hdr_destroy(hdr);
3491 mutex_exit(&dev->l2ad_mtx);
3494 if (HDR_HAS_L1HDR(hdr)) {
3495 arc_cksum_free(hdr);
3497 while (hdr->b_l1hdr.b_buf != NULL)
3498 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3501 if (hdr->b_l1hdr.b_thawed != NULL) {
3502 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3503 hdr->b_l1hdr.b_thawed = NULL;
3507 if (hdr->b_l1hdr.b_pabd != NULL) {
3508 arc_hdr_free_pabd(hdr);
3512 ASSERT3P(hdr->b_hash_next, ==, NULL);
3513 if (HDR_HAS_L1HDR(hdr)) {
3514 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3515 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3516 kmem_cache_free(hdr_full_cache, hdr);
3518 kmem_cache_free(hdr_l2only_cache, hdr);
3523 arc_buf_destroy(arc_buf_t *buf, void* tag)
3525 arc_buf_hdr_t *hdr = buf->b_hdr;
3526 kmutex_t *hash_lock = HDR_LOCK(hdr);
3528 if (hdr->b_l1hdr.b_state == arc_anon) {
3529 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3530 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3531 VERIFY0(remove_reference(hdr, NULL, tag));
3532 arc_hdr_destroy(hdr);
3536 mutex_enter(hash_lock);
3537 ASSERT3P(hdr, ==, buf->b_hdr);
3538 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3539 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3540 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3541 ASSERT3P(buf->b_data, !=, NULL);
3543 (void) remove_reference(hdr, hash_lock, tag);
3544 arc_buf_destroy_impl(buf);
3545 mutex_exit(hash_lock);
3549 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3550 * state of the header is dependent on its state prior to entering this
3551 * function. The following transitions are possible:
3553 * - arc_mru -> arc_mru_ghost
3554 * - arc_mfu -> arc_mfu_ghost
3555 * - arc_mru_ghost -> arc_l2c_only
3556 * - arc_mru_ghost -> deleted
3557 * - arc_mfu_ghost -> arc_l2c_only
3558 * - arc_mfu_ghost -> deleted
3561 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3563 arc_state_t *evicted_state, *state;
3564 int64_t bytes_evicted = 0;
3565 int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3566 zfs_arc_min_prescient_prefetch_ms : zfs_arc_min_prefetch_ms;
3568 ASSERT(MUTEX_HELD(hash_lock));
3569 ASSERT(HDR_HAS_L1HDR(hdr));
3571 state = hdr->b_l1hdr.b_state;
3572 if (GHOST_STATE(state)) {
3573 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3574 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3577 * l2arc_write_buffers() relies on a header's L1 portion
3578 * (i.e. its b_pabd field) during it's write phase.
3579 * Thus, we cannot push a header onto the arc_l2c_only
3580 * state (removing it's L1 piece) until the header is
3581 * done being written to the l2arc.
3583 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3584 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3585 return (bytes_evicted);
3588 ARCSTAT_BUMP(arcstat_deleted);
3589 bytes_evicted += HDR_GET_LSIZE(hdr);
3591 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3593 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3594 if (HDR_HAS_L2HDR(hdr)) {
3596 * This buffer is cached on the 2nd Level ARC;
3597 * don't destroy the header.
3599 arc_change_state(arc_l2c_only, hdr, hash_lock);
3601 * dropping from L1+L2 cached to L2-only,
3602 * realloc to remove the L1 header.
3604 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3607 arc_change_state(arc_anon, hdr, hash_lock);
3608 arc_hdr_destroy(hdr);
3610 return (bytes_evicted);
3613 ASSERT(state == arc_mru || state == arc_mfu);
3614 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3616 /* prefetch buffers have a minimum lifespan */
3617 if (HDR_IO_IN_PROGRESS(hdr) ||
3618 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3619 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access < min_lifetime * hz)) {
3620 ARCSTAT_BUMP(arcstat_evict_skip);
3621 return (bytes_evicted);
3624 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3625 while (hdr->b_l1hdr.b_buf) {
3626 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3627 if (!mutex_tryenter(&buf->b_evict_lock)) {
3628 ARCSTAT_BUMP(arcstat_mutex_miss);
3631 if (buf->b_data != NULL)
3632 bytes_evicted += HDR_GET_LSIZE(hdr);
3633 mutex_exit(&buf->b_evict_lock);
3634 arc_buf_destroy_impl(buf);
3637 if (HDR_HAS_L2HDR(hdr)) {
3638 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3640 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3641 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3642 HDR_GET_LSIZE(hdr));
3644 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3645 HDR_GET_LSIZE(hdr));
3649 if (hdr->b_l1hdr.b_bufcnt == 0) {
3650 arc_cksum_free(hdr);
3652 bytes_evicted += arc_hdr_size(hdr);
3655 * If this hdr is being evicted and has a compressed
3656 * buffer then we discard it here before we change states.
3657 * This ensures that the accounting is updated correctly
3658 * in arc_free_data_impl().
3660 arc_hdr_free_pabd(hdr);
3662 arc_change_state(evicted_state, hdr, hash_lock);
3663 ASSERT(HDR_IN_HASH_TABLE(hdr));
3664 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3665 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3668 return (bytes_evicted);
3672 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3673 uint64_t spa, int64_t bytes)
3675 multilist_sublist_t *mls;
3676 uint64_t bytes_evicted = 0;
3678 kmutex_t *hash_lock;
3679 int evict_count = 0;
3681 ASSERT3P(marker, !=, NULL);
3682 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3684 mls = multilist_sublist_lock(ml, idx);
3686 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3687 hdr = multilist_sublist_prev(mls, marker)) {
3688 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3689 (evict_count >= zfs_arc_evict_batch_limit))
3693 * To keep our iteration location, move the marker
3694 * forward. Since we're not holding hdr's hash lock, we
3695 * must be very careful and not remove 'hdr' from the
3696 * sublist. Otherwise, other consumers might mistake the
3697 * 'hdr' as not being on a sublist when they call the
3698 * multilist_link_active() function (they all rely on
3699 * the hash lock protecting concurrent insertions and
3700 * removals). multilist_sublist_move_forward() was
3701 * specifically implemented to ensure this is the case
3702 * (only 'marker' will be removed and re-inserted).
3704 multilist_sublist_move_forward(mls, marker);
3707 * The only case where the b_spa field should ever be
3708 * zero, is the marker headers inserted by
3709 * arc_evict_state(). It's possible for multiple threads
3710 * to be calling arc_evict_state() concurrently (e.g.
3711 * dsl_pool_close() and zio_inject_fault()), so we must
3712 * skip any markers we see from these other threads.
3714 if (hdr->b_spa == 0)
3717 /* we're only interested in evicting buffers of a certain spa */
3718 if (spa != 0 && hdr->b_spa != spa) {
3719 ARCSTAT_BUMP(arcstat_evict_skip);
3723 hash_lock = HDR_LOCK(hdr);
3726 * We aren't calling this function from any code path
3727 * that would already be holding a hash lock, so we're
3728 * asserting on this assumption to be defensive in case
3729 * this ever changes. Without this check, it would be
3730 * possible to incorrectly increment arcstat_mutex_miss
3731 * below (e.g. if the code changed such that we called
3732 * this function with a hash lock held).
3734 ASSERT(!MUTEX_HELD(hash_lock));
3736 if (mutex_tryenter(hash_lock)) {
3737 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3738 mutex_exit(hash_lock);
3740 bytes_evicted += evicted;
3743 * If evicted is zero, arc_evict_hdr() must have
3744 * decided to skip this header, don't increment
3745 * evict_count in this case.
3751 * If arc_size isn't overflowing, signal any
3752 * threads that might happen to be waiting.
3754 * For each header evicted, we wake up a single
3755 * thread. If we used cv_broadcast, we could
3756 * wake up "too many" threads causing arc_size
3757 * to significantly overflow arc_c; since
3758 * arc_get_data_impl() doesn't check for overflow
3759 * when it's woken up (it doesn't because it's
3760 * possible for the ARC to be overflowing while
3761 * full of un-evictable buffers, and the
3762 * function should proceed in this case).
3764 * If threads are left sleeping, due to not
3765 * using cv_broadcast, they will be woken up
3766 * just before arc_reclaim_thread() sleeps.
3768 mutex_enter(&arc_reclaim_lock);
3769 if (!arc_is_overflowing())
3770 cv_signal(&arc_reclaim_waiters_cv);
3771 mutex_exit(&arc_reclaim_lock);
3773 ARCSTAT_BUMP(arcstat_mutex_miss);
3777 multilist_sublist_unlock(mls);
3779 return (bytes_evicted);
3783 * Evict buffers from the given arc state, until we've removed the
3784 * specified number of bytes. Move the removed buffers to the
3785 * appropriate evict state.
3787 * This function makes a "best effort". It skips over any buffers
3788 * it can't get a hash_lock on, and so, may not catch all candidates.
3789 * It may also return without evicting as much space as requested.
3791 * If bytes is specified using the special value ARC_EVICT_ALL, this
3792 * will evict all available (i.e. unlocked and evictable) buffers from
3793 * the given arc state; which is used by arc_flush().
3796 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3797 arc_buf_contents_t type)
3799 uint64_t total_evicted = 0;
3800 multilist_t *ml = state->arcs_list[type];
3802 arc_buf_hdr_t **markers;
3804 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3806 num_sublists = multilist_get_num_sublists(ml);
3809 * If we've tried to evict from each sublist, made some
3810 * progress, but still have not hit the target number of bytes
3811 * to evict, we want to keep trying. The markers allow us to
3812 * pick up where we left off for each individual sublist, rather
3813 * than starting from the tail each time.
3815 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3816 for (int i = 0; i < num_sublists; i++) {
3817 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3820 * A b_spa of 0 is used to indicate that this header is
3821 * a marker. This fact is used in arc_adjust_type() and
3822 * arc_evict_state_impl().
3824 markers[i]->b_spa = 0;
3826 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3827 multilist_sublist_insert_tail(mls, markers[i]);
3828 multilist_sublist_unlock(mls);
3832 * While we haven't hit our target number of bytes to evict, or
3833 * we're evicting all available buffers.
3835 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3837 * Start eviction using a randomly selected sublist,
3838 * this is to try and evenly balance eviction across all
3839 * sublists. Always starting at the same sublist
3840 * (e.g. index 0) would cause evictions to favor certain
3841 * sublists over others.
3843 int sublist_idx = multilist_get_random_index(ml);
3844 uint64_t scan_evicted = 0;
3846 for (int i = 0; i < num_sublists; i++) {
3847 uint64_t bytes_remaining;
3848 uint64_t bytes_evicted;
3850 if (bytes == ARC_EVICT_ALL)
3851 bytes_remaining = ARC_EVICT_ALL;
3852 else if (total_evicted < bytes)
3853 bytes_remaining = bytes - total_evicted;
3857 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3858 markers[sublist_idx], spa, bytes_remaining);
3860 scan_evicted += bytes_evicted;
3861 total_evicted += bytes_evicted;
3863 /* we've reached the end, wrap to the beginning */
3864 if (++sublist_idx >= num_sublists)
3869 * If we didn't evict anything during this scan, we have
3870 * no reason to believe we'll evict more during another
3871 * scan, so break the loop.
3873 if (scan_evicted == 0) {
3874 /* This isn't possible, let's make that obvious */
3875 ASSERT3S(bytes, !=, 0);
3878 * When bytes is ARC_EVICT_ALL, the only way to
3879 * break the loop is when scan_evicted is zero.
3880 * In that case, we actually have evicted enough,
3881 * so we don't want to increment the kstat.
3883 if (bytes != ARC_EVICT_ALL) {
3884 ASSERT3S(total_evicted, <, bytes);
3885 ARCSTAT_BUMP(arcstat_evict_not_enough);
3892 for (int i = 0; i < num_sublists; i++) {
3893 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3894 multilist_sublist_remove(mls, markers[i]);
3895 multilist_sublist_unlock(mls);
3897 kmem_cache_free(hdr_full_cache, markers[i]);
3899 kmem_free(markers, sizeof (*markers) * num_sublists);
3901 return (total_evicted);
3905 * Flush all "evictable" data of the given type from the arc state
3906 * specified. This will not evict any "active" buffers (i.e. referenced).
3908 * When 'retry' is set to B_FALSE, the function will make a single pass
3909 * over the state and evict any buffers that it can. Since it doesn't
3910 * continually retry the eviction, it might end up leaving some buffers
3911 * in the ARC due to lock misses.
3913 * When 'retry' is set to B_TRUE, the function will continually retry the
3914 * eviction until *all* evictable buffers have been removed from the
3915 * state. As a result, if concurrent insertions into the state are
3916 * allowed (e.g. if the ARC isn't shutting down), this function might
3917 * wind up in an infinite loop, continually trying to evict buffers.
3920 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3923 uint64_t evicted = 0;
3925 while (refcount_count(&state->arcs_esize[type]) != 0) {
3926 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3936 * Evict the specified number of bytes from the state specified,
3937 * restricting eviction to the spa and type given. This function
3938 * prevents us from trying to evict more from a state's list than
3939 * is "evictable", and to skip evicting altogether when passed a
3940 * negative value for "bytes". In contrast, arc_evict_state() will
3941 * evict everything it can, when passed a negative value for "bytes".
3944 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3945 arc_buf_contents_t type)
3949 if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3950 delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3951 return (arc_evict_state(state, spa, delta, type));
3958 * Evict metadata buffers from the cache, such that arc_meta_used is
3959 * capped by the arc_meta_limit tunable.
3962 arc_adjust_meta(uint64_t meta_used)
3964 uint64_t total_evicted = 0;
3968 * If we're over the meta limit, we want to evict enough
3969 * metadata to get back under the meta limit. We don't want to
3970 * evict so much that we drop the MRU below arc_p, though. If
3971 * we're over the meta limit more than we're over arc_p, we
3972 * evict some from the MRU here, and some from the MFU below.
3974 target = MIN((int64_t)(meta_used - arc_meta_limit),
3975 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3976 refcount_count(&arc_mru->arcs_size) - arc_p));
3978 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3981 * Similar to the above, we want to evict enough bytes to get us
3982 * below the meta limit, but not so much as to drop us below the
3983 * space allotted to the MFU (which is defined as arc_c - arc_p).
3985 target = MIN((int64_t)(meta_used - arc_meta_limit),
3986 (int64_t)(refcount_count(&arc_mfu->arcs_size) -
3989 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3991 return (total_evicted);
3995 * Return the type of the oldest buffer in the given arc state
3997 * This function will select a random sublist of type ARC_BUFC_DATA and
3998 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3999 * is compared, and the type which contains the "older" buffer will be
4002 static arc_buf_contents_t
4003 arc_adjust_type(arc_state_t *state)
4005 multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
4006 multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
4007 int data_idx = multilist_get_random_index(data_ml);
4008 int meta_idx = multilist_get_random_index(meta_ml);
4009 multilist_sublist_t *data_mls;
4010 multilist_sublist_t *meta_mls;
4011 arc_buf_contents_t type;
4012 arc_buf_hdr_t *data_hdr;
4013 arc_buf_hdr_t *meta_hdr;
4016 * We keep the sublist lock until we're finished, to prevent
4017 * the headers from being destroyed via arc_evict_state().
4019 data_mls = multilist_sublist_lock(data_ml, data_idx);
4020 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4023 * These two loops are to ensure we skip any markers that
4024 * might be at the tail of the lists due to arc_evict_state().
4027 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4028 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4029 if (data_hdr->b_spa != 0)
4033 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4034 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4035 if (meta_hdr->b_spa != 0)
4039 if (data_hdr == NULL && meta_hdr == NULL) {
4040 type = ARC_BUFC_DATA;
4041 } else if (data_hdr == NULL) {
4042 ASSERT3P(meta_hdr, !=, NULL);
4043 type = ARC_BUFC_METADATA;
4044 } else if (meta_hdr == NULL) {
4045 ASSERT3P(data_hdr, !=, NULL);
4046 type = ARC_BUFC_DATA;
4048 ASSERT3P(data_hdr, !=, NULL);
4049 ASSERT3P(meta_hdr, !=, NULL);
4051 /* The headers can't be on the sublist without an L1 header */
4052 ASSERT(HDR_HAS_L1HDR(data_hdr));
4053 ASSERT(HDR_HAS_L1HDR(meta_hdr));
4055 if (data_hdr->b_l1hdr.b_arc_access <
4056 meta_hdr->b_l1hdr.b_arc_access) {
4057 type = ARC_BUFC_DATA;
4059 type = ARC_BUFC_METADATA;
4063 multilist_sublist_unlock(meta_mls);
4064 multilist_sublist_unlock(data_mls);
4070 * Evict buffers from the cache, such that arc_size is capped by arc_c.
4075 uint64_t total_evicted = 0;
4078 uint64_t asize = aggsum_value(&arc_size);
4079 uint64_t ameta = aggsum_value(&arc_meta_used);
4082 * If we're over arc_meta_limit, we want to correct that before
4083 * potentially evicting data buffers below.
4085 total_evicted += arc_adjust_meta(ameta);
4090 * If we're over the target cache size, we want to evict enough
4091 * from the list to get back to our target size. We don't want
4092 * to evict too much from the MRU, such that it drops below
4093 * arc_p. So, if we're over our target cache size more than
4094 * the MRU is over arc_p, we'll evict enough to get back to
4095 * arc_p here, and then evict more from the MFU below.
4097 target = MIN((int64_t)(asize - arc_c),
4098 (int64_t)(refcount_count(&arc_anon->arcs_size) +
4099 refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4102 * If we're below arc_meta_min, always prefer to evict data.
4103 * Otherwise, try to satisfy the requested number of bytes to
4104 * evict from the type which contains older buffers; in an
4105 * effort to keep newer buffers in the cache regardless of their
4106 * type. If we cannot satisfy the number of bytes from this
4107 * type, spill over into the next type.
4109 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
4110 ameta > arc_meta_min) {
4111 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4112 total_evicted += bytes;
4115 * If we couldn't evict our target number of bytes from
4116 * metadata, we try to get the rest from data.
4121 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4123 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4124 total_evicted += bytes;
4127 * If we couldn't evict our target number of bytes from
4128 * data, we try to get the rest from metadata.
4133 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4139 * Now that we've tried to evict enough from the MRU to get its
4140 * size back to arc_p, if we're still above the target cache
4141 * size, we evict the rest from the MFU.
4143 target = asize - arc_c;
4145 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4146 ameta > arc_meta_min) {
4147 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4148 total_evicted += bytes;
4151 * If we couldn't evict our target number of bytes from
4152 * metadata, we try to get the rest from data.
4157 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4159 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4160 total_evicted += bytes;
4163 * If we couldn't evict our target number of bytes from
4164 * data, we try to get the rest from data.
4169 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4173 * Adjust ghost lists
4175 * In addition to the above, the ARC also defines target values
4176 * for the ghost lists. The sum of the mru list and mru ghost
4177 * list should never exceed the target size of the cache, and
4178 * the sum of the mru list, mfu list, mru ghost list, and mfu
4179 * ghost list should never exceed twice the target size of the
4180 * cache. The following logic enforces these limits on the ghost
4181 * caches, and evicts from them as needed.
4183 target = refcount_count(&arc_mru->arcs_size) +
4184 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4186 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4187 total_evicted += bytes;
4192 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4195 * We assume the sum of the mru list and mfu list is less than
4196 * or equal to arc_c (we enforced this above), which means we
4197 * can use the simpler of the two equations below:
4199 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4200 * mru ghost + mfu ghost <= arc_c
4202 target = refcount_count(&arc_mru_ghost->arcs_size) +
4203 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4205 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4206 total_evicted += bytes;
4211 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4213 return (total_evicted);
4217 arc_flush(spa_t *spa, boolean_t retry)
4222 * If retry is B_TRUE, a spa must not be specified since we have
4223 * no good way to determine if all of a spa's buffers have been
4224 * evicted from an arc state.
4226 ASSERT(!retry || spa == 0);
4229 guid = spa_load_guid(spa);
4231 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4232 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4234 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4235 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4237 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4238 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4240 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4241 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4245 arc_shrink(int64_t to_free)
4247 uint64_t asize = aggsum_value(&arc_size);
4248 if (arc_c > arc_c_min) {
4249 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4250 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4251 if (arc_c > arc_c_min + to_free)
4252 atomic_add_64(&arc_c, -to_free);
4256 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4258 arc_c = MAX(asize, arc_c_min);
4260 arc_p = (arc_c >> 1);
4262 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4265 ASSERT(arc_c >= arc_c_min);
4266 ASSERT((int64_t)arc_p >= 0);
4269 if (asize > arc_c) {
4270 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, asize,
4272 (void) arc_adjust();
4276 typedef enum free_memory_reason_t {
4281 FMR_PAGES_PP_MAXIMUM,
4284 } free_memory_reason_t;
4286 int64_t last_free_memory;
4287 free_memory_reason_t last_free_reason;
4290 * Additional reserve of pages for pp_reserve.
4292 int64_t arc_pages_pp_reserve = 64;
4295 * Additional reserve of pages for swapfs.
4297 int64_t arc_swapfs_reserve = 64;
4300 * Return the amount of memory that can be consumed before reclaim will be
4301 * needed. Positive if there is sufficient free memory, negative indicates
4302 * the amount of memory that needs to be freed up.
4305 arc_available_memory(void)
4307 int64_t lowest = INT64_MAX;
4309 free_memory_reason_t r = FMR_UNKNOWN;
4314 * Cooperate with pagedaemon when it's time for it to scan
4315 * and reclaim some pages.
4317 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4325 n = PAGESIZE * (-needfree);
4333 * check that we're out of range of the pageout scanner. It starts to
4334 * schedule paging if freemem is less than lotsfree and needfree.
4335 * lotsfree is the high-water mark for pageout, and needfree is the
4336 * number of needed free pages. We add extra pages here to make sure
4337 * the scanner doesn't start up while we're freeing memory.
4339 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4346 * check to make sure that swapfs has enough space so that anon
4347 * reservations can still succeed. anon_resvmem() checks that the
4348 * availrmem is greater than swapfs_minfree, and the number of reserved
4349 * swap pages. We also add a bit of extra here just to prevent
4350 * circumstances from getting really dire.
4352 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4353 desfree - arc_swapfs_reserve);
4356 r = FMR_SWAPFS_MINFREE;
4361 * Check that we have enough availrmem that memory locking (e.g., via
4362 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
4363 * stores the number of pages that cannot be locked; when availrmem
4364 * drops below pages_pp_maximum, page locking mechanisms such as
4365 * page_pp_lock() will fail.)
4367 n = PAGESIZE * (availrmem - pages_pp_maximum -
4368 arc_pages_pp_reserve);
4371 r = FMR_PAGES_PP_MAXIMUM;
4374 #endif /* __FreeBSD__ */
4375 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4377 * If we're on an i386 platform, it's possible that we'll exhaust the
4378 * kernel heap space before we ever run out of available physical
4379 * memory. Most checks of the size of the heap_area compare against
4380 * tune.t_minarmem, which is the minimum available real memory that we
4381 * can have in the system. However, this is generally fixed at 25 pages
4382 * which is so low that it's useless. In this comparison, we seek to
4383 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4384 * heap is allocated. (Or, in the calculation, if less than 1/4th is
4387 n = uma_avail() - (long)(uma_limit() / 4);
4395 * If zio data pages are being allocated out of a separate heap segment,
4396 * then enforce that the size of available vmem for this arena remains
4397 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4399 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4400 * memory (in the zio_arena) free, which can avoid memory
4401 * fragmentation issues.
4403 if (zio_arena != NULL) {
4404 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4405 (vmem_size(zio_arena, VMEM_ALLOC) >>
4406 arc_zio_arena_free_shift);
4414 /* Every 100 calls, free a small amount */
4415 if (spa_get_random(100) == 0)
4417 #endif /* _KERNEL */
4419 last_free_memory = lowest;
4420 last_free_reason = r;
4421 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4427 * Determine if the system is under memory pressure and is asking
4428 * to reclaim memory. A return value of B_TRUE indicates that the system
4429 * is under memory pressure and that the arc should adjust accordingly.
4432 arc_reclaim_needed(void)
4434 return (arc_available_memory() < 0);
4437 extern kmem_cache_t *zio_buf_cache[];
4438 extern kmem_cache_t *zio_data_buf_cache[];
4439 extern kmem_cache_t *range_seg_cache;
4440 extern kmem_cache_t *abd_chunk_cache;
4442 static __noinline void
4443 arc_kmem_reap_now(void)
4446 kmem_cache_t *prev_cache = NULL;
4447 kmem_cache_t *prev_data_cache = NULL;
4449 DTRACE_PROBE(arc__kmem_reap_start);
4451 if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4453 * We are exceeding our meta-data cache limit.
4454 * Purge some DNLC entries to release holds on meta-data.
4456 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4460 * Reclaim unused memory from all kmem caches.
4467 * If a kmem reap is already active, don't schedule more. We must
4468 * check for this because kmem_cache_reap_soon() won't actually
4469 * block on the cache being reaped (this is to prevent callers from
4470 * becoming implicitly blocked by a system-wide kmem reap -- which,
4471 * on a system with many, many full magazines, can take minutes).
4473 if (kmem_cache_reap_active())
4476 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4477 if (zio_buf_cache[i] != prev_cache) {
4478 prev_cache = zio_buf_cache[i];
4479 kmem_cache_reap_soon(zio_buf_cache[i]);
4481 if (zio_data_buf_cache[i] != prev_data_cache) {
4482 prev_data_cache = zio_data_buf_cache[i];
4483 kmem_cache_reap_soon(zio_data_buf_cache[i]);
4486 kmem_cache_reap_soon(abd_chunk_cache);
4487 kmem_cache_reap_soon(buf_cache);
4488 kmem_cache_reap_soon(hdr_full_cache);
4489 kmem_cache_reap_soon(hdr_l2only_cache);
4490 kmem_cache_reap_soon(range_seg_cache);
4493 if (zio_arena != NULL) {
4495 * Ask the vmem arena to reclaim unused memory from its
4498 vmem_qcache_reap(zio_arena);
4501 DTRACE_PROBE(arc__kmem_reap_end);
4505 * Threads can block in arc_get_data_impl() waiting for this thread to evict
4506 * enough data and signal them to proceed. When this happens, the threads in
4507 * arc_get_data_impl() are sleeping while holding the hash lock for their
4508 * particular arc header. Thus, we must be careful to never sleep on a
4509 * hash lock in this thread. This is to prevent the following deadlock:
4511 * - Thread A sleeps on CV in arc_get_data_impl() holding hash lock "L",
4512 * waiting for the reclaim thread to signal it.
4514 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4515 * fails, and goes to sleep forever.
4517 * This possible deadlock is avoided by always acquiring a hash lock
4518 * using mutex_tryenter() from arc_reclaim_thread().
4522 arc_reclaim_thread(void *unused __unused)
4524 hrtime_t growtime = 0;
4525 hrtime_t kmem_reap_time = 0;
4528 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4530 mutex_enter(&arc_reclaim_lock);
4531 while (!arc_reclaim_thread_exit) {
4532 uint64_t evicted = 0;
4535 * This is necessary in order for the mdb ::arc dcmd to
4536 * show up to date information. Since the ::arc command
4537 * does not call the kstat's update function, without
4538 * this call, the command may show stale stats for the
4539 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4540 * with this change, the data might be up to 1 second
4541 * out of date; but that should suffice. The arc_state_t
4542 * structures can be queried directly if more accurate
4543 * information is needed.
4545 if (arc_ksp != NULL)
4546 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4548 mutex_exit(&arc_reclaim_lock);
4551 * We call arc_adjust() before (possibly) calling
4552 * arc_kmem_reap_now(), so that we can wake up
4553 * arc_get_data_impl() sooner.
4555 evicted = arc_adjust();
4557 int64_t free_memory = arc_available_memory();
4558 if (free_memory < 0) {
4559 hrtime_t curtime = gethrtime();
4560 arc_no_grow = B_TRUE;
4564 * Wait at least zfs_grow_retry (default 60) seconds
4565 * before considering growing.
4567 growtime = curtime + SEC2NSEC(arc_grow_retry);
4570 * Wait at least arc_kmem_cache_reap_retry_ms
4571 * between arc_kmem_reap_now() calls. Without
4572 * this check it is possible to end up in a
4573 * situation where we spend lots of time
4574 * reaping caches, while we're near arc_c_min.
4576 if (curtime >= kmem_reap_time) {
4577 arc_kmem_reap_now();
4578 kmem_reap_time = gethrtime() +
4579 MSEC2NSEC(arc_kmem_cache_reap_retry_ms);
4583 * If we are still low on memory, shrink the ARC
4584 * so that we have arc_shrink_min free space.
4586 free_memory = arc_available_memory();
4589 (arc_c >> arc_shrink_shift) - free_memory;
4593 to_free = MAX(to_free, ptob(needfree));
4596 arc_shrink(to_free);
4598 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4599 arc_no_grow = B_TRUE;
4600 } else if (gethrtime() >= growtime) {
4601 arc_no_grow = B_FALSE;
4604 mutex_enter(&arc_reclaim_lock);
4607 * If evicted is zero, we couldn't evict anything via
4608 * arc_adjust(). This could be due to hash lock
4609 * collisions, but more likely due to the majority of
4610 * arc buffers being unevictable. Therefore, even if
4611 * arc_size is above arc_c, another pass is unlikely to
4612 * be helpful and could potentially cause us to enter an
4615 if (aggsum_compare(&arc_size, arc_c) <= 0|| evicted == 0) {
4617 * We're either no longer overflowing, or we
4618 * can't evict anything more, so we should wake
4619 * up any threads before we go to sleep.
4621 cv_broadcast(&arc_reclaim_waiters_cv);
4624 * Block until signaled, or after one second (we
4625 * might need to perform arc_kmem_reap_now()
4626 * even if we aren't being signalled)
4628 CALLB_CPR_SAFE_BEGIN(&cpr);
4629 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4630 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4631 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4635 arc_reclaim_thread_exit = B_FALSE;
4636 cv_broadcast(&arc_reclaim_thread_cv);
4637 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
4641 static u_int arc_dnlc_evicts_arg;
4642 extern struct vfsops zfs_vfsops;
4645 arc_dnlc_evicts_thread(void *dummy __unused)
4650 CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
4652 mutex_enter(&arc_dnlc_evicts_lock);
4653 while (!arc_dnlc_evicts_thread_exit) {
4654 CALLB_CPR_SAFE_BEGIN(&cpr);
4655 (void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
4656 CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
4657 if (arc_dnlc_evicts_arg != 0) {
4658 percent = arc_dnlc_evicts_arg;
4659 mutex_exit(&arc_dnlc_evicts_lock);
4661 vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
4663 mutex_enter(&arc_dnlc_evicts_lock);
4665 * Clear our token only after vnlru_free()
4666 * pass is done, to avoid false queueing of
4669 arc_dnlc_evicts_arg = 0;
4672 arc_dnlc_evicts_thread_exit = FALSE;
4673 cv_broadcast(&arc_dnlc_evicts_cv);
4674 CALLB_CPR_EXIT(&cpr);
4679 dnlc_reduce_cache(void *arg)
4683 percent = (u_int)(uintptr_t)arg;
4684 mutex_enter(&arc_dnlc_evicts_lock);
4685 if (arc_dnlc_evicts_arg == 0) {
4686 arc_dnlc_evicts_arg = percent;
4687 cv_broadcast(&arc_dnlc_evicts_cv);
4689 mutex_exit(&arc_dnlc_evicts_lock);
4693 * Adapt arc info given the number of bytes we are trying to add and
4694 * the state that we are comming from. This function is only called
4695 * when we are adding new content to the cache.
4698 arc_adapt(int bytes, arc_state_t *state)
4701 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4702 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4703 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4705 if (state == arc_l2c_only)
4710 * Adapt the target size of the MRU list:
4711 * - if we just hit in the MRU ghost list, then increase
4712 * the target size of the MRU list.
4713 * - if we just hit in the MFU ghost list, then increase
4714 * the target size of the MFU list by decreasing the
4715 * target size of the MRU list.
4717 if (state == arc_mru_ghost) {
4718 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4719 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4721 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4722 } else if (state == arc_mfu_ghost) {
4725 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4726 mult = MIN(mult, 10);
4728 delta = MIN(bytes * mult, arc_p);
4729 arc_p = MAX(arc_p_min, arc_p - delta);
4731 ASSERT((int64_t)arc_p >= 0);
4733 if (arc_reclaim_needed()) {
4734 cv_signal(&arc_reclaim_thread_cv);
4741 if (arc_c >= arc_c_max)
4745 * If we're within (2 * maxblocksize) bytes of the target
4746 * cache size, increment the target cache size
4748 if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
4750 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
4751 atomic_add_64(&arc_c, (int64_t)bytes);
4752 if (arc_c > arc_c_max)
4754 else if (state == arc_anon)
4755 atomic_add_64(&arc_p, (int64_t)bytes);
4759 ASSERT((int64_t)arc_p >= 0);
4763 * Check if arc_size has grown past our upper threshold, determined by
4764 * zfs_arc_overflow_shift.
4767 arc_is_overflowing(void)
4769 /* Always allow at least one block of overflow */
4770 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4771 arc_c >> zfs_arc_overflow_shift);
4774 * We just compare the lower bound here for performance reasons. Our
4775 * primary goals are to make sure that the arc never grows without
4776 * bound, and that it can reach its maximum size. This check
4777 * accomplishes both goals. The maximum amount we could run over by is
4778 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4779 * in the ARC. In practice, that's in the tens of MB, which is low
4780 * enough to be safe.
4782 return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4786 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4788 arc_buf_contents_t type = arc_buf_type(hdr);
4790 arc_get_data_impl(hdr, size, tag);
4791 if (type == ARC_BUFC_METADATA) {
4792 return (abd_alloc(size, B_TRUE));
4794 ASSERT(type == ARC_BUFC_DATA);
4795 return (abd_alloc(size, B_FALSE));
4800 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4802 arc_buf_contents_t type = arc_buf_type(hdr);
4804 arc_get_data_impl(hdr, size, tag);
4805 if (type == ARC_BUFC_METADATA) {
4806 return (zio_buf_alloc(size));
4808 ASSERT(type == ARC_BUFC_DATA);
4809 return (zio_data_buf_alloc(size));
4814 * Allocate a block and return it to the caller. If we are hitting the
4815 * hard limit for the cache size, we must sleep, waiting for the eviction
4816 * thread to catch up. If we're past the target size but below the hard
4817 * limit, we'll only signal the reclaim thread and continue on.
4820 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4822 arc_state_t *state = hdr->b_l1hdr.b_state;
4823 arc_buf_contents_t type = arc_buf_type(hdr);
4825 arc_adapt(size, state);
4828 * If arc_size is currently overflowing, and has grown past our
4829 * upper limit, we must be adding data faster than the evict
4830 * thread can evict. Thus, to ensure we don't compound the
4831 * problem by adding more data and forcing arc_size to grow even
4832 * further past it's target size, we halt and wait for the
4833 * eviction thread to catch up.
4835 * It's also possible that the reclaim thread is unable to evict
4836 * enough buffers to get arc_size below the overflow limit (e.g.
4837 * due to buffers being un-evictable, or hash lock collisions).
4838 * In this case, we want to proceed regardless if we're
4839 * overflowing; thus we don't use a while loop here.
4841 if (arc_is_overflowing()) {
4842 mutex_enter(&arc_reclaim_lock);
4845 * Now that we've acquired the lock, we may no longer be
4846 * over the overflow limit, lets check.
4848 * We're ignoring the case of spurious wake ups. If that
4849 * were to happen, it'd let this thread consume an ARC
4850 * buffer before it should have (i.e. before we're under
4851 * the overflow limit and were signalled by the reclaim
4852 * thread). As long as that is a rare occurrence, it
4853 * shouldn't cause any harm.
4855 if (arc_is_overflowing()) {
4856 cv_signal(&arc_reclaim_thread_cv);
4857 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4860 mutex_exit(&arc_reclaim_lock);
4863 VERIFY3U(hdr->b_type, ==, type);
4864 if (type == ARC_BUFC_METADATA) {
4865 arc_space_consume(size, ARC_SPACE_META);
4867 arc_space_consume(size, ARC_SPACE_DATA);
4871 * Update the state size. Note that ghost states have a
4872 * "ghost size" and so don't need to be updated.
4874 if (!GHOST_STATE(state)) {
4876 (void) refcount_add_many(&state->arcs_size, size, tag);
4879 * If this is reached via arc_read, the link is
4880 * protected by the hash lock. If reached via
4881 * arc_buf_alloc, the header should not be accessed by
4882 * any other thread. And, if reached via arc_read_done,
4883 * the hash lock will protect it if it's found in the
4884 * hash table; otherwise no other thread should be
4885 * trying to [add|remove]_reference it.
4887 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4888 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4889 (void) refcount_add_many(&state->arcs_esize[type],
4894 * If we are growing the cache, and we are adding anonymous
4895 * data, and we have outgrown arc_p, update arc_p
4897 if (aggsum_compare(&arc_size, arc_c) < 0 &&
4898 hdr->b_l1hdr.b_state == arc_anon &&
4899 (refcount_count(&arc_anon->arcs_size) +
4900 refcount_count(&arc_mru->arcs_size) > arc_p))
4901 arc_p = MIN(arc_c, arc_p + size);
4903 ARCSTAT_BUMP(arcstat_allocated);
4907 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4909 arc_free_data_impl(hdr, size, tag);
4914 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4916 arc_buf_contents_t type = arc_buf_type(hdr);
4918 arc_free_data_impl(hdr, size, tag);
4919 if (type == ARC_BUFC_METADATA) {
4920 zio_buf_free(buf, size);
4922 ASSERT(type == ARC_BUFC_DATA);
4923 zio_data_buf_free(buf, size);
4928 * Free the arc data buffer.
4931 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4933 arc_state_t *state = hdr->b_l1hdr.b_state;
4934 arc_buf_contents_t type = arc_buf_type(hdr);
4936 /* protected by hash lock, if in the hash table */
4937 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4938 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4939 ASSERT(state != arc_anon && state != arc_l2c_only);
4941 (void) refcount_remove_many(&state->arcs_esize[type],
4944 (void) refcount_remove_many(&state->arcs_size, size, tag);
4946 VERIFY3U(hdr->b_type, ==, type);
4947 if (type == ARC_BUFC_METADATA) {
4948 arc_space_return(size, ARC_SPACE_META);
4950 ASSERT(type == ARC_BUFC_DATA);
4951 arc_space_return(size, ARC_SPACE_DATA);
4956 * This routine is called whenever a buffer is accessed.
4957 * NOTE: the hash lock is dropped in this function.
4960 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4964 ASSERT(MUTEX_HELD(hash_lock));
4965 ASSERT(HDR_HAS_L1HDR(hdr));
4967 if (hdr->b_l1hdr.b_state == arc_anon) {
4969 * This buffer is not in the cache, and does not
4970 * appear in our "ghost" list. Add the new buffer
4974 ASSERT0(hdr->b_l1hdr.b_arc_access);
4975 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4976 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4977 arc_change_state(arc_mru, hdr, hash_lock);
4979 } else if (hdr->b_l1hdr.b_state == arc_mru) {
4980 now = ddi_get_lbolt();
4983 * If this buffer is here because of a prefetch, then either:
4984 * - clear the flag if this is a "referencing" read
4985 * (any subsequent access will bump this into the MFU state).
4987 * - move the buffer to the head of the list if this is
4988 * another prefetch (to make it less likely to be evicted).
4990 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
4991 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4992 /* link protected by hash lock */
4993 ASSERT(multilist_link_active(
4994 &hdr->b_l1hdr.b_arc_node));
4996 arc_hdr_clear_flags(hdr,
4998 ARC_FLAG_PRESCIENT_PREFETCH);
4999 ARCSTAT_BUMP(arcstat_mru_hits);
5001 hdr->b_l1hdr.b_arc_access = now;
5006 * This buffer has been "accessed" only once so far,
5007 * but it is still in the cache. Move it to the MFU
5010 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5012 * More than 125ms have passed since we
5013 * instantiated this buffer. Move it to the
5014 * most frequently used state.
5016 hdr->b_l1hdr.b_arc_access = now;
5017 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5018 arc_change_state(arc_mfu, hdr, hash_lock);
5020 ARCSTAT_BUMP(arcstat_mru_hits);
5021 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5022 arc_state_t *new_state;
5024 * This buffer has been "accessed" recently, but
5025 * was evicted from the cache. Move it to the
5029 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5030 new_state = arc_mru;
5031 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5032 arc_hdr_clear_flags(hdr,
5034 ARC_FLAG_PRESCIENT_PREFETCH);
5036 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5038 new_state = arc_mfu;
5039 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5042 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5043 arc_change_state(new_state, hdr, hash_lock);
5045 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5046 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
5048 * This buffer has been accessed more than once and is
5049 * still in the cache. Keep it in the MFU state.
5051 * NOTE: an add_reference() that occurred when we did
5052 * the arc_read() will have kicked this off the list.
5053 * If it was a prefetch, we will explicitly move it to
5054 * the head of the list now.
5057 ARCSTAT_BUMP(arcstat_mfu_hits);
5058 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5059 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5060 arc_state_t *new_state = arc_mfu;
5062 * This buffer has been accessed more than once but has
5063 * been evicted from the cache. Move it back to the
5067 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5069 * This is a prefetch access...
5070 * move this block back to the MRU state.
5072 new_state = arc_mru;
5075 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5076 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5077 arc_change_state(new_state, hdr, hash_lock);
5079 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5080 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5082 * This buffer is on the 2nd Level ARC.
5085 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5086 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5087 arc_change_state(arc_mfu, hdr, hash_lock);
5089 ASSERT(!"invalid arc state");
5094 * This routine is called by dbuf_hold() to update the arc_access() state
5095 * which otherwise would be skipped for entries in the dbuf cache.
5098 arc_buf_access(arc_buf_t *buf)
5100 mutex_enter(&buf->b_evict_lock);
5101 arc_buf_hdr_t *hdr = buf->b_hdr;
5104 * Avoid taking the hash_lock when possible as an optimization.
5105 * The header must be checked again under the hash_lock in order
5106 * to handle the case where it is concurrently being released.
5108 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5109 mutex_exit(&buf->b_evict_lock);
5110 ARCSTAT_BUMP(arcstat_access_skip);
5114 kmutex_t *hash_lock = HDR_LOCK(hdr);
5115 mutex_enter(hash_lock);
5117 if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5118 mutex_exit(hash_lock);
5119 mutex_exit(&buf->b_evict_lock);
5120 ARCSTAT_BUMP(arcstat_access_skip);
5124 mutex_exit(&buf->b_evict_lock);
5126 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5127 hdr->b_l1hdr.b_state == arc_mfu);
5129 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5130 arc_access(hdr, hash_lock);
5131 mutex_exit(hash_lock);
5133 ARCSTAT_BUMP(arcstat_hits);
5134 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5135 demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5138 /* a generic arc_read_done_func_t which you can use */
5141 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5142 arc_buf_t *buf, void *arg)
5147 bcopy(buf->b_data, arg, arc_buf_size(buf));
5148 arc_buf_destroy(buf, arg);
5151 /* a generic arc_read_done_func_t */
5154 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5155 arc_buf_t *buf, void *arg)
5157 arc_buf_t **bufp = arg;
5159 ASSERT(zio == NULL || zio->io_error != 0);
5162 ASSERT(zio == NULL || zio->io_error == 0);
5164 ASSERT(buf->b_data != NULL);
5169 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5171 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5172 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5173 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
5175 if (HDR_COMPRESSION_ENABLED(hdr)) {
5176 ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
5177 BP_GET_COMPRESS(bp));
5179 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5180 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5185 arc_read_done(zio_t *zio)
5187 arc_buf_hdr_t *hdr = zio->io_private;
5188 kmutex_t *hash_lock = NULL;
5189 arc_callback_t *callback_list;
5190 arc_callback_t *acb;
5191 boolean_t freeable = B_FALSE;
5192 boolean_t no_zio_error = (zio->io_error == 0);
5195 * The hdr was inserted into hash-table and removed from lists
5196 * prior to starting I/O. We should find this header, since
5197 * it's in the hash table, and it should be legit since it's
5198 * not possible to evict it during the I/O. The only possible
5199 * reason for it not to be found is if we were freed during the
5202 if (HDR_IN_HASH_TABLE(hdr)) {
5203 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5204 ASSERT3U(hdr->b_dva.dva_word[0], ==,
5205 BP_IDENTITY(zio->io_bp)->dva_word[0]);
5206 ASSERT3U(hdr->b_dva.dva_word[1], ==,
5207 BP_IDENTITY(zio->io_bp)->dva_word[1]);
5209 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
5212 ASSERT((found == hdr &&
5213 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5214 (found == hdr && HDR_L2_READING(hdr)));
5215 ASSERT3P(hash_lock, !=, NULL);
5219 /* byteswap if necessary */
5220 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5221 if (BP_GET_LEVEL(zio->io_bp) > 0) {
5222 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5224 hdr->b_l1hdr.b_byteswap =
5225 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5228 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5232 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5233 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5234 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5236 callback_list = hdr->b_l1hdr.b_acb;
5237 ASSERT3P(callback_list, !=, NULL);
5239 if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5241 * Only call arc_access on anonymous buffers. This is because
5242 * if we've issued an I/O for an evicted buffer, we've already
5243 * called arc_access (to prevent any simultaneous readers from
5244 * getting confused).
5246 arc_access(hdr, hash_lock);
5250 * If a read request has a callback (i.e. acb_done is not NULL), then we
5251 * make a buf containing the data according to the parameters which were
5252 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5253 * aren't needlessly decompressing the data multiple times.
5255 int callback_cnt = 0;
5256 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5263 int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5264 acb->acb_compressed, zio->io_error == 0,
5268 * Decompression failed. Set io_error
5269 * so that when we call acb_done (below),
5270 * we will indicate that the read failed.
5271 * Note that in the unusual case where one
5272 * callback is compressed and another
5273 * uncompressed, we will mark all of them
5274 * as failed, even though the uncompressed
5275 * one can't actually fail. In this case,
5276 * the hdr will not be anonymous, because
5277 * if there are multiple callbacks, it's
5278 * because multiple threads found the same
5279 * arc buf in the hash table.
5281 zio->io_error = error;
5286 * If there are multiple callbacks, we must have the hash lock,
5287 * because the only way for multiple threads to find this hdr is
5288 * in the hash table. This ensures that if there are multiple
5289 * callbacks, the hdr is not anonymous. If it were anonymous,
5290 * we couldn't use arc_buf_destroy() in the error case below.
5292 ASSERT(callback_cnt < 2 || hash_lock != NULL);
5294 hdr->b_l1hdr.b_acb = NULL;
5295 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5296 if (callback_cnt == 0) {
5297 ASSERT(HDR_PREFETCH(hdr));
5298 ASSERT0(hdr->b_l1hdr.b_bufcnt);
5299 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5302 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5303 callback_list != NULL);
5306 arc_hdr_verify(hdr, zio->io_bp);
5308 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5309 if (hdr->b_l1hdr.b_state != arc_anon)
5310 arc_change_state(arc_anon, hdr, hash_lock);
5311 if (HDR_IN_HASH_TABLE(hdr))
5312 buf_hash_remove(hdr);
5313 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5317 * Broadcast before we drop the hash_lock to avoid the possibility
5318 * that the hdr (and hence the cv) might be freed before we get to
5319 * the cv_broadcast().
5321 cv_broadcast(&hdr->b_l1hdr.b_cv);
5323 if (hash_lock != NULL) {
5324 mutex_exit(hash_lock);
5327 * This block was freed while we waited for the read to
5328 * complete. It has been removed from the hash table and
5329 * moved to the anonymous state (so that it won't show up
5332 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5333 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5336 /* execute each callback and free its structure */
5337 while ((acb = callback_list) != NULL) {
5338 if (acb->acb_done != NULL) {
5339 if (zio->io_error != 0 && acb->acb_buf != NULL) {
5341 * If arc_buf_alloc_impl() fails during
5342 * decompression, the buf will still be
5343 * allocated, and needs to be freed here.
5345 arc_buf_destroy(acb->acb_buf, acb->acb_private);
5346 acb->acb_buf = NULL;
5348 acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5349 acb->acb_buf, acb->acb_private);
5352 if (acb->acb_zio_dummy != NULL) {
5353 acb->acb_zio_dummy->io_error = zio->io_error;
5354 zio_nowait(acb->acb_zio_dummy);
5357 callback_list = acb->acb_next;
5358 kmem_free(acb, sizeof (arc_callback_t));
5362 arc_hdr_destroy(hdr);
5366 * "Read" the block at the specified DVA (in bp) via the
5367 * cache. If the block is found in the cache, invoke the provided
5368 * callback immediately and return. Note that the `zio' parameter
5369 * in the callback will be NULL in this case, since no IO was
5370 * required. If the block is not in the cache pass the read request
5371 * on to the spa with a substitute callback function, so that the
5372 * requested block will be added to the cache.
5374 * If a read request arrives for a block that has a read in-progress,
5375 * either wait for the in-progress read to complete (and return the
5376 * results); or, if this is a read with a "done" func, add a record
5377 * to the read to invoke the "done" func when the read completes,
5378 * and return; or just return.
5380 * arc_read_done() will invoke all the requested "done" functions
5381 * for readers of this block.
5384 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_read_done_func_t *done,
5385 void *private, zio_priority_t priority, int zio_flags,
5386 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5388 arc_buf_hdr_t *hdr = NULL;
5389 kmutex_t *hash_lock = NULL;
5391 uint64_t guid = spa_load_guid(spa);
5392 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5395 ASSERT(!BP_IS_EMBEDDED(bp) ||
5396 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5399 if (!BP_IS_EMBEDDED(bp)) {
5401 * Embedded BP's have no DVA and require no I/O to "read".
5402 * Create an anonymous arc buf to back it.
5404 hdr = buf_hash_find(guid, bp, &hash_lock);
5407 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
5408 arc_buf_t *buf = NULL;
5409 *arc_flags |= ARC_FLAG_CACHED;
5411 if (HDR_IO_IN_PROGRESS(hdr)) {
5412 zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5414 ASSERT3P(head_zio, !=, NULL);
5415 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5416 priority == ZIO_PRIORITY_SYNC_READ) {
5418 * This is a sync read that needs to wait for
5419 * an in-flight async read. Request that the
5420 * zio have its priority upgraded.
5422 zio_change_priority(head_zio, priority);
5423 DTRACE_PROBE1(arc__async__upgrade__sync,
5424 arc_buf_hdr_t *, hdr);
5425 ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5427 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5428 arc_hdr_clear_flags(hdr,
5429 ARC_FLAG_PREDICTIVE_PREFETCH);
5432 if (*arc_flags & ARC_FLAG_WAIT) {
5433 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5434 mutex_exit(hash_lock);
5437 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5440 arc_callback_t *acb = NULL;
5442 acb = kmem_zalloc(sizeof (arc_callback_t),
5444 acb->acb_done = done;
5445 acb->acb_private = private;
5446 acb->acb_compressed = compressed_read;
5448 acb->acb_zio_dummy = zio_null(pio,
5449 spa, NULL, NULL, NULL, zio_flags);
5451 ASSERT3P(acb->acb_done, !=, NULL);
5452 acb->acb_zio_head = head_zio;
5453 acb->acb_next = hdr->b_l1hdr.b_acb;
5454 hdr->b_l1hdr.b_acb = acb;
5455 mutex_exit(hash_lock);
5458 mutex_exit(hash_lock);
5462 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5463 hdr->b_l1hdr.b_state == arc_mfu);
5466 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5468 * This is a demand read which does not have to
5469 * wait for i/o because we did a predictive
5470 * prefetch i/o for it, which has completed.
5473 arc__demand__hit__predictive__prefetch,
5474 arc_buf_hdr_t *, hdr);
5476 arcstat_demand_hit_predictive_prefetch);
5477 arc_hdr_clear_flags(hdr,
5478 ARC_FLAG_PREDICTIVE_PREFETCH);
5481 if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5483 arcstat_demand_hit_prescient_prefetch);
5484 arc_hdr_clear_flags(hdr,
5485 ARC_FLAG_PRESCIENT_PREFETCH);
5488 ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5489 /* Get a buf with the desired data in it. */
5490 rc = arc_buf_alloc_impl(hdr, private,
5491 compressed_read, B_TRUE, &buf);
5493 arc_buf_destroy(buf, private);
5496 ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
5497 rc == 0 || rc != ENOENT);
5498 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
5499 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5500 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5502 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5503 arc_access(hdr, hash_lock);
5504 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5505 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5506 if (*arc_flags & ARC_FLAG_L2CACHE)
5507 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5508 mutex_exit(hash_lock);
5509 ARCSTAT_BUMP(arcstat_hits);
5510 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5511 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5512 data, metadata, hits);
5515 done(NULL, zb, bp, buf, private);
5517 uint64_t lsize = BP_GET_LSIZE(bp);
5518 uint64_t psize = BP_GET_PSIZE(bp);
5519 arc_callback_t *acb;
5522 boolean_t devw = B_FALSE;
5526 /* this block is not in the cache */
5527 arc_buf_hdr_t *exists = NULL;
5528 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5529 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5530 BP_GET_COMPRESS(bp), type);
5532 if (!BP_IS_EMBEDDED(bp)) {
5533 hdr->b_dva = *BP_IDENTITY(bp);
5534 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5535 exists = buf_hash_insert(hdr, &hash_lock);
5537 if (exists != NULL) {
5538 /* somebody beat us to the hash insert */
5539 mutex_exit(hash_lock);
5540 buf_discard_identity(hdr);
5541 arc_hdr_destroy(hdr);
5542 goto top; /* restart the IO request */
5546 * This block is in the ghost cache. If it was L2-only
5547 * (and thus didn't have an L1 hdr), we realloc the
5548 * header to add an L1 hdr.
5550 if (!HDR_HAS_L1HDR(hdr)) {
5551 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5554 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5555 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5556 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5557 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5558 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5559 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5562 * This is a delicate dance that we play here.
5563 * This hdr is in the ghost list so we access it
5564 * to move it out of the ghost list before we
5565 * initiate the read. If it's a prefetch then
5566 * it won't have a callback so we'll remove the
5567 * reference that arc_buf_alloc_impl() created. We
5568 * do this after we've called arc_access() to
5569 * avoid hitting an assert in remove_reference().
5571 arc_access(hdr, hash_lock);
5572 arc_hdr_alloc_pabd(hdr);
5574 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5575 size = arc_hdr_size(hdr);
5578 * If compression is enabled on the hdr, then will do
5579 * RAW I/O and will store the compressed data in the hdr's
5580 * data block. Otherwise, the hdr's data block will contain
5581 * the uncompressed data.
5583 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5584 zio_flags |= ZIO_FLAG_RAW;
5587 if (*arc_flags & ARC_FLAG_PREFETCH)
5588 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5589 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5590 arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5592 if (*arc_flags & ARC_FLAG_L2CACHE)
5593 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5594 if (BP_GET_LEVEL(bp) > 0)
5595 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5596 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5597 arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5598 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5600 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5601 acb->acb_done = done;
5602 acb->acb_private = private;
5603 acb->acb_compressed = compressed_read;
5605 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5606 hdr->b_l1hdr.b_acb = acb;
5607 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5609 if (HDR_HAS_L2HDR(hdr) &&
5610 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5611 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5612 addr = hdr->b_l2hdr.b_daddr;
5614 * Lock out L2ARC device removal.
5616 if (vdev_is_dead(vd) ||
5617 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5622 * We count both async reads and scrub IOs as asynchronous so
5623 * that both can be upgraded in the event of a cache hit while
5624 * the read IO is still in-flight.
5626 if (priority == ZIO_PRIORITY_ASYNC_READ ||
5627 priority == ZIO_PRIORITY_SCRUB)
5628 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5630 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5633 * At this point, we have a level 1 cache miss. Try again in
5634 * L2ARC if possible.
5636 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5638 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5639 uint64_t, lsize, zbookmark_phys_t *, zb);
5640 ARCSTAT_BUMP(arcstat_misses);
5641 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5642 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5643 data, metadata, misses);
5648 racct_add_force(curproc, RACCT_READBPS, size);
5649 racct_add_force(curproc, RACCT_READIOPS, 1);
5650 PROC_UNLOCK(curproc);
5653 curthread->td_ru.ru_inblock++;
5656 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5658 * Read from the L2ARC if the following are true:
5659 * 1. The L2ARC vdev was previously cached.
5660 * 2. This buffer still has L2ARC metadata.
5661 * 3. This buffer isn't currently writing to the L2ARC.
5662 * 4. The L2ARC entry wasn't evicted, which may
5663 * also have invalidated the vdev.
5664 * 5. This isn't prefetch and l2arc_noprefetch is set.
5666 if (HDR_HAS_L2HDR(hdr) &&
5667 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5668 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5669 l2arc_read_callback_t *cb;
5673 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5674 ARCSTAT_BUMP(arcstat_l2_hits);
5676 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5678 cb->l2rcb_hdr = hdr;
5681 cb->l2rcb_flags = zio_flags;
5683 asize = vdev_psize_to_asize(vd, size);
5684 if (asize != size) {
5685 abd = abd_alloc_for_io(asize,
5686 HDR_ISTYPE_METADATA(hdr));
5687 cb->l2rcb_abd = abd;
5689 abd = hdr->b_l1hdr.b_pabd;
5692 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5693 addr + asize <= vd->vdev_psize -
5694 VDEV_LABEL_END_SIZE);
5697 * l2arc read. The SCL_L2ARC lock will be
5698 * released by l2arc_read_done().
5699 * Issue a null zio if the underlying buffer
5700 * was squashed to zero size by compression.
5702 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5703 ZIO_COMPRESS_EMPTY);
5704 rzio = zio_read_phys(pio, vd, addr,
5707 l2arc_read_done, cb, priority,
5708 zio_flags | ZIO_FLAG_DONT_CACHE |
5710 ZIO_FLAG_DONT_PROPAGATE |
5711 ZIO_FLAG_DONT_RETRY, B_FALSE);
5712 acb->acb_zio_head = rzio;
5714 if (hash_lock != NULL)
5715 mutex_exit(hash_lock);
5717 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5719 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5721 if (*arc_flags & ARC_FLAG_NOWAIT) {
5726 ASSERT(*arc_flags & ARC_FLAG_WAIT);
5727 if (zio_wait(rzio) == 0)
5730 /* l2arc read error; goto zio_read() */
5731 if (hash_lock != NULL)
5732 mutex_enter(hash_lock);
5734 DTRACE_PROBE1(l2arc__miss,
5735 arc_buf_hdr_t *, hdr);
5736 ARCSTAT_BUMP(arcstat_l2_misses);
5737 if (HDR_L2_WRITING(hdr))
5738 ARCSTAT_BUMP(arcstat_l2_rw_clash);
5739 spa_config_exit(spa, SCL_L2ARC, vd);
5743 spa_config_exit(spa, SCL_L2ARC, vd);
5744 if (l2arc_ndev != 0) {
5745 DTRACE_PROBE1(l2arc__miss,
5746 arc_buf_hdr_t *, hdr);
5747 ARCSTAT_BUMP(arcstat_l2_misses);
5751 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5752 arc_read_done, hdr, priority, zio_flags, zb);
5753 acb->acb_zio_head = rzio;
5755 if (hash_lock != NULL)
5756 mutex_exit(hash_lock);
5758 if (*arc_flags & ARC_FLAG_WAIT)
5759 return (zio_wait(rzio));
5761 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5768 * Notify the arc that a block was freed, and thus will never be used again.
5771 arc_freed(spa_t *spa, const blkptr_t *bp)
5774 kmutex_t *hash_lock;
5775 uint64_t guid = spa_load_guid(spa);
5777 ASSERT(!BP_IS_EMBEDDED(bp));
5779 hdr = buf_hash_find(guid, bp, &hash_lock);
5784 * We might be trying to free a block that is still doing I/O
5785 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5786 * dmu_sync-ed block). If this block is being prefetched, then it
5787 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5788 * until the I/O completes. A block may also have a reference if it is
5789 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5790 * have written the new block to its final resting place on disk but
5791 * without the dedup flag set. This would have left the hdr in the MRU
5792 * state and discoverable. When the txg finally syncs it detects that
5793 * the block was overridden in open context and issues an override I/O.
5794 * Since this is a dedup block, the override I/O will determine if the
5795 * block is already in the DDT. If so, then it will replace the io_bp
5796 * with the bp from the DDT and allow the I/O to finish. When the I/O
5797 * reaches the done callback, dbuf_write_override_done, it will
5798 * check to see if the io_bp and io_bp_override are identical.
5799 * If they are not, then it indicates that the bp was replaced with
5800 * the bp in the DDT and the override bp is freed. This allows
5801 * us to arrive here with a reference on a block that is being
5802 * freed. So if we have an I/O in progress, or a reference to
5803 * this hdr, then we don't destroy the hdr.
5805 if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5806 refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5807 arc_change_state(arc_anon, hdr, hash_lock);
5808 arc_hdr_destroy(hdr);
5809 mutex_exit(hash_lock);
5811 mutex_exit(hash_lock);
5817 * Release this buffer from the cache, making it an anonymous buffer. This
5818 * must be done after a read and prior to modifying the buffer contents.
5819 * If the buffer has more than one reference, we must make
5820 * a new hdr for the buffer.
5823 arc_release(arc_buf_t *buf, void *tag)
5825 arc_buf_hdr_t *hdr = buf->b_hdr;
5828 * It would be nice to assert that if it's DMU metadata (level >
5829 * 0 || it's the dnode file), then it must be syncing context.
5830 * But we don't know that information at this level.
5833 mutex_enter(&buf->b_evict_lock);
5835 ASSERT(HDR_HAS_L1HDR(hdr));
5838 * We don't grab the hash lock prior to this check, because if
5839 * the buffer's header is in the arc_anon state, it won't be
5840 * linked into the hash table.
5842 if (hdr->b_l1hdr.b_state == arc_anon) {
5843 mutex_exit(&buf->b_evict_lock);
5844 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5845 ASSERT(!HDR_IN_HASH_TABLE(hdr));
5846 ASSERT(!HDR_HAS_L2HDR(hdr));
5847 ASSERT(HDR_EMPTY(hdr));
5848 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5849 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5850 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5852 hdr->b_l1hdr.b_arc_access = 0;
5855 * If the buf is being overridden then it may already
5856 * have a hdr that is not empty.
5858 buf_discard_identity(hdr);
5864 kmutex_t *hash_lock = HDR_LOCK(hdr);
5865 mutex_enter(hash_lock);
5868 * This assignment is only valid as long as the hash_lock is
5869 * held, we must be careful not to reference state or the
5870 * b_state field after dropping the lock.
5872 arc_state_t *state = hdr->b_l1hdr.b_state;
5873 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5874 ASSERT3P(state, !=, arc_anon);
5876 /* this buffer is not on any list */
5877 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
5879 if (HDR_HAS_L2HDR(hdr)) {
5880 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5883 * We have to recheck this conditional again now that
5884 * we're holding the l2ad_mtx to prevent a race with
5885 * another thread which might be concurrently calling
5886 * l2arc_evict(). In that case, l2arc_evict() might have
5887 * destroyed the header's L2 portion as we were waiting
5888 * to acquire the l2ad_mtx.
5890 if (HDR_HAS_L2HDR(hdr)) {
5892 arc_hdr_l2hdr_destroy(hdr);
5895 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5899 * Do we have more than one buf?
5901 if (hdr->b_l1hdr.b_bufcnt > 1) {
5902 arc_buf_hdr_t *nhdr;
5903 uint64_t spa = hdr->b_spa;
5904 uint64_t psize = HDR_GET_PSIZE(hdr);
5905 uint64_t lsize = HDR_GET_LSIZE(hdr);
5906 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5907 arc_buf_contents_t type = arc_buf_type(hdr);
5908 VERIFY3U(hdr->b_type, ==, type);
5910 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5911 (void) remove_reference(hdr, hash_lock, tag);
5913 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5914 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5915 ASSERT(ARC_BUF_LAST(buf));
5919 * Pull the data off of this hdr and attach it to
5920 * a new anonymous hdr. Also find the last buffer
5921 * in the hdr's buffer list.
5923 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5924 ASSERT3P(lastbuf, !=, NULL);
5927 * If the current arc_buf_t and the hdr are sharing their data
5928 * buffer, then we must stop sharing that block.
5930 if (arc_buf_is_shared(buf)) {
5931 VERIFY(!arc_buf_is_shared(lastbuf));
5934 * First, sever the block sharing relationship between
5935 * buf and the arc_buf_hdr_t.
5937 arc_unshare_buf(hdr, buf);
5940 * Now we need to recreate the hdr's b_pabd. Since we
5941 * have lastbuf handy, we try to share with it, but if
5942 * we can't then we allocate a new b_pabd and copy the
5943 * data from buf into it.
5945 if (arc_can_share(hdr, lastbuf)) {
5946 arc_share_buf(hdr, lastbuf);
5948 arc_hdr_alloc_pabd(hdr);
5949 abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5950 buf->b_data, psize);
5952 VERIFY3P(lastbuf->b_data, !=, NULL);
5953 } else if (HDR_SHARED_DATA(hdr)) {
5955 * Uncompressed shared buffers are always at the end
5956 * of the list. Compressed buffers don't have the
5957 * same requirements. This makes it hard to
5958 * simply assert that the lastbuf is shared so
5959 * we rely on the hdr's compression flags to determine
5960 * if we have a compressed, shared buffer.
5962 ASSERT(arc_buf_is_shared(lastbuf) ||
5963 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
5964 ASSERT(!ARC_BUF_SHARED(buf));
5966 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5967 ASSERT3P(state, !=, arc_l2c_only);
5969 (void) refcount_remove_many(&state->arcs_size,
5970 arc_buf_size(buf), buf);
5972 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5973 ASSERT3P(state, !=, arc_l2c_only);
5974 (void) refcount_remove_many(&state->arcs_esize[type],
5975 arc_buf_size(buf), buf);
5978 hdr->b_l1hdr.b_bufcnt -= 1;
5979 arc_cksum_verify(buf);
5981 arc_buf_unwatch(buf);
5984 mutex_exit(hash_lock);
5987 * Allocate a new hdr. The new hdr will contain a b_pabd
5988 * buffer which will be freed in arc_write().
5990 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5991 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5992 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5993 ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5994 VERIFY3U(nhdr->b_type, ==, type);
5995 ASSERT(!HDR_SHARED_DATA(nhdr));
5997 nhdr->b_l1hdr.b_buf = buf;
5998 nhdr->b_l1hdr.b_bufcnt = 1;
5999 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6002 mutex_exit(&buf->b_evict_lock);
6003 (void) refcount_add_many(&arc_anon->arcs_size,
6004 arc_buf_size(buf), buf);
6006 mutex_exit(&buf->b_evict_lock);
6007 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6008 /* protected by hash lock, or hdr is on arc_anon */
6009 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6010 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6011 arc_change_state(arc_anon, hdr, hash_lock);
6012 hdr->b_l1hdr.b_arc_access = 0;
6013 mutex_exit(hash_lock);
6015 buf_discard_identity(hdr);
6021 arc_released(arc_buf_t *buf)
6025 mutex_enter(&buf->b_evict_lock);
6026 released = (buf->b_data != NULL &&
6027 buf->b_hdr->b_l1hdr.b_state == arc_anon);
6028 mutex_exit(&buf->b_evict_lock);
6034 arc_referenced(arc_buf_t *buf)
6038 mutex_enter(&buf->b_evict_lock);
6039 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6040 mutex_exit(&buf->b_evict_lock);
6041 return (referenced);
6046 arc_write_ready(zio_t *zio)
6048 arc_write_callback_t *callback = zio->io_private;
6049 arc_buf_t *buf = callback->awcb_buf;
6050 arc_buf_hdr_t *hdr = buf->b_hdr;
6051 uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
6053 ASSERT(HDR_HAS_L1HDR(hdr));
6054 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6055 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6058 * If we're reexecuting this zio because the pool suspended, then
6059 * cleanup any state that was previously set the first time the
6060 * callback was invoked.
6062 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6063 arc_cksum_free(hdr);
6065 arc_buf_unwatch(buf);
6067 if (hdr->b_l1hdr.b_pabd != NULL) {
6068 if (arc_buf_is_shared(buf)) {
6069 arc_unshare_buf(hdr, buf);
6071 arc_hdr_free_pabd(hdr);
6075 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6076 ASSERT(!HDR_SHARED_DATA(hdr));
6077 ASSERT(!arc_buf_is_shared(buf));
6079 callback->awcb_ready(zio, buf, callback->awcb_private);
6081 if (HDR_IO_IN_PROGRESS(hdr))
6082 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6084 arc_cksum_compute(buf);
6085 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6087 enum zio_compress compress;
6088 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6089 compress = ZIO_COMPRESS_OFF;
6091 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
6092 compress = BP_GET_COMPRESS(zio->io_bp);
6094 HDR_SET_PSIZE(hdr, psize);
6095 arc_hdr_set_compress(hdr, compress);
6099 * Fill the hdr with data. If the hdr is compressed, the data we want
6100 * is available from the zio, otherwise we can take it from the buf.
6102 * We might be able to share the buf's data with the hdr here. However,
6103 * doing so would cause the ARC to be full of linear ABDs if we write a
6104 * lot of shareable data. As a compromise, we check whether scattered
6105 * ABDs are allowed, and assume that if they are then the user wants
6106 * the ARC to be primarily filled with them regardless of the data being
6107 * written. Therefore, if they're allowed then we allocate one and copy
6108 * the data into it; otherwise, we share the data directly if we can.
6110 if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6111 arc_hdr_alloc_pabd(hdr);
6114 * Ideally, we would always copy the io_abd into b_pabd, but the
6115 * user may have disabled compressed ARC, thus we must check the
6116 * hdr's compression setting rather than the io_bp's.
6118 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
6119 ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
6121 ASSERT3U(psize, >, 0);
6123 abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6125 ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6127 abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6131 ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6132 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6133 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6135 arc_share_buf(hdr, buf);
6138 arc_hdr_verify(hdr, zio->io_bp);
6142 arc_write_children_ready(zio_t *zio)
6144 arc_write_callback_t *callback = zio->io_private;
6145 arc_buf_t *buf = callback->awcb_buf;
6147 callback->awcb_children_ready(zio, buf, callback->awcb_private);
6151 * The SPA calls this callback for each physical write that happens on behalf
6152 * of a logical write. See the comment in dbuf_write_physdone() for details.
6155 arc_write_physdone(zio_t *zio)
6157 arc_write_callback_t *cb = zio->io_private;
6158 if (cb->awcb_physdone != NULL)
6159 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6163 arc_write_done(zio_t *zio)
6165 arc_write_callback_t *callback = zio->io_private;
6166 arc_buf_t *buf = callback->awcb_buf;
6167 arc_buf_hdr_t *hdr = buf->b_hdr;
6169 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6171 if (zio->io_error == 0) {
6172 arc_hdr_verify(hdr, zio->io_bp);
6174 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6175 buf_discard_identity(hdr);
6177 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6178 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6181 ASSERT(HDR_EMPTY(hdr));
6185 * If the block to be written was all-zero or compressed enough to be
6186 * embedded in the BP, no write was performed so there will be no
6187 * dva/birth/checksum. The buffer must therefore remain anonymous
6190 if (!HDR_EMPTY(hdr)) {
6191 arc_buf_hdr_t *exists;
6192 kmutex_t *hash_lock;
6194 ASSERT3U(zio->io_error, ==, 0);
6196 arc_cksum_verify(buf);
6198 exists = buf_hash_insert(hdr, &hash_lock);
6199 if (exists != NULL) {
6201 * This can only happen if we overwrite for
6202 * sync-to-convergence, because we remove
6203 * buffers from the hash table when we arc_free().
6205 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6206 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6207 panic("bad overwrite, hdr=%p exists=%p",
6208 (void *)hdr, (void *)exists);
6209 ASSERT(refcount_is_zero(
6210 &exists->b_l1hdr.b_refcnt));
6211 arc_change_state(arc_anon, exists, hash_lock);
6212 mutex_exit(hash_lock);
6213 arc_hdr_destroy(exists);
6214 exists = buf_hash_insert(hdr, &hash_lock);
6215 ASSERT3P(exists, ==, NULL);
6216 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6218 ASSERT(zio->io_prop.zp_nopwrite);
6219 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6220 panic("bad nopwrite, hdr=%p exists=%p",
6221 (void *)hdr, (void *)exists);
6224 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6225 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6226 ASSERT(BP_GET_DEDUP(zio->io_bp));
6227 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6230 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6231 /* if it's not anon, we are doing a scrub */
6232 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6233 arc_access(hdr, hash_lock);
6234 mutex_exit(hash_lock);
6236 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6239 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6240 callback->awcb_done(zio, buf, callback->awcb_private);
6242 abd_put(zio->io_abd);
6243 kmem_free(callback, sizeof (arc_write_callback_t));
6247 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6248 boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6249 arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6250 arc_write_done_func_t *done, void *private, zio_priority_t priority,
6251 int zio_flags, const zbookmark_phys_t *zb)
6253 arc_buf_hdr_t *hdr = buf->b_hdr;
6254 arc_write_callback_t *callback;
6256 zio_prop_t localprop = *zp;
6258 ASSERT3P(ready, !=, NULL);
6259 ASSERT3P(done, !=, NULL);
6260 ASSERT(!HDR_IO_ERROR(hdr));
6261 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6262 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6263 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6265 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6266 if (ARC_BUF_COMPRESSED(buf)) {
6268 * We're writing a pre-compressed buffer. Make the
6269 * compression algorithm requested by the zio_prop_t match
6270 * the pre-compressed buffer's compression algorithm.
6272 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6274 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6275 zio_flags |= ZIO_FLAG_RAW;
6277 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6278 callback->awcb_ready = ready;
6279 callback->awcb_children_ready = children_ready;
6280 callback->awcb_physdone = physdone;
6281 callback->awcb_done = done;
6282 callback->awcb_private = private;
6283 callback->awcb_buf = buf;
6286 * The hdr's b_pabd is now stale, free it now. A new data block
6287 * will be allocated when the zio pipeline calls arc_write_ready().
6289 if (hdr->b_l1hdr.b_pabd != NULL) {
6291 * If the buf is currently sharing the data block with
6292 * the hdr then we need to break that relationship here.
6293 * The hdr will remain with a NULL data pointer and the
6294 * buf will take sole ownership of the block.
6296 if (arc_buf_is_shared(buf)) {
6297 arc_unshare_buf(hdr, buf);
6299 arc_hdr_free_pabd(hdr);
6301 VERIFY3P(buf->b_data, !=, NULL);
6302 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6304 ASSERT(!arc_buf_is_shared(buf));
6305 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6307 zio = zio_write(pio, spa, txg, bp,
6308 abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6309 HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6310 (children_ready != NULL) ? arc_write_children_ready : NULL,
6311 arc_write_physdone, arc_write_done, callback,
6312 priority, zio_flags, zb);
6318 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
6321 uint64_t available_memory = ptob(freemem);
6323 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
6324 available_memory = MIN(available_memory, uma_avail());
6327 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
6330 if (txg > spa->spa_lowmem_last_txg) {
6331 spa->spa_lowmem_last_txg = txg;
6332 spa->spa_lowmem_page_load = 0;
6335 * If we are in pageout, we know that memory is already tight,
6336 * the arc is already going to be evicting, so we just want to
6337 * continue to let page writes occur as quickly as possible.
6339 if (curproc == pageproc) {
6340 if (spa->spa_lowmem_page_load >
6341 MAX(ptob(minfree), available_memory) / 4)
6342 return (SET_ERROR(ERESTART));
6343 /* Note: reserve is inflated, so we deflate */
6344 atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
6346 } else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
6347 /* memory is low, delay before restarting */
6348 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6349 return (SET_ERROR(EAGAIN));
6351 spa->spa_lowmem_page_load = 0;
6352 #endif /* _KERNEL */
6357 arc_tempreserve_clear(uint64_t reserve)
6359 atomic_add_64(&arc_tempreserve, -reserve);
6360 ASSERT((int64_t)arc_tempreserve >= 0);
6364 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
6369 if (reserve > arc_c/4 && !arc_no_grow) {
6370 arc_c = MIN(arc_c_max, reserve * 4);
6371 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
6373 if (reserve > arc_c)
6374 return (SET_ERROR(ENOMEM));
6377 * Don't count loaned bufs as in flight dirty data to prevent long
6378 * network delays from blocking transactions that are ready to be
6379 * assigned to a txg.
6382 /* assert that it has not wrapped around */
6383 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6385 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
6386 arc_loaned_bytes), 0);
6389 * Writes will, almost always, require additional memory allocations
6390 * in order to compress/encrypt/etc the data. We therefore need to
6391 * make sure that there is sufficient available memory for this.
6393 error = arc_memory_throttle(spa, reserve, txg);
6398 * Throttle writes when the amount of dirty data in the cache
6399 * gets too large. We try to keep the cache less than half full
6400 * of dirty blocks so that our sync times don't grow too large.
6402 * In the case of one pool being built on another pool, we want
6403 * to make sure we don't end up throttling the lower (backing)
6404 * pool when the upper pool is the majority contributor to dirty
6405 * data. To insure we make forward progress during throttling, we
6406 * also check the current pool's net dirty data and only throttle
6407 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6408 * data in the cache.
6410 * Note: if two requests come in concurrently, we might let them
6411 * both succeed, when one of them should fail. Not a huge deal.
6413 uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6414 uint64_t spa_dirty_anon = spa_dirty_data(spa);
6416 if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
6417 anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
6418 spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
6419 uint64_t meta_esize =
6420 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6421 uint64_t data_esize =
6422 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6423 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6424 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6425 arc_tempreserve >> 10, meta_esize >> 10,
6426 data_esize >> 10, reserve >> 10, arc_c >> 10);
6427 return (SET_ERROR(ERESTART));
6429 atomic_add_64(&arc_tempreserve, reserve);
6434 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6435 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6437 size->value.ui64 = refcount_count(&state->arcs_size);
6438 evict_data->value.ui64 =
6439 refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6440 evict_metadata->value.ui64 =
6441 refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6445 arc_kstat_update(kstat_t *ksp, int rw)
6447 arc_stats_t *as = ksp->ks_data;
6449 if (rw == KSTAT_WRITE) {
6452 arc_kstat_update_state(arc_anon,
6453 &as->arcstat_anon_size,
6454 &as->arcstat_anon_evictable_data,
6455 &as->arcstat_anon_evictable_metadata);
6456 arc_kstat_update_state(arc_mru,
6457 &as->arcstat_mru_size,
6458 &as->arcstat_mru_evictable_data,
6459 &as->arcstat_mru_evictable_metadata);
6460 arc_kstat_update_state(arc_mru_ghost,
6461 &as->arcstat_mru_ghost_size,
6462 &as->arcstat_mru_ghost_evictable_data,
6463 &as->arcstat_mru_ghost_evictable_metadata);
6464 arc_kstat_update_state(arc_mfu,
6465 &as->arcstat_mfu_size,
6466 &as->arcstat_mfu_evictable_data,
6467 &as->arcstat_mfu_evictable_metadata);
6468 arc_kstat_update_state(arc_mfu_ghost,
6469 &as->arcstat_mfu_ghost_size,
6470 &as->arcstat_mfu_ghost_evictable_data,
6471 &as->arcstat_mfu_ghost_evictable_metadata);
6473 ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6474 ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6475 ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6476 ARCSTAT(arcstat_metadata_size) =
6477 aggsum_value(&astat_metadata_size);
6478 ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6479 ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
6480 ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6487 * This function *must* return indices evenly distributed between all
6488 * sublists of the multilist. This is needed due to how the ARC eviction
6489 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6490 * distributed between all sublists and uses this assumption when
6491 * deciding which sublist to evict from and how much to evict from it.
6494 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6496 arc_buf_hdr_t *hdr = obj;
6499 * We rely on b_dva to generate evenly distributed index
6500 * numbers using buf_hash below. So, as an added precaution,
6501 * let's make sure we never add empty buffers to the arc lists.
6503 ASSERT(!HDR_EMPTY(hdr));
6506 * The assumption here, is the hash value for a given
6507 * arc_buf_hdr_t will remain constant throughout it's lifetime
6508 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6509 * Thus, we don't need to store the header's sublist index
6510 * on insertion, as this index can be recalculated on removal.
6512 * Also, the low order bits of the hash value are thought to be
6513 * distributed evenly. Otherwise, in the case that the multilist
6514 * has a power of two number of sublists, each sublists' usage
6515 * would not be evenly distributed.
6517 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6518 multilist_get_num_sublists(ml));
6522 static eventhandler_tag arc_event_lowmem = NULL;
6525 arc_lowmem(void *arg __unused, int howto __unused)
6528 mutex_enter(&arc_reclaim_lock);
6529 DTRACE_PROBE1(arc__needfree, int64_t, ((int64_t)freemem - zfs_arc_free_target) * PAGESIZE);
6530 cv_signal(&arc_reclaim_thread_cv);
6533 * It is unsafe to block here in arbitrary threads, because we can come
6534 * here from ARC itself and may hold ARC locks and thus risk a deadlock
6535 * with ARC reclaim thread.
6537 if (curproc == pageproc)
6538 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
6539 mutex_exit(&arc_reclaim_lock);
6544 arc_state_init(void)
6546 arc_anon = &ARC_anon;
6548 arc_mru_ghost = &ARC_mru_ghost;
6550 arc_mfu_ghost = &ARC_mfu_ghost;
6551 arc_l2c_only = &ARC_l2c_only;
6553 arc_mru->arcs_list[ARC_BUFC_METADATA] =
6554 multilist_create(sizeof (arc_buf_hdr_t),
6555 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6556 arc_state_multilist_index_func);
6557 arc_mru->arcs_list[ARC_BUFC_DATA] =
6558 multilist_create(sizeof (arc_buf_hdr_t),
6559 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6560 arc_state_multilist_index_func);
6561 arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6562 multilist_create(sizeof (arc_buf_hdr_t),
6563 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6564 arc_state_multilist_index_func);
6565 arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6566 multilist_create(sizeof (arc_buf_hdr_t),
6567 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6568 arc_state_multilist_index_func);
6569 arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6570 multilist_create(sizeof (arc_buf_hdr_t),
6571 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6572 arc_state_multilist_index_func);
6573 arc_mfu->arcs_list[ARC_BUFC_DATA] =
6574 multilist_create(sizeof (arc_buf_hdr_t),
6575 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6576 arc_state_multilist_index_func);
6577 arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6578 multilist_create(sizeof (arc_buf_hdr_t),
6579 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6580 arc_state_multilist_index_func);
6581 arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6582 multilist_create(sizeof (arc_buf_hdr_t),
6583 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6584 arc_state_multilist_index_func);
6585 arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6586 multilist_create(sizeof (arc_buf_hdr_t),
6587 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6588 arc_state_multilist_index_func);
6589 arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6590 multilist_create(sizeof (arc_buf_hdr_t),
6591 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6592 arc_state_multilist_index_func);
6594 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6595 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6596 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6597 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6598 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6599 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6600 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6601 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6602 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6603 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6604 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6605 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6607 refcount_create(&arc_anon->arcs_size);
6608 refcount_create(&arc_mru->arcs_size);
6609 refcount_create(&arc_mru_ghost->arcs_size);
6610 refcount_create(&arc_mfu->arcs_size);
6611 refcount_create(&arc_mfu_ghost->arcs_size);
6612 refcount_create(&arc_l2c_only->arcs_size);
6614 aggsum_init(&arc_meta_used, 0);
6615 aggsum_init(&arc_size, 0);
6616 aggsum_init(&astat_data_size, 0);
6617 aggsum_init(&astat_metadata_size, 0);
6618 aggsum_init(&astat_hdr_size, 0);
6619 aggsum_init(&astat_other_size, 0);
6620 aggsum_init(&astat_l2_hdr_size, 0);
6624 arc_state_fini(void)
6626 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6627 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6628 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6629 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6630 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6631 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6632 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6633 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6634 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6635 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6636 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6637 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6639 refcount_destroy(&arc_anon->arcs_size);
6640 refcount_destroy(&arc_mru->arcs_size);
6641 refcount_destroy(&arc_mru_ghost->arcs_size);
6642 refcount_destroy(&arc_mfu->arcs_size);
6643 refcount_destroy(&arc_mfu_ghost->arcs_size);
6644 refcount_destroy(&arc_l2c_only->arcs_size);
6646 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6647 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6648 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6649 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
6650 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
6651 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
6652 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
6653 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6665 int i, prefetch_tunable_set = 0;
6668 * allmem is "all memory that we could possibly use".
6672 uint64_t allmem = ptob(physmem - swapfs_minfree);
6674 uint64_t allmem = (physmem * PAGESIZE) / 2;
6677 uint64_t allmem = kmem_size();
6681 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
6682 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
6683 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
6685 mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
6686 cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
6688 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
6689 arc_c_min = MAX(allmem / 32, arc_abs_min);
6690 /* set max to 5/8 of all memory, or all but 1GB, whichever is more */
6691 if (allmem >= 1 << 30)
6692 arc_c_max = allmem - (1 << 30);
6694 arc_c_max = arc_c_min;
6695 arc_c_max = MAX(allmem * 5 / 8, arc_c_max);
6698 * In userland, there's only the memory pressure that we artificially
6699 * create (see arc_available_memory()). Don't let arc_c get too
6700 * small, because it can cause transactions to be larger than
6701 * arc_c, causing arc_tempreserve_space() to fail.
6704 arc_c_min = arc_c_max / 2;
6709 * Allow the tunables to override our calculations if they are
6712 if (zfs_arc_max > arc_abs_min && zfs_arc_max < allmem) {
6713 arc_c_max = zfs_arc_max;
6714 arc_c_min = MIN(arc_c_min, arc_c_max);
6716 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
6717 arc_c_min = zfs_arc_min;
6721 arc_p = (arc_c >> 1);
6723 /* limit meta-data to 1/4 of the arc capacity */
6724 arc_meta_limit = arc_c_max / 4;
6728 * Metadata is stored in the kernel's heap. Don't let us
6729 * use more than half the heap for the ARC.
6732 arc_meta_limit = MIN(arc_meta_limit, uma_limit() / 2);
6734 arc_meta_limit = MIN(arc_meta_limit,
6735 vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6739 /* Allow the tunable to override if it is reasonable */
6740 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6741 arc_meta_limit = zfs_arc_meta_limit;
6743 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6744 arc_c_min = arc_meta_limit / 2;
6746 if (zfs_arc_meta_min > 0) {
6747 arc_meta_min = zfs_arc_meta_min;
6749 arc_meta_min = arc_c_min / 2;
6752 if (zfs_arc_grow_retry > 0)
6753 arc_grow_retry = zfs_arc_grow_retry;
6755 if (zfs_arc_shrink_shift > 0)
6756 arc_shrink_shift = zfs_arc_shrink_shift;
6758 if (zfs_arc_no_grow_shift > 0)
6759 arc_no_grow_shift = zfs_arc_no_grow_shift;
6761 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6763 if (arc_no_grow_shift >= arc_shrink_shift)
6764 arc_no_grow_shift = arc_shrink_shift - 1;
6766 if (zfs_arc_p_min_shift > 0)
6767 arc_p_min_shift = zfs_arc_p_min_shift;
6769 /* if kmem_flags are set, lets try to use less memory */
6770 if (kmem_debugging())
6772 if (arc_c < arc_c_min)
6775 zfs_arc_min = arc_c_min;
6776 zfs_arc_max = arc_c_max;
6781 arc_reclaim_thread_exit = B_FALSE;
6782 arc_dnlc_evicts_thread_exit = FALSE;
6784 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6785 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6787 if (arc_ksp != NULL) {
6788 arc_ksp->ks_data = &arc_stats;
6789 arc_ksp->ks_update = arc_kstat_update;
6790 kstat_install(arc_ksp);
6793 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6794 TS_RUN, minclsyspri);
6797 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
6798 EVENTHANDLER_PRI_FIRST);
6801 (void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
6802 TS_RUN, minclsyspri);
6808 * Calculate maximum amount of dirty data per pool.
6810 * If it has been set by /etc/system, take that.
6811 * Otherwise, use a percentage of physical memory defined by
6812 * zfs_dirty_data_max_percent (default 10%) with a cap at
6813 * zfs_dirty_data_max_max (default 4GB).
6815 if (zfs_dirty_data_max == 0) {
6816 zfs_dirty_data_max = ptob(physmem) *
6817 zfs_dirty_data_max_percent / 100;
6818 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6819 zfs_dirty_data_max_max);
6823 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
6824 prefetch_tunable_set = 1;
6827 if (prefetch_tunable_set == 0) {
6828 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
6830 printf(" add \"vfs.zfs.prefetch_disable=0\" "
6831 "to /boot/loader.conf.\n");
6832 zfs_prefetch_disable = 1;
6835 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
6836 prefetch_tunable_set == 0) {
6837 printf("ZFS NOTICE: Prefetch is disabled by default if less "
6838 "than 4GB of RAM is present;\n"
6839 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
6840 "to /boot/loader.conf.\n");
6841 zfs_prefetch_disable = 1;
6844 /* Warn about ZFS memory and address space requirements. */
6845 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
6846 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
6847 "expect unstable behavior.\n");
6849 if (allmem < 512 * (1 << 20)) {
6850 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
6851 "expect unstable behavior.\n");
6852 printf(" Consider tuning vm.kmem_size and "
6853 "vm.kmem_size_max\n");
6854 printf(" in /boot/loader.conf.\n");
6863 if (arc_event_lowmem != NULL)
6864 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
6867 mutex_enter(&arc_reclaim_lock);
6868 arc_reclaim_thread_exit = B_TRUE;
6870 * The reclaim thread will set arc_reclaim_thread_exit back to
6871 * B_FALSE when it is finished exiting; we're waiting for that.
6873 while (arc_reclaim_thread_exit) {
6874 cv_signal(&arc_reclaim_thread_cv);
6875 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6877 mutex_exit(&arc_reclaim_lock);
6879 /* Use B_TRUE to ensure *all* buffers are evicted */
6880 arc_flush(NULL, B_TRUE);
6882 mutex_enter(&arc_dnlc_evicts_lock);
6883 arc_dnlc_evicts_thread_exit = TRUE;
6885 * The user evicts thread will set arc_user_evicts_thread_exit
6886 * to FALSE when it is finished exiting; we're waiting for that.
6888 while (arc_dnlc_evicts_thread_exit) {
6889 cv_signal(&arc_dnlc_evicts_cv);
6890 cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
6892 mutex_exit(&arc_dnlc_evicts_lock);
6896 if (arc_ksp != NULL) {
6897 kstat_delete(arc_ksp);
6901 mutex_destroy(&arc_reclaim_lock);
6902 cv_destroy(&arc_reclaim_thread_cv);
6903 cv_destroy(&arc_reclaim_waiters_cv);
6905 mutex_destroy(&arc_dnlc_evicts_lock);
6906 cv_destroy(&arc_dnlc_evicts_cv);
6911 ASSERT0(arc_loaned_bytes);
6917 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6918 * It uses dedicated storage devices to hold cached data, which are populated
6919 * using large infrequent writes. The main role of this cache is to boost
6920 * the performance of random read workloads. The intended L2ARC devices
6921 * include short-stroked disks, solid state disks, and other media with
6922 * substantially faster read latency than disk.
6924 * +-----------------------+
6926 * +-----------------------+
6929 * l2arc_feed_thread() arc_read()
6933 * +---------------+ |
6935 * +---------------+ |
6940 * +-------+ +-------+
6942 * | cache | | cache |
6943 * +-------+ +-------+
6944 * +=========+ .-----.
6945 * : L2ARC : |-_____-|
6946 * : devices : | Disks |
6947 * +=========+ `-_____-'
6949 * Read requests are satisfied from the following sources, in order:
6952 * 2) vdev cache of L2ARC devices
6954 * 4) vdev cache of disks
6957 * Some L2ARC device types exhibit extremely slow write performance.
6958 * To accommodate for this there are some significant differences between
6959 * the L2ARC and traditional cache design:
6961 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
6962 * the ARC behave as usual, freeing buffers and placing headers on ghost
6963 * lists. The ARC does not send buffers to the L2ARC during eviction as
6964 * this would add inflated write latencies for all ARC memory pressure.
6966 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6967 * It does this by periodically scanning buffers from the eviction-end of
6968 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6969 * not already there. It scans until a headroom of buffers is satisfied,
6970 * which itself is a buffer for ARC eviction. If a compressible buffer is
6971 * found during scanning and selected for writing to an L2ARC device, we
6972 * temporarily boost scanning headroom during the next scan cycle to make
6973 * sure we adapt to compression effects (which might significantly reduce
6974 * the data volume we write to L2ARC). The thread that does this is
6975 * l2arc_feed_thread(), illustrated below; example sizes are included to
6976 * provide a better sense of ratio than this diagram:
6979 * +---------------------+----------+
6980 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
6981 * +---------------------+----------+ | o L2ARC eligible
6982 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
6983 * +---------------------+----------+ |
6984 * 15.9 Gbytes ^ 32 Mbytes |
6986 * l2arc_feed_thread()
6988 * l2arc write hand <--[oooo]--'
6992 * +==============================+
6993 * L2ARC dev |####|#|###|###| |####| ... |
6994 * +==============================+
6997 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6998 * evicted, then the L2ARC has cached a buffer much sooner than it probably
6999 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
7000 * safe to say that this is an uncommon case, since buffers at the end of
7001 * the ARC lists have moved there due to inactivity.
7003 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7004 * then the L2ARC simply misses copying some buffers. This serves as a
7005 * pressure valve to prevent heavy read workloads from both stalling the ARC
7006 * with waits and clogging the L2ARC with writes. This also helps prevent
7007 * the potential for the L2ARC to churn if it attempts to cache content too
7008 * quickly, such as during backups of the entire pool.
7010 * 5. After system boot and before the ARC has filled main memory, there are
7011 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7012 * lists can remain mostly static. Instead of searching from tail of these
7013 * lists as pictured, the l2arc_feed_thread() will search from the list heads
7014 * for eligible buffers, greatly increasing its chance of finding them.
7016 * The L2ARC device write speed is also boosted during this time so that
7017 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
7018 * there are no L2ARC reads, and no fear of degrading read performance
7019 * through increased writes.
7021 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7022 * the vdev queue can aggregate them into larger and fewer writes. Each
7023 * device is written to in a rotor fashion, sweeping writes through
7024 * available space then repeating.
7026 * 7. The L2ARC does not store dirty content. It never needs to flush
7027 * write buffers back to disk based storage.
7029 * 8. If an ARC buffer is written (and dirtied) which also exists in the
7030 * L2ARC, the now stale L2ARC buffer is immediately dropped.
7032 * The performance of the L2ARC can be tweaked by a number of tunables, which
7033 * may be necessary for different workloads:
7035 * l2arc_write_max max write bytes per interval
7036 * l2arc_write_boost extra write bytes during device warmup
7037 * l2arc_noprefetch skip caching prefetched buffers
7038 * l2arc_headroom number of max device writes to precache
7039 * l2arc_headroom_boost when we find compressed buffers during ARC
7040 * scanning, we multiply headroom by this
7041 * percentage factor for the next scan cycle,
7042 * since more compressed buffers are likely to
7044 * l2arc_feed_secs seconds between L2ARC writing
7046 * Tunables may be removed or added as future performance improvements are
7047 * integrated, and also may become zpool properties.
7049 * There are three key functions that control how the L2ARC warms up:
7051 * l2arc_write_eligible() check if a buffer is eligible to cache
7052 * l2arc_write_size() calculate how much to write
7053 * l2arc_write_interval() calculate sleep delay between writes
7055 * These three functions determine what to write, how much, and how quickly
7060 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7063 * A buffer is *not* eligible for the L2ARC if it:
7064 * 1. belongs to a different spa.
7065 * 2. is already cached on the L2ARC.
7066 * 3. has an I/O in progress (it may be an incomplete read).
7067 * 4. is flagged not eligible (zfs property).
7069 if (hdr->b_spa != spa_guid) {
7070 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
7073 if (HDR_HAS_L2HDR(hdr)) {
7074 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
7077 if (HDR_IO_IN_PROGRESS(hdr)) {
7078 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
7081 if (!HDR_L2CACHE(hdr)) {
7082 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
7090 l2arc_write_size(void)
7095 * Make sure our globals have meaningful values in case the user
7098 size = l2arc_write_max;
7100 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7101 "be greater than zero, resetting it to the default (%d)",
7103 size = l2arc_write_max = L2ARC_WRITE_SIZE;
7106 if (arc_warm == B_FALSE)
7107 size += l2arc_write_boost;
7114 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7116 clock_t interval, next, now;
7119 * If the ARC lists are busy, increase our write rate; if the
7120 * lists are stale, idle back. This is achieved by checking
7121 * how much we previously wrote - if it was more than half of
7122 * what we wanted, schedule the next write much sooner.
7124 if (l2arc_feed_again && wrote > (wanted / 2))
7125 interval = (hz * l2arc_feed_min_ms) / 1000;
7127 interval = hz * l2arc_feed_secs;
7129 now = ddi_get_lbolt();
7130 next = MAX(now, MIN(now + interval, began + interval));
7136 * Cycle through L2ARC devices. This is how L2ARC load balances.
7137 * If a device is returned, this also returns holding the spa config lock.
7139 static l2arc_dev_t *
7140 l2arc_dev_get_next(void)
7142 l2arc_dev_t *first, *next = NULL;
7145 * Lock out the removal of spas (spa_namespace_lock), then removal
7146 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
7147 * both locks will be dropped and a spa config lock held instead.
7149 mutex_enter(&spa_namespace_lock);
7150 mutex_enter(&l2arc_dev_mtx);
7152 /* if there are no vdevs, there is nothing to do */
7153 if (l2arc_ndev == 0)
7157 next = l2arc_dev_last;
7159 /* loop around the list looking for a non-faulted vdev */
7161 next = list_head(l2arc_dev_list);
7163 next = list_next(l2arc_dev_list, next);
7165 next = list_head(l2arc_dev_list);
7168 /* if we have come back to the start, bail out */
7171 else if (next == first)
7174 } while (vdev_is_dead(next->l2ad_vdev));
7176 /* if we were unable to find any usable vdevs, return NULL */
7177 if (vdev_is_dead(next->l2ad_vdev))
7180 l2arc_dev_last = next;
7183 mutex_exit(&l2arc_dev_mtx);
7186 * Grab the config lock to prevent the 'next' device from being
7187 * removed while we are writing to it.
7190 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7191 mutex_exit(&spa_namespace_lock);
7197 * Free buffers that were tagged for destruction.
7200 l2arc_do_free_on_write()
7203 l2arc_data_free_t *df, *df_prev;
7205 mutex_enter(&l2arc_free_on_write_mtx);
7206 buflist = l2arc_free_on_write;
7208 for (df = list_tail(buflist); df; df = df_prev) {
7209 df_prev = list_prev(buflist, df);
7210 ASSERT3P(df->l2df_abd, !=, NULL);
7211 abd_free(df->l2df_abd);
7212 list_remove(buflist, df);
7213 kmem_free(df, sizeof (l2arc_data_free_t));
7216 mutex_exit(&l2arc_free_on_write_mtx);
7220 * A write to a cache device has completed. Update all headers to allow
7221 * reads from these buffers to begin.
7224 l2arc_write_done(zio_t *zio)
7226 l2arc_write_callback_t *cb;
7229 arc_buf_hdr_t *head, *hdr, *hdr_prev;
7230 kmutex_t *hash_lock;
7231 int64_t bytes_dropped = 0;
7233 cb = zio->io_private;
7234 ASSERT3P(cb, !=, NULL);
7235 dev = cb->l2wcb_dev;
7236 ASSERT3P(dev, !=, NULL);
7237 head = cb->l2wcb_head;
7238 ASSERT3P(head, !=, NULL);
7239 buflist = &dev->l2ad_buflist;
7240 ASSERT3P(buflist, !=, NULL);
7241 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7242 l2arc_write_callback_t *, cb);
7244 if (zio->io_error != 0)
7245 ARCSTAT_BUMP(arcstat_l2_writes_error);
7248 * All writes completed, or an error was hit.
7251 mutex_enter(&dev->l2ad_mtx);
7252 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7253 hdr_prev = list_prev(buflist, hdr);
7255 hash_lock = HDR_LOCK(hdr);
7258 * We cannot use mutex_enter or else we can deadlock
7259 * with l2arc_write_buffers (due to swapping the order
7260 * the hash lock and l2ad_mtx are taken).
7262 if (!mutex_tryenter(hash_lock)) {
7264 * Missed the hash lock. We must retry so we
7265 * don't leave the ARC_FLAG_L2_WRITING bit set.
7267 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7270 * We don't want to rescan the headers we've
7271 * already marked as having been written out, so
7272 * we reinsert the head node so we can pick up
7273 * where we left off.
7275 list_remove(buflist, head);
7276 list_insert_after(buflist, hdr, head);
7278 mutex_exit(&dev->l2ad_mtx);
7281 * We wait for the hash lock to become available
7282 * to try and prevent busy waiting, and increase
7283 * the chance we'll be able to acquire the lock
7284 * the next time around.
7286 mutex_enter(hash_lock);
7287 mutex_exit(hash_lock);
7292 * We could not have been moved into the arc_l2c_only
7293 * state while in-flight due to our ARC_FLAG_L2_WRITING
7294 * bit being set. Let's just ensure that's being enforced.
7296 ASSERT(HDR_HAS_L1HDR(hdr));
7298 if (zio->io_error != 0) {
7300 * Error - drop L2ARC entry.
7302 list_remove(buflist, hdr);
7304 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7306 ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
7307 ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
7309 bytes_dropped += arc_hdr_size(hdr);
7310 (void) refcount_remove_many(&dev->l2ad_alloc,
7311 arc_hdr_size(hdr), hdr);
7315 * Allow ARC to begin reads and ghost list evictions to
7318 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7320 mutex_exit(hash_lock);
7323 atomic_inc_64(&l2arc_writes_done);
7324 list_remove(buflist, head);
7325 ASSERT(!HDR_HAS_L1HDR(head));
7326 kmem_cache_free(hdr_l2only_cache, head);
7327 mutex_exit(&dev->l2ad_mtx);
7329 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7331 l2arc_do_free_on_write();
7333 kmem_free(cb, sizeof (l2arc_write_callback_t));
7337 * A read to a cache device completed. Validate buffer contents before
7338 * handing over to the regular ARC routines.
7341 l2arc_read_done(zio_t *zio)
7343 l2arc_read_callback_t *cb;
7345 kmutex_t *hash_lock;
7346 boolean_t valid_cksum;
7348 ASSERT3P(zio->io_vd, !=, NULL);
7349 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7351 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7353 cb = zio->io_private;
7354 ASSERT3P(cb, !=, NULL);
7355 hdr = cb->l2rcb_hdr;
7356 ASSERT3P(hdr, !=, NULL);
7358 hash_lock = HDR_LOCK(hdr);
7359 mutex_enter(hash_lock);
7360 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7363 * If the data was read into a temporary buffer,
7364 * move it and free the buffer.
7366 if (cb->l2rcb_abd != NULL) {
7367 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7368 if (zio->io_error == 0) {
7369 abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
7374 * The following must be done regardless of whether
7375 * there was an error:
7376 * - free the temporary buffer
7377 * - point zio to the real ARC buffer
7378 * - set zio size accordingly
7379 * These are required because zio is either re-used for
7380 * an I/O of the block in the case of the error
7381 * or the zio is passed to arc_read_done() and it
7384 abd_free(cb->l2rcb_abd);
7385 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7386 zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
7389 ASSERT3P(zio->io_abd, !=, NULL);
7392 * Check this survived the L2ARC journey.
7394 ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
7395 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
7396 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
7398 valid_cksum = arc_cksum_is_equal(hdr, zio);
7399 if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7400 mutex_exit(hash_lock);
7401 zio->io_private = hdr;
7404 mutex_exit(hash_lock);
7406 * Buffer didn't survive caching. Increment stats and
7407 * reissue to the original storage device.
7409 if (zio->io_error != 0) {
7410 ARCSTAT_BUMP(arcstat_l2_io_error);
7412 zio->io_error = SET_ERROR(EIO);
7415 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7418 * If there's no waiter, issue an async i/o to the primary
7419 * storage now. If there *is* a waiter, the caller must
7420 * issue the i/o in a context where it's OK to block.
7422 if (zio->io_waiter == NULL) {
7423 zio_t *pio = zio_unique_parent(zio);
7425 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7427 zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7428 hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
7429 hdr, zio->io_priority, cb->l2rcb_flags,
7434 kmem_free(cb, sizeof (l2arc_read_callback_t));
7438 * This is the list priority from which the L2ARC will search for pages to
7439 * cache. This is used within loops (0..3) to cycle through lists in the
7440 * desired order. This order can have a significant effect on cache
7443 * Currently the metadata lists are hit first, MFU then MRU, followed by
7444 * the data lists. This function returns a locked list, and also returns
7447 static multilist_sublist_t *
7448 l2arc_sublist_lock(int list_num)
7450 multilist_t *ml = NULL;
7453 ASSERT(list_num >= 0 && list_num <= 3);
7457 ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
7460 ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
7463 ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
7466 ml = arc_mru->arcs_list[ARC_BUFC_DATA];
7471 * Return a randomly-selected sublist. This is acceptable
7472 * because the caller feeds only a little bit of data for each
7473 * call (8MB). Subsequent calls will result in different
7474 * sublists being selected.
7476 idx = multilist_get_random_index(ml);
7477 return (multilist_sublist_lock(ml, idx));
7481 * Evict buffers from the device write hand to the distance specified in
7482 * bytes. This distance may span populated buffers, it may span nothing.
7483 * This is clearing a region on the L2ARC device ready for writing.
7484 * If the 'all' boolean is set, every buffer is evicted.
7487 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7490 arc_buf_hdr_t *hdr, *hdr_prev;
7491 kmutex_t *hash_lock;
7494 buflist = &dev->l2ad_buflist;
7496 if (!all && dev->l2ad_first) {
7498 * This is the first sweep through the device. There is
7504 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7506 * When nearing the end of the device, evict to the end
7507 * before the device write hand jumps to the start.
7509 taddr = dev->l2ad_end;
7511 taddr = dev->l2ad_hand + distance;
7513 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7514 uint64_t, taddr, boolean_t, all);
7517 mutex_enter(&dev->l2ad_mtx);
7518 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
7519 hdr_prev = list_prev(buflist, hdr);
7521 hash_lock = HDR_LOCK(hdr);
7524 * We cannot use mutex_enter or else we can deadlock
7525 * with l2arc_write_buffers (due to swapping the order
7526 * the hash lock and l2ad_mtx are taken).
7528 if (!mutex_tryenter(hash_lock)) {
7530 * Missed the hash lock. Retry.
7532 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
7533 mutex_exit(&dev->l2ad_mtx);
7534 mutex_enter(hash_lock);
7535 mutex_exit(hash_lock);
7540 * A header can't be on this list if it doesn't have L2 header.
7542 ASSERT(HDR_HAS_L2HDR(hdr));
7544 /* Ensure this header has finished being written. */
7545 ASSERT(!HDR_L2_WRITING(hdr));
7546 ASSERT(!HDR_L2_WRITE_HEAD(hdr));
7548 if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
7549 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
7551 * We've evicted to the target address,
7552 * or the end of the device.
7554 mutex_exit(hash_lock);
7558 if (!HDR_HAS_L1HDR(hdr)) {
7559 ASSERT(!HDR_L2_READING(hdr));
7561 * This doesn't exist in the ARC. Destroy.
7562 * arc_hdr_destroy() will call list_remove()
7563 * and decrement arcstat_l2_lsize.
7565 arc_change_state(arc_anon, hdr, hash_lock);
7566 arc_hdr_destroy(hdr);
7568 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
7569 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
7571 * Invalidate issued or about to be issued
7572 * reads, since we may be about to write
7573 * over this location.
7575 if (HDR_L2_READING(hdr)) {
7576 ARCSTAT_BUMP(arcstat_l2_evict_reading);
7577 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7580 arc_hdr_l2hdr_destroy(hdr);
7582 mutex_exit(hash_lock);
7584 mutex_exit(&dev->l2ad_mtx);
7588 * Find and write ARC buffers to the L2ARC device.
7590 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7591 * for reading until they have completed writing.
7592 * The headroom_boost is an in-out parameter used to maintain headroom boost
7593 * state between calls to this function.
7595 * Returns the number of bytes actually written (which may be smaller than
7596 * the delta by which the device hand has changed due to alignment).
7599 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7601 arc_buf_hdr_t *hdr, *hdr_prev, *head;
7602 uint64_t write_asize, write_psize, write_lsize, headroom;
7604 l2arc_write_callback_t *cb;
7606 uint64_t guid = spa_load_guid(spa);
7609 ASSERT3P(dev->l2ad_vdev, !=, NULL);
7612 write_lsize = write_asize = write_psize = 0;
7614 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7615 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7617 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
7619 * Copy buffers for L2ARC writing.
7621 for (try = 0; try <= 3; try++) {
7622 multilist_sublist_t *mls = l2arc_sublist_lock(try);
7623 uint64_t passed_sz = 0;
7625 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
7628 * L2ARC fast warmup.
7630 * Until the ARC is warm and starts to evict, read from the
7631 * head of the ARC lists rather than the tail.
7633 if (arc_warm == B_FALSE)
7634 hdr = multilist_sublist_head(mls);
7636 hdr = multilist_sublist_tail(mls);
7638 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
7640 headroom = target_sz * l2arc_headroom;
7641 if (zfs_compressed_arc_enabled)
7642 headroom = (headroom * l2arc_headroom_boost) / 100;
7644 for (; hdr; hdr = hdr_prev) {
7645 kmutex_t *hash_lock;
7647 if (arc_warm == B_FALSE)
7648 hdr_prev = multilist_sublist_next(mls, hdr);
7650 hdr_prev = multilist_sublist_prev(mls, hdr);
7651 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
7652 HDR_GET_LSIZE(hdr));
7654 hash_lock = HDR_LOCK(hdr);
7655 if (!mutex_tryenter(hash_lock)) {
7656 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
7658 * Skip this buffer rather than waiting.
7663 passed_sz += HDR_GET_LSIZE(hdr);
7664 if (passed_sz > headroom) {
7668 mutex_exit(hash_lock);
7669 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
7673 if (!l2arc_write_eligible(guid, hdr)) {
7674 mutex_exit(hash_lock);
7679 * We rely on the L1 portion of the header below, so
7680 * it's invalid for this header to have been evicted out
7681 * of the ghost cache, prior to being written out. The
7682 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7684 ASSERT(HDR_HAS_L1HDR(hdr));
7686 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7687 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7688 ASSERT3U(arc_hdr_size(hdr), >, 0);
7689 uint64_t psize = arc_hdr_size(hdr);
7690 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7693 if ((write_asize + asize) > target_sz) {
7695 mutex_exit(hash_lock);
7696 ARCSTAT_BUMP(arcstat_l2_write_full);
7702 * Insert a dummy header on the buflist so
7703 * l2arc_write_done() can find where the
7704 * write buffers begin without searching.
7706 mutex_enter(&dev->l2ad_mtx);
7707 list_insert_head(&dev->l2ad_buflist, head);
7708 mutex_exit(&dev->l2ad_mtx);
7711 sizeof (l2arc_write_callback_t), KM_SLEEP);
7712 cb->l2wcb_dev = dev;
7713 cb->l2wcb_head = head;
7714 pio = zio_root(spa, l2arc_write_done, cb,
7716 ARCSTAT_BUMP(arcstat_l2_write_pios);
7719 hdr->b_l2hdr.b_dev = dev;
7720 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7721 arc_hdr_set_flags(hdr,
7722 ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7724 mutex_enter(&dev->l2ad_mtx);
7725 list_insert_head(&dev->l2ad_buflist, hdr);
7726 mutex_exit(&dev->l2ad_mtx);
7728 (void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
7731 * Normally the L2ARC can use the hdr's data, but if
7732 * we're sharing data between the hdr and one of its
7733 * bufs, L2ARC needs its own copy of the data so that
7734 * the ZIO below can't race with the buf consumer.
7735 * Another case where we need to create a copy of the
7736 * data is when the buffer size is not device-aligned
7737 * and we need to pad the block to make it such.
7738 * That also keeps the clock hand suitably aligned.
7740 * To ensure that the copy will be available for the
7741 * lifetime of the ZIO and be cleaned up afterwards, we
7742 * add it to the l2arc_free_on_write queue.
7745 if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7746 to_write = hdr->b_l1hdr.b_pabd;
7748 to_write = abd_alloc_for_io(asize,
7749 HDR_ISTYPE_METADATA(hdr));
7750 abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
7751 if (asize != psize) {
7752 abd_zero_off(to_write, psize,
7755 l2arc_free_abd_on_write(to_write, asize,
7758 wzio = zio_write_phys(pio, dev->l2ad_vdev,
7759 hdr->b_l2hdr.b_daddr, asize, to_write,
7760 ZIO_CHECKSUM_OFF, NULL, hdr,
7761 ZIO_PRIORITY_ASYNC_WRITE,
7762 ZIO_FLAG_CANFAIL, B_FALSE);
7764 write_lsize += HDR_GET_LSIZE(hdr);
7765 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7768 write_psize += psize;
7769 write_asize += asize;
7770 dev->l2ad_hand += asize;
7772 mutex_exit(hash_lock);
7774 (void) zio_nowait(wzio);
7777 multilist_sublist_unlock(mls);
7783 /* No buffers selected for writing? */
7785 ASSERT0(write_lsize);
7786 ASSERT(!HDR_HAS_L1HDR(head));
7787 kmem_cache_free(hdr_l2only_cache, head);
7791 ASSERT3U(write_psize, <=, target_sz);
7792 ARCSTAT_BUMP(arcstat_l2_writes_sent);
7793 ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
7794 ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
7795 ARCSTAT_INCR(arcstat_l2_psize, write_psize);
7796 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7799 * Bump device hand to the device start if it is approaching the end.
7800 * l2arc_evict() will already have evicted ahead for this case.
7802 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7803 dev->l2ad_hand = dev->l2ad_start;
7804 dev->l2ad_first = B_FALSE;
7807 dev->l2ad_writing = B_TRUE;
7808 (void) zio_wait(pio);
7809 dev->l2ad_writing = B_FALSE;
7811 return (write_asize);
7815 * This thread feeds the L2ARC at regular intervals. This is the beating
7816 * heart of the L2ARC.
7820 l2arc_feed_thread(void *unused __unused)
7825 uint64_t size, wrote;
7826 clock_t begin, next = ddi_get_lbolt();
7828 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7830 mutex_enter(&l2arc_feed_thr_lock);
7832 while (l2arc_thread_exit == 0) {
7833 CALLB_CPR_SAFE_BEGIN(&cpr);
7834 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7835 next - ddi_get_lbolt());
7836 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7837 next = ddi_get_lbolt() + hz;
7840 * Quick check for L2ARC devices.
7842 mutex_enter(&l2arc_dev_mtx);
7843 if (l2arc_ndev == 0) {
7844 mutex_exit(&l2arc_dev_mtx);
7847 mutex_exit(&l2arc_dev_mtx);
7848 begin = ddi_get_lbolt();
7851 * This selects the next l2arc device to write to, and in
7852 * doing so the next spa to feed from: dev->l2ad_spa. This
7853 * will return NULL if there are now no l2arc devices or if
7854 * they are all faulted.
7856 * If a device is returned, its spa's config lock is also
7857 * held to prevent device removal. l2arc_dev_get_next()
7858 * will grab and release l2arc_dev_mtx.
7860 if ((dev = l2arc_dev_get_next()) == NULL)
7863 spa = dev->l2ad_spa;
7864 ASSERT3P(spa, !=, NULL);
7867 * If the pool is read-only then force the feed thread to
7868 * sleep a little longer.
7870 if (!spa_writeable(spa)) {
7871 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7872 spa_config_exit(spa, SCL_L2ARC, dev);
7877 * Avoid contributing to memory pressure.
7879 if (arc_reclaim_needed()) {
7880 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7881 spa_config_exit(spa, SCL_L2ARC, dev);
7885 ARCSTAT_BUMP(arcstat_l2_feeds);
7887 size = l2arc_write_size();
7890 * Evict L2ARC buffers that will be overwritten.
7892 l2arc_evict(dev, size, B_FALSE);
7895 * Write ARC buffers.
7897 wrote = l2arc_write_buffers(spa, dev, size);
7900 * Calculate interval between writes.
7902 next = l2arc_write_interval(begin, size, wrote);
7903 spa_config_exit(spa, SCL_L2ARC, dev);
7906 l2arc_thread_exit = 0;
7907 cv_broadcast(&l2arc_feed_thr_cv);
7908 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
7913 l2arc_vdev_present(vdev_t *vd)
7917 mutex_enter(&l2arc_dev_mtx);
7918 for (dev = list_head(l2arc_dev_list); dev != NULL;
7919 dev = list_next(l2arc_dev_list, dev)) {
7920 if (dev->l2ad_vdev == vd)
7923 mutex_exit(&l2arc_dev_mtx);
7925 return (dev != NULL);
7929 * Add a vdev for use by the L2ARC. By this point the spa has already
7930 * validated the vdev and opened it.
7933 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7935 l2arc_dev_t *adddev;
7937 ASSERT(!l2arc_vdev_present(vd));
7939 vdev_ashift_optimize(vd);
7942 * Create a new l2arc device entry.
7944 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7945 adddev->l2ad_spa = spa;
7946 adddev->l2ad_vdev = vd;
7947 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7948 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7949 adddev->l2ad_hand = adddev->l2ad_start;
7950 adddev->l2ad_first = B_TRUE;
7951 adddev->l2ad_writing = B_FALSE;
7953 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7955 * This is a list of all ARC buffers that are still valid on the
7958 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7959 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7961 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7962 refcount_create(&adddev->l2ad_alloc);
7965 * Add device to global list
7967 mutex_enter(&l2arc_dev_mtx);
7968 list_insert_head(l2arc_dev_list, adddev);
7969 atomic_inc_64(&l2arc_ndev);
7970 mutex_exit(&l2arc_dev_mtx);
7974 * Remove a vdev from the L2ARC.
7977 l2arc_remove_vdev(vdev_t *vd)
7979 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7982 * Find the device by vdev
7984 mutex_enter(&l2arc_dev_mtx);
7985 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7986 nextdev = list_next(l2arc_dev_list, dev);
7987 if (vd == dev->l2ad_vdev) {
7992 ASSERT3P(remdev, !=, NULL);
7995 * Remove device from global list
7997 list_remove(l2arc_dev_list, remdev);
7998 l2arc_dev_last = NULL; /* may have been invalidated */
7999 atomic_dec_64(&l2arc_ndev);
8000 mutex_exit(&l2arc_dev_mtx);
8003 * Clear all buflists and ARC references. L2ARC device flush.
8005 l2arc_evict(remdev, 0, B_TRUE);
8006 list_destroy(&remdev->l2ad_buflist);
8007 mutex_destroy(&remdev->l2ad_mtx);
8008 refcount_destroy(&remdev->l2ad_alloc);
8009 kmem_free(remdev, sizeof (l2arc_dev_t));
8015 l2arc_thread_exit = 0;
8017 l2arc_writes_sent = 0;
8018 l2arc_writes_done = 0;
8020 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
8021 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
8022 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
8023 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
8025 l2arc_dev_list = &L2ARC_dev_list;
8026 l2arc_free_on_write = &L2ARC_free_on_write;
8027 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
8028 offsetof(l2arc_dev_t, l2ad_node));
8029 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
8030 offsetof(l2arc_data_free_t, l2df_list_node));
8037 * This is called from dmu_fini(), which is called from spa_fini();
8038 * Because of this, we can assume that all l2arc devices have
8039 * already been removed when the pools themselves were removed.
8042 l2arc_do_free_on_write();
8044 mutex_destroy(&l2arc_feed_thr_lock);
8045 cv_destroy(&l2arc_feed_thr_cv);
8046 mutex_destroy(&l2arc_dev_mtx);
8047 mutex_destroy(&l2arc_free_on_write_mtx);
8049 list_destroy(l2arc_dev_list);
8050 list_destroy(l2arc_free_on_write);
8056 if (!(spa_mode_global & FWRITE))
8059 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
8060 TS_RUN, minclsyspri);
8066 if (!(spa_mode_global & FWRITE))
8069 mutex_enter(&l2arc_feed_thr_lock);
8070 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
8071 l2arc_thread_exit = 1;
8072 while (l2arc_thread_exit != 0)
8073 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
8074 mutex_exit(&l2arc_feed_thr_lock);