4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
24 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
30 * DVA-based Adjustable Replacement Cache
32 * While much of the theory of operation used here is
33 * based on the self-tuning, low overhead replacement cache
34 * presented by Megiddo and Modha at FAST 2003, there are some
35 * significant differences:
37 * 1. The Megiddo and Modha model assumes any page is evictable.
38 * Pages in its cache cannot be "locked" into memory. This makes
39 * the eviction algorithm simple: evict the last page in the list.
40 * This also make the performance characteristics easy to reason
41 * about. Our cache is not so simple. At any given moment, some
42 * subset of the blocks in the cache are un-evictable because we
43 * have handed out a reference to them. Blocks are only evictable
44 * when there are no external references active. This makes
45 * eviction far more problematic: we choose to evict the evictable
46 * blocks that are the "lowest" in the list.
48 * There are times when it is not possible to evict the requested
49 * space. In these circumstances we are unable to adjust the cache
50 * size. To prevent the cache growing unbounded at these times we
51 * implement a "cache throttle" that slows the flow of new data
52 * into the cache until we can make space available.
54 * 2. The Megiddo and Modha model assumes a fixed cache size.
55 * Pages are evicted when the cache is full and there is a cache
56 * miss. Our model has a variable sized cache. It grows with
57 * high use, but also tries to react to memory pressure from the
58 * operating system: decreasing its size when system memory is
61 * 3. The Megiddo and Modha model assumes a fixed page size. All
62 * elements of the cache are therefore exactly the same size. So
63 * when adjusting the cache size following a cache miss, its simply
64 * a matter of choosing a single page to evict. In our model, we
65 * have variable sized cache blocks (rangeing from 512 bytes to
66 * 128K bytes). We therefore choose a set of blocks to evict to make
67 * space for a cache miss that approximates as closely as possible
68 * the space used by the new block.
70 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71 * by N. Megiddo & D. Modha, FAST 2003
77 * A new reference to a cache buffer can be obtained in two
78 * ways: 1) via a hash table lookup using the DVA as a key,
79 * or 2) via one of the ARC lists. The arc_read() interface
80 * uses method 1, while the internal ARC algorithms for
81 * adjusting the cache use method 2. We therefore provide two
82 * types of locks: 1) the hash table lock array, and 2) the
85 * Buffers do not have their own mutexes, rather they rely on the
86 * hash table mutexes for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexes).
89 * buf_hash_find() returns the appropriate mutex (held) when it
90 * locates the requested buffer in the hash table. It returns
91 * NULL for the mutex if the buffer was not in the table.
93 * buf_hash_remove() expects the appropriate hash mutex to be
94 * already held before it is invoked.
96 * Each ARC state also has a mutex which is used to protect the
97 * buffer list associated with the state. When attempting to
98 * obtain a hash table lock while holding an ARC list lock you
99 * must use: mutex_tryenter() to avoid deadlock. Also note that
100 * the active state mutex must be held before the ghost state mutex.
102 * 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_pdata).
133 * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
134 * ability to store the physical data (b_pdata) associated with the DVA of the
135 * arc_buf_hdr_t. Since the b_pdata 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_pdata 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_pdata +-+ |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_pdata buffer into a
195 * new data buffer, or shares the hdr's b_pdata 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_pdata +-+ |---------| |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_pdata
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_pdata. 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_pdata. The
245 * L2ARC will always write the contents of b_pdata 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/multilist.h>
268 #include <sys/dnlc.h>
269 #include <sys/racct.h>
271 #include <sys/callb.h>
272 #include <sys/kstat.h>
273 #include <sys/trim_map.h>
274 #include <zfs_fletcher.h>
277 #include <machine/vmparam.h>
281 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
282 boolean_t arc_watch = B_FALSE;
287 static kmutex_t arc_reclaim_lock;
288 static kcondvar_t arc_reclaim_thread_cv;
289 static boolean_t arc_reclaim_thread_exit;
290 static kcondvar_t arc_reclaim_waiters_cv;
292 static kmutex_t arc_dnlc_evicts_lock;
293 static kcondvar_t arc_dnlc_evicts_cv;
294 static boolean_t arc_dnlc_evicts_thread_exit;
296 uint_t arc_reduce_dnlc_percent = 3;
299 * The number of headers to evict in arc_evict_state_impl() before
300 * dropping the sublist lock and evicting from another sublist. A lower
301 * value means we're more likely to evict the "correct" header (i.e. the
302 * oldest header in the arc state), but comes with higher overhead
303 * (i.e. more invocations of arc_evict_state_impl()).
305 int zfs_arc_evict_batch_limit = 10;
307 /* number of seconds before growing cache again */
308 static int arc_grow_retry = 60;
310 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
311 int zfs_arc_overflow_shift = 8;
313 /* shift of arc_c for calculating both min and max arc_p */
314 static int arc_p_min_shift = 4;
316 /* log2(fraction of arc to reclaim) */
317 static int arc_shrink_shift = 7;
320 * log2(fraction of ARC which must be free to allow growing).
321 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
322 * when reading a new block into the ARC, we will evict an equal-sized block
325 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
326 * we will still not allow it to grow.
328 int arc_no_grow_shift = 5;
332 * minimum lifespan of a prefetch block in clock ticks
333 * (initialized in arc_init())
335 static int arc_min_prefetch_lifespan;
338 * If this percent of memory is free, don't throttle.
340 int arc_lotsfree_percent = 10;
343 extern boolean_t zfs_prefetch_disable;
346 * The arc has filled available memory and has now warmed up.
348 static boolean_t arc_warm;
351 * These tunables are for performance analysis.
353 uint64_t zfs_arc_max;
354 uint64_t zfs_arc_min;
355 uint64_t zfs_arc_meta_limit = 0;
356 uint64_t zfs_arc_meta_min = 0;
357 int zfs_arc_grow_retry = 0;
358 int zfs_arc_shrink_shift = 0;
359 int zfs_arc_p_min_shift = 0;
360 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
361 u_int zfs_arc_free_target = 0;
363 /* Absolute min for arc min / max is 16MB. */
364 static uint64_t arc_abs_min = 16 << 20;
366 boolean_t zfs_compressed_arc_enabled = B_TRUE;
368 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
369 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
370 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
371 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
373 #if defined(__FreeBSD__) && defined(_KERNEL)
375 arc_free_target_init(void *unused __unused)
378 zfs_arc_free_target = vm_pageout_wakeup_thresh;
380 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
381 arc_free_target_init, NULL);
383 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
384 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
385 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
386 SYSCTL_DECL(_vfs_zfs);
387 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
388 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
389 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
390 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
391 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
392 &zfs_arc_average_blocksize, 0,
393 "ARC average blocksize");
394 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
395 &arc_shrink_shift, 0,
396 "log2(fraction of arc to reclaim)");
397 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
398 &zfs_compressed_arc_enabled, 0, "Enable compressed ARC");
401 * We don't have a tunable for arc_free_target due to the dependency on
402 * pagedaemon initialisation.
404 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
405 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
406 sysctl_vfs_zfs_arc_free_target, "IU",
407 "Desired number of free pages below which ARC triggers reclaim");
410 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
415 val = zfs_arc_free_target;
416 err = sysctl_handle_int(oidp, &val, 0, req);
417 if (err != 0 || req->newptr == NULL)
422 if (val > vm_cnt.v_page_count)
425 zfs_arc_free_target = val;
431 * Must be declared here, before the definition of corresponding kstat
432 * macro which uses the same names will confuse the compiler.
434 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
435 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
436 sysctl_vfs_zfs_arc_meta_limit, "QU",
437 "ARC metadata limit");
441 * Note that buffers can be in one of 6 states:
442 * ARC_anon - anonymous (discussed below)
443 * ARC_mru - recently used, currently cached
444 * ARC_mru_ghost - recentely used, no longer in cache
445 * ARC_mfu - frequently used, currently cached
446 * ARC_mfu_ghost - frequently used, no longer in cache
447 * ARC_l2c_only - exists in L2ARC but not other states
448 * When there are no active references to the buffer, they are
449 * are linked onto a list in one of these arc states. These are
450 * the only buffers that can be evicted or deleted. Within each
451 * state there are multiple lists, one for meta-data and one for
452 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
453 * etc.) is tracked separately so that it can be managed more
454 * explicitly: favored over data, limited explicitly.
456 * Anonymous buffers are buffers that are not associated with
457 * a DVA. These are buffers that hold dirty block copies
458 * before they are written to stable storage. By definition,
459 * they are "ref'd" and are considered part of arc_mru
460 * that cannot be freed. Generally, they will aquire a DVA
461 * as they are written and migrate onto the arc_mru list.
463 * The ARC_l2c_only state is for buffers that are in the second
464 * level ARC but no longer in any of the ARC_m* lists. The second
465 * level ARC itself may also contain buffers that are in any of
466 * the ARC_m* states - meaning that a buffer can exist in two
467 * places. The reason for the ARC_l2c_only state is to keep the
468 * buffer header in the hash table, so that reads that hit the
469 * second level ARC benefit from these fast lookups.
472 typedef struct arc_state {
474 * list of evictable buffers
476 multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
478 * total amount of evictable data in this state
480 refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
482 * total amount of data in this state; this includes: evictable,
483 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
485 refcount_t arcs_size;
489 static arc_state_t ARC_anon;
490 static arc_state_t ARC_mru;
491 static arc_state_t ARC_mru_ghost;
492 static arc_state_t ARC_mfu;
493 static arc_state_t ARC_mfu_ghost;
494 static arc_state_t ARC_l2c_only;
496 typedef struct arc_stats {
497 kstat_named_t arcstat_hits;
498 kstat_named_t arcstat_misses;
499 kstat_named_t arcstat_demand_data_hits;
500 kstat_named_t arcstat_demand_data_misses;
501 kstat_named_t arcstat_demand_metadata_hits;
502 kstat_named_t arcstat_demand_metadata_misses;
503 kstat_named_t arcstat_prefetch_data_hits;
504 kstat_named_t arcstat_prefetch_data_misses;
505 kstat_named_t arcstat_prefetch_metadata_hits;
506 kstat_named_t arcstat_prefetch_metadata_misses;
507 kstat_named_t arcstat_mru_hits;
508 kstat_named_t arcstat_mru_ghost_hits;
509 kstat_named_t arcstat_mfu_hits;
510 kstat_named_t arcstat_mfu_ghost_hits;
511 kstat_named_t arcstat_allocated;
512 kstat_named_t arcstat_deleted;
514 * Number of buffers that could not be evicted because the hash lock
515 * was held by another thread. The lock may not necessarily be held
516 * by something using the same buffer, since hash locks are shared
517 * by multiple buffers.
519 kstat_named_t arcstat_mutex_miss;
521 * Number of buffers skipped because they have I/O in progress, are
522 * indrect prefetch buffers that have not lived long enough, or are
523 * not from the spa we're trying to evict from.
525 kstat_named_t arcstat_evict_skip;
527 * Number of times arc_evict_state() was unable to evict enough
528 * buffers to reach it's target amount.
530 kstat_named_t arcstat_evict_not_enough;
531 kstat_named_t arcstat_evict_l2_cached;
532 kstat_named_t arcstat_evict_l2_eligible;
533 kstat_named_t arcstat_evict_l2_ineligible;
534 kstat_named_t arcstat_evict_l2_skip;
535 kstat_named_t arcstat_hash_elements;
536 kstat_named_t arcstat_hash_elements_max;
537 kstat_named_t arcstat_hash_collisions;
538 kstat_named_t arcstat_hash_chains;
539 kstat_named_t arcstat_hash_chain_max;
540 kstat_named_t arcstat_p;
541 kstat_named_t arcstat_c;
542 kstat_named_t arcstat_c_min;
543 kstat_named_t arcstat_c_max;
544 kstat_named_t arcstat_size;
546 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pdata.
547 * Note that the compressed bytes may match the uncompressed bytes
548 * if the block is either not compressed or compressed arc is disabled.
550 kstat_named_t arcstat_compressed_size;
552 * Uncompressed size of the data stored in b_pdata. If compressed
553 * arc is disabled then this value will be identical to the stat
556 kstat_named_t arcstat_uncompressed_size;
558 * Number of bytes stored in all the arc_buf_t's. This is classified
559 * as "overhead" since this data is typically short-lived and will
560 * be evicted from the arc when it becomes unreferenced unless the
561 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
562 * values have been set (see comment in dbuf.c for more information).
564 kstat_named_t arcstat_overhead_size;
566 * Number of bytes consumed by internal ARC structures necessary
567 * for tracking purposes; these structures are not actually
568 * backed by ARC buffers. This includes arc_buf_hdr_t structures
569 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
570 * caches), and arc_buf_t structures (allocated via arc_buf_t
573 kstat_named_t arcstat_hdr_size;
575 * Number of bytes consumed by ARC buffers of type equal to
576 * ARC_BUFC_DATA. This is generally consumed by buffers backing
577 * on disk user data (e.g. plain file contents).
579 kstat_named_t arcstat_data_size;
581 * Number of bytes consumed by ARC buffers of type equal to
582 * ARC_BUFC_METADATA. This is generally consumed by buffers
583 * backing on disk data that is used for internal ZFS
584 * structures (e.g. ZAP, dnode, indirect blocks, etc).
586 kstat_named_t arcstat_metadata_size;
588 * Number of bytes consumed by various buffers and structures
589 * not actually backed with ARC buffers. This includes bonus
590 * buffers (allocated directly via zio_buf_* functions),
591 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
592 * cache), and dnode_t structures (allocated via dnode_t cache).
594 kstat_named_t arcstat_other_size;
596 * Total number of bytes consumed by ARC buffers residing in the
597 * arc_anon state. This includes *all* buffers in the arc_anon
598 * state; e.g. data, metadata, evictable, and unevictable buffers
599 * are all included in this value.
601 kstat_named_t arcstat_anon_size;
603 * Number of bytes consumed by ARC buffers that meet the
604 * following criteria: backing buffers of type ARC_BUFC_DATA,
605 * residing in the arc_anon state, and are eligible for eviction
606 * (e.g. have no outstanding holds on the buffer).
608 kstat_named_t arcstat_anon_evictable_data;
610 * Number of bytes consumed by ARC buffers that meet the
611 * following criteria: backing buffers of type ARC_BUFC_METADATA,
612 * residing in the arc_anon state, and are eligible for eviction
613 * (e.g. have no outstanding holds on the buffer).
615 kstat_named_t arcstat_anon_evictable_metadata;
617 * Total number of bytes consumed by ARC buffers residing in the
618 * arc_mru state. This includes *all* buffers in the arc_mru
619 * state; e.g. data, metadata, evictable, and unevictable buffers
620 * are all included in this value.
622 kstat_named_t arcstat_mru_size;
624 * Number of bytes consumed by ARC buffers that meet the
625 * following criteria: backing buffers of type ARC_BUFC_DATA,
626 * residing in the arc_mru state, and are eligible for eviction
627 * (e.g. have no outstanding holds on the buffer).
629 kstat_named_t arcstat_mru_evictable_data;
631 * Number of bytes consumed by ARC buffers that meet the
632 * following criteria: backing buffers of type ARC_BUFC_METADATA,
633 * residing in the arc_mru state, and are eligible for eviction
634 * (e.g. have no outstanding holds on the buffer).
636 kstat_named_t arcstat_mru_evictable_metadata;
638 * Total number of bytes that *would have been* consumed by ARC
639 * buffers in the arc_mru_ghost state. The key thing to note
640 * here, is the fact that this size doesn't actually indicate
641 * RAM consumption. The ghost lists only consist of headers and
642 * don't actually have ARC buffers linked off of these headers.
643 * Thus, *if* the headers had associated ARC buffers, these
644 * buffers *would have* consumed this number of bytes.
646 kstat_named_t arcstat_mru_ghost_size;
648 * Number of bytes that *would have been* consumed by ARC
649 * buffers that are eligible for eviction, of type
650 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
652 kstat_named_t arcstat_mru_ghost_evictable_data;
654 * Number of bytes that *would have been* consumed by ARC
655 * buffers that are eligible for eviction, of type
656 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
658 kstat_named_t arcstat_mru_ghost_evictable_metadata;
660 * Total number of bytes consumed by ARC buffers residing in the
661 * arc_mfu state. This includes *all* buffers in the arc_mfu
662 * state; e.g. data, metadata, evictable, and unevictable buffers
663 * are all included in this value.
665 kstat_named_t arcstat_mfu_size;
667 * Number of bytes consumed by ARC buffers that are eligible for
668 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
671 kstat_named_t arcstat_mfu_evictable_data;
673 * Number of bytes consumed by ARC buffers that are eligible for
674 * eviction, of type ARC_BUFC_METADATA, and reside in the
677 kstat_named_t arcstat_mfu_evictable_metadata;
679 * Total number of bytes that *would have been* consumed by ARC
680 * buffers in the arc_mfu_ghost state. See the comment above
681 * arcstat_mru_ghost_size for more details.
683 kstat_named_t arcstat_mfu_ghost_size;
685 * Number of bytes that *would have been* consumed by ARC
686 * buffers that are eligible for eviction, of type
687 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
689 kstat_named_t arcstat_mfu_ghost_evictable_data;
691 * Number of bytes that *would have been* consumed by ARC
692 * buffers that are eligible for eviction, of type
693 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
695 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
696 kstat_named_t arcstat_l2_hits;
697 kstat_named_t arcstat_l2_misses;
698 kstat_named_t arcstat_l2_feeds;
699 kstat_named_t arcstat_l2_rw_clash;
700 kstat_named_t arcstat_l2_read_bytes;
701 kstat_named_t arcstat_l2_write_bytes;
702 kstat_named_t arcstat_l2_writes_sent;
703 kstat_named_t arcstat_l2_writes_done;
704 kstat_named_t arcstat_l2_writes_error;
705 kstat_named_t arcstat_l2_writes_lock_retry;
706 kstat_named_t arcstat_l2_evict_lock_retry;
707 kstat_named_t arcstat_l2_evict_reading;
708 kstat_named_t arcstat_l2_evict_l1cached;
709 kstat_named_t arcstat_l2_free_on_write;
710 kstat_named_t arcstat_l2_abort_lowmem;
711 kstat_named_t arcstat_l2_cksum_bad;
712 kstat_named_t arcstat_l2_io_error;
713 kstat_named_t arcstat_l2_size;
714 kstat_named_t arcstat_l2_asize;
715 kstat_named_t arcstat_l2_hdr_size;
716 kstat_named_t arcstat_l2_write_trylock_fail;
717 kstat_named_t arcstat_l2_write_passed_headroom;
718 kstat_named_t arcstat_l2_write_spa_mismatch;
719 kstat_named_t arcstat_l2_write_in_l2;
720 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
721 kstat_named_t arcstat_l2_write_not_cacheable;
722 kstat_named_t arcstat_l2_write_full;
723 kstat_named_t arcstat_l2_write_buffer_iter;
724 kstat_named_t arcstat_l2_write_pios;
725 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
726 kstat_named_t arcstat_l2_write_buffer_list_iter;
727 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
728 kstat_named_t arcstat_memory_throttle_count;
729 kstat_named_t arcstat_meta_used;
730 kstat_named_t arcstat_meta_limit;
731 kstat_named_t arcstat_meta_max;
732 kstat_named_t arcstat_meta_min;
733 kstat_named_t arcstat_sync_wait_for_async;
734 kstat_named_t arcstat_demand_hit_predictive_prefetch;
737 static arc_stats_t arc_stats = {
738 { "hits", KSTAT_DATA_UINT64 },
739 { "misses", KSTAT_DATA_UINT64 },
740 { "demand_data_hits", KSTAT_DATA_UINT64 },
741 { "demand_data_misses", KSTAT_DATA_UINT64 },
742 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
743 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
744 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
745 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
746 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
747 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
748 { "mru_hits", KSTAT_DATA_UINT64 },
749 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
750 { "mfu_hits", KSTAT_DATA_UINT64 },
751 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
752 { "allocated", KSTAT_DATA_UINT64 },
753 { "deleted", KSTAT_DATA_UINT64 },
754 { "mutex_miss", KSTAT_DATA_UINT64 },
755 { "evict_skip", KSTAT_DATA_UINT64 },
756 { "evict_not_enough", KSTAT_DATA_UINT64 },
757 { "evict_l2_cached", KSTAT_DATA_UINT64 },
758 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
759 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
760 { "evict_l2_skip", KSTAT_DATA_UINT64 },
761 { "hash_elements", KSTAT_DATA_UINT64 },
762 { "hash_elements_max", KSTAT_DATA_UINT64 },
763 { "hash_collisions", KSTAT_DATA_UINT64 },
764 { "hash_chains", KSTAT_DATA_UINT64 },
765 { "hash_chain_max", KSTAT_DATA_UINT64 },
766 { "p", KSTAT_DATA_UINT64 },
767 { "c", KSTAT_DATA_UINT64 },
768 { "c_min", KSTAT_DATA_UINT64 },
769 { "c_max", KSTAT_DATA_UINT64 },
770 { "size", KSTAT_DATA_UINT64 },
771 { "compressed_size", KSTAT_DATA_UINT64 },
772 { "uncompressed_size", KSTAT_DATA_UINT64 },
773 { "overhead_size", KSTAT_DATA_UINT64 },
774 { "hdr_size", KSTAT_DATA_UINT64 },
775 { "data_size", KSTAT_DATA_UINT64 },
776 { "metadata_size", KSTAT_DATA_UINT64 },
777 { "other_size", KSTAT_DATA_UINT64 },
778 { "anon_size", KSTAT_DATA_UINT64 },
779 { "anon_evictable_data", KSTAT_DATA_UINT64 },
780 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
781 { "mru_size", KSTAT_DATA_UINT64 },
782 { "mru_evictable_data", KSTAT_DATA_UINT64 },
783 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
784 { "mru_ghost_size", KSTAT_DATA_UINT64 },
785 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
786 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
787 { "mfu_size", KSTAT_DATA_UINT64 },
788 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
789 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
790 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
791 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
792 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
793 { "l2_hits", KSTAT_DATA_UINT64 },
794 { "l2_misses", KSTAT_DATA_UINT64 },
795 { "l2_feeds", KSTAT_DATA_UINT64 },
796 { "l2_rw_clash", KSTAT_DATA_UINT64 },
797 { "l2_read_bytes", KSTAT_DATA_UINT64 },
798 { "l2_write_bytes", KSTAT_DATA_UINT64 },
799 { "l2_writes_sent", KSTAT_DATA_UINT64 },
800 { "l2_writes_done", KSTAT_DATA_UINT64 },
801 { "l2_writes_error", KSTAT_DATA_UINT64 },
802 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
803 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
804 { "l2_evict_reading", KSTAT_DATA_UINT64 },
805 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
806 { "l2_free_on_write", KSTAT_DATA_UINT64 },
807 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
808 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
809 { "l2_io_error", KSTAT_DATA_UINT64 },
810 { "l2_size", KSTAT_DATA_UINT64 },
811 { "l2_asize", KSTAT_DATA_UINT64 },
812 { "l2_hdr_size", KSTAT_DATA_UINT64 },
813 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
814 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
815 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
816 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
817 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
818 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
819 { "l2_write_full", KSTAT_DATA_UINT64 },
820 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
821 { "l2_write_pios", KSTAT_DATA_UINT64 },
822 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
823 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
824 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
825 { "memory_throttle_count", KSTAT_DATA_UINT64 },
826 { "arc_meta_used", KSTAT_DATA_UINT64 },
827 { "arc_meta_limit", KSTAT_DATA_UINT64 },
828 { "arc_meta_max", KSTAT_DATA_UINT64 },
829 { "arc_meta_min", KSTAT_DATA_UINT64 },
830 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
831 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
834 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
836 #define ARCSTAT_INCR(stat, val) \
837 atomic_add_64(&arc_stats.stat.value.ui64, (val))
839 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
840 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
842 #define ARCSTAT_MAX(stat, val) { \
844 while ((val) > (m = arc_stats.stat.value.ui64) && \
845 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
849 #define ARCSTAT_MAXSTAT(stat) \
850 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
853 * We define a macro to allow ARC hits/misses to be easily broken down by
854 * two separate conditions, giving a total of four different subtypes for
855 * each of hits and misses (so eight statistics total).
857 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
860 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
862 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
866 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
868 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
873 static arc_state_t *arc_anon;
874 static arc_state_t *arc_mru;
875 static arc_state_t *arc_mru_ghost;
876 static arc_state_t *arc_mfu;
877 static arc_state_t *arc_mfu_ghost;
878 static arc_state_t *arc_l2c_only;
881 * There are several ARC variables that are critical to export as kstats --
882 * but we don't want to have to grovel around in the kstat whenever we wish to
883 * manipulate them. For these variables, we therefore define them to be in
884 * terms of the statistic variable. This assures that we are not introducing
885 * the possibility of inconsistency by having shadow copies of the variables,
886 * while still allowing the code to be readable.
888 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
889 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
890 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
891 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
892 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
893 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
894 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
895 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
896 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
898 /* compressed size of entire arc */
899 #define arc_compressed_size ARCSTAT(arcstat_compressed_size)
900 /* uncompressed size of entire arc */
901 #define arc_uncompressed_size ARCSTAT(arcstat_uncompressed_size)
902 /* number of bytes in the arc from arc_buf_t's */
903 #define arc_overhead_size ARCSTAT(arcstat_overhead_size)
905 static int arc_no_grow; /* Don't try to grow cache size */
906 static uint64_t arc_tempreserve;
907 static uint64_t arc_loaned_bytes;
909 typedef struct arc_callback arc_callback_t;
911 struct arc_callback {
913 arc_done_func_t *acb_done;
915 boolean_t acb_compressed;
916 zio_t *acb_zio_dummy;
917 arc_callback_t *acb_next;
920 typedef struct arc_write_callback arc_write_callback_t;
922 struct arc_write_callback {
924 arc_done_func_t *awcb_ready;
925 arc_done_func_t *awcb_children_ready;
926 arc_done_func_t *awcb_physdone;
927 arc_done_func_t *awcb_done;
932 * ARC buffers are separated into multiple structs as a memory saving measure:
933 * - Common fields struct, always defined, and embedded within it:
934 * - L2-only fields, always allocated but undefined when not in L2ARC
935 * - L1-only fields, only allocated when in L1ARC
937 * Buffer in L1 Buffer only in L2
938 * +------------------------+ +------------------------+
939 * | arc_buf_hdr_t | | arc_buf_hdr_t |
943 * +------------------------+ +------------------------+
944 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
945 * | (undefined if L1-only) | | |
946 * +------------------------+ +------------------------+
947 * | l1arc_buf_hdr_t |
952 * +------------------------+
954 * Because it's possible for the L2ARC to become extremely large, we can wind
955 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
956 * is minimized by only allocating the fields necessary for an L1-cached buffer
957 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
958 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
959 * words in pointers. arc_hdr_realloc() is used to switch a header between
960 * these two allocation states.
962 typedef struct l1arc_buf_hdr {
963 kmutex_t b_freeze_lock;
964 zio_cksum_t *b_freeze_cksum;
967 * Used for debugging with kmem_flags - by allocating and freeing
968 * b_thawed when the buffer is thawed, we get a record of the stack
969 * trace that thawed it.
976 /* for waiting on writes to complete */
980 /* protected by arc state mutex */
981 arc_state_t *b_state;
982 multilist_node_t b_arc_node;
984 /* updated atomically */
985 clock_t b_arc_access;
987 /* self protecting */
990 arc_callback_t *b_acb;
994 typedef struct l2arc_dev l2arc_dev_t;
996 typedef struct l2arc_buf_hdr {
997 /* protected by arc_buf_hdr mutex */
998 l2arc_dev_t *b_dev; /* L2ARC device */
999 uint64_t b_daddr; /* disk address, offset byte */
1001 list_node_t b_l2node;
1004 struct arc_buf_hdr {
1005 /* protected by hash lock */
1009 arc_buf_contents_t b_type;
1010 arc_buf_hdr_t *b_hash_next;
1011 arc_flags_t b_flags;
1014 * This field stores the size of the data buffer after
1015 * compression, and is set in the arc's zio completion handlers.
1016 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1018 * While the block pointers can store up to 32MB in their psize
1019 * field, we can only store up to 32MB minus 512B. This is due
1020 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1021 * a field of zeros represents 512B in the bp). We can't use a
1022 * bias of 1 since we need to reserve a psize of zero, here, to
1023 * represent holes and embedded blocks.
1025 * This isn't a problem in practice, since the maximum size of a
1026 * buffer is limited to 16MB, so we never need to store 32MB in
1027 * this field. Even in the upstream illumos code base, the
1028 * maximum size of a buffer is limited to 16MB.
1033 * This field stores the size of the data buffer before
1034 * compression, and cannot change once set. It is in units
1035 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1037 uint16_t b_lsize; /* immutable */
1038 uint64_t b_spa; /* immutable */
1040 /* L2ARC fields. Undefined when not in L2ARC. */
1041 l2arc_buf_hdr_t b_l2hdr;
1042 /* L1ARC fields. Undefined when in l2arc_only state */
1043 l1arc_buf_hdr_t b_l1hdr;
1046 #if defined(__FreeBSD__) && defined(_KERNEL)
1048 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1053 val = arc_meta_limit;
1054 err = sysctl_handle_64(oidp, &val, 0, req);
1055 if (err != 0 || req->newptr == NULL)
1058 if (val <= 0 || val > arc_c_max)
1061 arc_meta_limit = val;
1066 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1072 err = sysctl_handle_64(oidp, &val, 0, req);
1073 if (err != 0 || req->newptr == NULL)
1076 if (zfs_arc_max == 0) {
1077 /* Loader tunable so blindly set */
1082 if (val < arc_abs_min || val > kmem_size())
1084 if (val < arc_c_min)
1086 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1092 arc_p = (arc_c >> 1);
1094 if (zfs_arc_meta_limit == 0) {
1095 /* limit meta-data to 1/4 of the arc capacity */
1096 arc_meta_limit = arc_c_max / 4;
1099 /* if kmem_flags are set, lets try to use less memory */
1100 if (kmem_debugging())
1103 zfs_arc_max = arc_c;
1109 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1115 err = sysctl_handle_64(oidp, &val, 0, req);
1116 if (err != 0 || req->newptr == NULL)
1119 if (zfs_arc_min == 0) {
1120 /* Loader tunable so blindly set */
1125 if (val < arc_abs_min || val > arc_c_max)
1130 if (zfs_arc_meta_min == 0)
1131 arc_meta_min = arc_c_min / 2;
1133 if (arc_c < arc_c_min)
1136 zfs_arc_min = arc_c_min;
1142 #define GHOST_STATE(state) \
1143 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
1144 (state) == arc_l2c_only)
1146 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1147 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1148 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1149 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1150 #define HDR_COMPRESSION_ENABLED(hdr) \
1151 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1153 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1154 #define HDR_L2_READING(hdr) \
1155 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1156 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1157 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1158 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1159 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1160 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1162 #define HDR_ISTYPE_METADATA(hdr) \
1163 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1164 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1166 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1167 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1169 /* For storing compression mode in b_flags */
1170 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1172 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1173 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1174 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1175 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1177 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
1178 #define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1179 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1185 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1186 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1189 * Hash table routines
1192 #define HT_LOCK_PAD CACHE_LINE_SIZE
1197 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1201 #define BUF_LOCKS 256
1202 typedef struct buf_hash_table {
1204 arc_buf_hdr_t **ht_table;
1205 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1208 static buf_hash_table_t buf_hash_table;
1210 #define BUF_HASH_INDEX(spa, dva, birth) \
1211 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1212 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1213 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1214 #define HDR_LOCK(hdr) \
1215 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1217 uint64_t zfs_crc64_table[256];
1223 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1224 #define L2ARC_HEADROOM 2 /* num of writes */
1226 * If we discover during ARC scan any buffers to be compressed, we boost
1227 * our headroom for the next scanning cycle by this percentage multiple.
1229 #define L2ARC_HEADROOM_BOOST 200
1230 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1231 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1233 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1234 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1236 /* L2ARC Performance Tunables */
1237 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1238 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1239 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1240 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1241 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1242 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1243 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1244 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1245 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1247 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1248 &l2arc_write_max, 0, "max write size");
1249 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1250 &l2arc_write_boost, 0, "extra write during warmup");
1251 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1252 &l2arc_headroom, 0, "number of dev writes");
1253 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1254 &l2arc_feed_secs, 0, "interval seconds");
1255 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1256 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1258 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1259 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1260 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1261 &l2arc_feed_again, 0, "turbo warmup");
1262 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1263 &l2arc_norw, 0, "no reads during writes");
1265 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1266 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1267 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1268 &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1269 "size of anonymous state");
1270 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1271 &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1272 "size of anonymous state");
1274 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1275 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1276 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1277 &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1278 "size of metadata in mru state");
1279 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1280 &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1281 "size of data in mru state");
1283 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1284 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1285 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1286 &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1287 "size of metadata in mru ghost state");
1288 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1289 &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1290 "size of data in mru ghost state");
1292 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1293 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1294 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1295 &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1296 "size of metadata in mfu state");
1297 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1298 &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1299 "size of data in mfu state");
1301 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1302 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1303 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1304 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1305 "size of metadata in mfu ghost state");
1306 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1307 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1308 "size of data in mfu ghost state");
1310 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1311 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1317 vdev_t *l2ad_vdev; /* vdev */
1318 spa_t *l2ad_spa; /* spa */
1319 uint64_t l2ad_hand; /* next write location */
1320 uint64_t l2ad_start; /* first addr on device */
1321 uint64_t l2ad_end; /* last addr on device */
1322 boolean_t l2ad_first; /* first sweep through */
1323 boolean_t l2ad_writing; /* currently writing */
1324 kmutex_t l2ad_mtx; /* lock for buffer list */
1325 list_t l2ad_buflist; /* buffer list */
1326 list_node_t l2ad_node; /* device list node */
1327 refcount_t l2ad_alloc; /* allocated bytes */
1330 static list_t L2ARC_dev_list; /* device list */
1331 static list_t *l2arc_dev_list; /* device list pointer */
1332 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1333 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1334 static list_t L2ARC_free_on_write; /* free after write buf list */
1335 static list_t *l2arc_free_on_write; /* free after write list ptr */
1336 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1337 static uint64_t l2arc_ndev; /* number of devices */
1339 typedef struct l2arc_read_callback {
1340 arc_buf_hdr_t *l2rcb_hdr; /* read header */
1341 blkptr_t l2rcb_bp; /* original blkptr */
1342 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1343 int l2rcb_flags; /* original flags */
1344 void *l2rcb_data; /* temporary buffer */
1345 } l2arc_read_callback_t;
1347 typedef struct l2arc_write_callback {
1348 l2arc_dev_t *l2wcb_dev; /* device info */
1349 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1350 } l2arc_write_callback_t;
1352 typedef struct l2arc_data_free {
1353 /* protected by l2arc_free_on_write_mtx */
1356 arc_buf_contents_t l2df_type;
1357 list_node_t l2df_list_node;
1358 } l2arc_data_free_t;
1360 static kmutex_t l2arc_feed_thr_lock;
1361 static kcondvar_t l2arc_feed_thr_cv;
1362 static uint8_t l2arc_thread_exit;
1364 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1365 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1366 static void arc_hdr_free_pdata(arc_buf_hdr_t *hdr);
1367 static void arc_hdr_alloc_pdata(arc_buf_hdr_t *);
1368 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1369 static boolean_t arc_is_overflowing();
1370 static void arc_buf_watch(arc_buf_t *);
1372 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1373 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1374 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1375 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1377 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1378 static void l2arc_read_done(zio_t *);
1381 l2arc_trim(const arc_buf_hdr_t *hdr)
1383 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1385 ASSERT(HDR_HAS_L2HDR(hdr));
1386 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1388 if (HDR_GET_PSIZE(hdr) != 0) {
1389 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1390 HDR_GET_PSIZE(hdr), 0);
1395 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1397 uint8_t *vdva = (uint8_t *)dva;
1398 uint64_t crc = -1ULL;
1401 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1403 for (i = 0; i < sizeof (dva_t); i++)
1404 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1406 crc ^= (spa>>8) ^ birth;
1411 #define HDR_EMPTY(hdr) \
1412 ((hdr)->b_dva.dva_word[0] == 0 && \
1413 (hdr)->b_dva.dva_word[1] == 0)
1415 #define HDR_EQUAL(spa, dva, birth, hdr) \
1416 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1417 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1418 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1421 buf_discard_identity(arc_buf_hdr_t *hdr)
1423 hdr->b_dva.dva_word[0] = 0;
1424 hdr->b_dva.dva_word[1] = 0;
1428 static arc_buf_hdr_t *
1429 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1431 const dva_t *dva = BP_IDENTITY(bp);
1432 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1433 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1434 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1437 mutex_enter(hash_lock);
1438 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1439 hdr = hdr->b_hash_next) {
1440 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1445 mutex_exit(hash_lock);
1451 * Insert an entry into the hash table. If there is already an element
1452 * equal to elem in the hash table, then the already existing element
1453 * will be returned and the new element will not be inserted.
1454 * Otherwise returns NULL.
1455 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1457 static arc_buf_hdr_t *
1458 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1460 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1461 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1462 arc_buf_hdr_t *fhdr;
1465 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1466 ASSERT(hdr->b_birth != 0);
1467 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1469 if (lockp != NULL) {
1471 mutex_enter(hash_lock);
1473 ASSERT(MUTEX_HELD(hash_lock));
1476 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1477 fhdr = fhdr->b_hash_next, i++) {
1478 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1482 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1483 buf_hash_table.ht_table[idx] = hdr;
1484 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1486 /* collect some hash table performance data */
1488 ARCSTAT_BUMP(arcstat_hash_collisions);
1490 ARCSTAT_BUMP(arcstat_hash_chains);
1492 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1495 ARCSTAT_BUMP(arcstat_hash_elements);
1496 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1502 buf_hash_remove(arc_buf_hdr_t *hdr)
1504 arc_buf_hdr_t *fhdr, **hdrp;
1505 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1507 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1508 ASSERT(HDR_IN_HASH_TABLE(hdr));
1510 hdrp = &buf_hash_table.ht_table[idx];
1511 while ((fhdr = *hdrp) != hdr) {
1512 ASSERT3P(fhdr, !=, NULL);
1513 hdrp = &fhdr->b_hash_next;
1515 *hdrp = hdr->b_hash_next;
1516 hdr->b_hash_next = NULL;
1517 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1519 /* collect some hash table performance data */
1520 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1522 if (buf_hash_table.ht_table[idx] &&
1523 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1524 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1528 * Global data structures and functions for the buf kmem cache.
1530 static kmem_cache_t *hdr_full_cache;
1531 static kmem_cache_t *hdr_l2only_cache;
1532 static kmem_cache_t *buf_cache;
1539 kmem_free(buf_hash_table.ht_table,
1540 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1541 for (i = 0; i < BUF_LOCKS; i++)
1542 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1543 kmem_cache_destroy(hdr_full_cache);
1544 kmem_cache_destroy(hdr_l2only_cache);
1545 kmem_cache_destroy(buf_cache);
1549 * Constructor callback - called when the cache is empty
1550 * and a new buf is requested.
1554 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1556 arc_buf_hdr_t *hdr = vbuf;
1558 bzero(hdr, HDR_FULL_SIZE);
1559 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1560 refcount_create(&hdr->b_l1hdr.b_refcnt);
1561 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1562 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1563 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1570 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1572 arc_buf_hdr_t *hdr = vbuf;
1574 bzero(hdr, HDR_L2ONLY_SIZE);
1575 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1582 buf_cons(void *vbuf, void *unused, int kmflag)
1584 arc_buf_t *buf = vbuf;
1586 bzero(buf, sizeof (arc_buf_t));
1587 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1588 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1594 * Destructor callback - called when a cached buf is
1595 * no longer required.
1599 hdr_full_dest(void *vbuf, void *unused)
1601 arc_buf_hdr_t *hdr = vbuf;
1603 ASSERT(HDR_EMPTY(hdr));
1604 cv_destroy(&hdr->b_l1hdr.b_cv);
1605 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1606 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1607 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1608 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1613 hdr_l2only_dest(void *vbuf, void *unused)
1615 arc_buf_hdr_t *hdr = vbuf;
1617 ASSERT(HDR_EMPTY(hdr));
1618 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1623 buf_dest(void *vbuf, void *unused)
1625 arc_buf_t *buf = vbuf;
1627 mutex_destroy(&buf->b_evict_lock);
1628 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1632 * Reclaim callback -- invoked when memory is low.
1636 hdr_recl(void *unused)
1638 dprintf("hdr_recl called\n");
1640 * umem calls the reclaim func when we destroy the buf cache,
1641 * which is after we do arc_fini().
1644 cv_signal(&arc_reclaim_thread_cv);
1651 uint64_t hsize = 1ULL << 12;
1655 * The hash table is big enough to fill all of physical memory
1656 * with an average block size of zfs_arc_average_blocksize (default 8K).
1657 * By default, the table will take up
1658 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1660 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1663 buf_hash_table.ht_mask = hsize - 1;
1664 buf_hash_table.ht_table =
1665 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1666 if (buf_hash_table.ht_table == NULL) {
1667 ASSERT(hsize > (1ULL << 8));
1672 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1673 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1674 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1675 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1677 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1678 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1680 for (i = 0; i < 256; i++)
1681 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1682 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1684 for (i = 0; i < BUF_LOCKS; i++) {
1685 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1686 NULL, MUTEX_DEFAULT, NULL);
1691 * This is the size that the buf occupies in memory. If the buf is compressed,
1692 * it will correspond to the compressed size. You should use this method of
1693 * getting the buf size unless you explicitly need the logical size.
1696 arc_buf_size(arc_buf_t *buf)
1698 return (ARC_BUF_COMPRESSED(buf) ?
1699 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1703 arc_buf_lsize(arc_buf_t *buf)
1705 return (HDR_GET_LSIZE(buf->b_hdr));
1709 arc_get_compression(arc_buf_t *buf)
1711 return (ARC_BUF_COMPRESSED(buf) ?
1712 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1715 #define ARC_MINTIME (hz>>4) /* 62 ms */
1717 static inline boolean_t
1718 arc_buf_is_shared(arc_buf_t *buf)
1720 boolean_t shared = (buf->b_data != NULL &&
1721 buf->b_data == buf->b_hdr->b_l1hdr.b_pdata);
1722 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1723 IMPLY(shared, ARC_BUF_SHARED(buf));
1724 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1727 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1728 * already being shared" requirement prevents us from doing that.
1735 * Free the checksum associated with this header. If there is no checksum, this
1739 arc_cksum_free(arc_buf_hdr_t *hdr)
1741 ASSERT(HDR_HAS_L1HDR(hdr));
1742 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1743 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1744 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1745 hdr->b_l1hdr.b_freeze_cksum = NULL;
1747 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1751 * Return true iff at least one of the bufs on hdr is not compressed.
1754 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1756 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1757 if (!ARC_BUF_COMPRESSED(b)) {
1765 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1766 * matches the checksum that is stored in the hdr. If there is no checksum,
1767 * or if the buf is compressed, this is a no-op.
1770 arc_cksum_verify(arc_buf_t *buf)
1772 arc_buf_hdr_t *hdr = buf->b_hdr;
1775 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1778 if (ARC_BUF_COMPRESSED(buf)) {
1779 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1780 arc_hdr_has_uncompressed_buf(hdr));
1784 ASSERT(HDR_HAS_L1HDR(hdr));
1786 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1787 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1788 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1792 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1793 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1794 panic("buffer modified while frozen!");
1795 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1799 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1801 enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1802 boolean_t valid_cksum;
1804 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1805 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1808 * We rely on the blkptr's checksum to determine if the block
1809 * is valid or not. When compressed arc is enabled, the l2arc
1810 * writes the block to the l2arc just as it appears in the pool.
1811 * This allows us to use the blkptr's checksum to validate the
1812 * data that we just read off of the l2arc without having to store
1813 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1814 * arc is disabled, then the data written to the l2arc is always
1815 * uncompressed and won't match the block as it exists in the main
1816 * pool. When this is the case, we must first compress it if it is
1817 * compressed on the main pool before we can validate the checksum.
1819 if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1820 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1821 uint64_t lsize = HDR_GET_LSIZE(hdr);
1824 void *cbuf = zio_buf_alloc(HDR_GET_PSIZE(hdr));
1825 csize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1826 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1827 if (csize < HDR_GET_PSIZE(hdr)) {
1829 * Compressed blocks are always a multiple of the
1830 * smallest ashift in the pool. Ideally, we would
1831 * like to round up the csize to the next
1832 * spa_min_ashift but that value may have changed
1833 * since the block was last written. Instead,
1834 * we rely on the fact that the hdr's psize
1835 * was set to the psize of the block when it was
1836 * last written. We set the csize to that value
1837 * and zero out any part that should not contain
1840 bzero((char *)cbuf + csize, HDR_GET_PSIZE(hdr) - csize);
1841 csize = HDR_GET_PSIZE(hdr);
1843 zio_push_transform(zio, cbuf, csize, HDR_GET_PSIZE(hdr), NULL);
1847 * Block pointers always store the checksum for the logical data.
1848 * If the block pointer has the gang bit set, then the checksum
1849 * it represents is for the reconstituted data and not for an
1850 * individual gang member. The zio pipeline, however, must be able to
1851 * determine the checksum of each of the gang constituents so it
1852 * treats the checksum comparison differently than what we need
1853 * for l2arc blocks. This prevents us from using the
1854 * zio_checksum_error() interface directly. Instead we must call the
1855 * zio_checksum_error_impl() so that we can ensure the checksum is
1856 * generated using the correct checksum algorithm and accounts for the
1857 * logical I/O size and not just a gang fragment.
1859 valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1860 BP_GET_CHECKSUM(zio->io_bp), zio->io_data, zio->io_size,
1861 zio->io_offset, NULL) == 0);
1862 zio_pop_transforms(zio);
1863 return (valid_cksum);
1867 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1868 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1869 * isn't modified later on. If buf is compressed or there is already a checksum
1870 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1873 arc_cksum_compute(arc_buf_t *buf)
1875 arc_buf_hdr_t *hdr = buf->b_hdr;
1877 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1880 ASSERT(HDR_HAS_L1HDR(hdr));
1882 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1883 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1884 ASSERT(arc_hdr_has_uncompressed_buf(hdr));
1885 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1887 } else if (ARC_BUF_COMPRESSED(buf)) {
1888 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1892 ASSERT(!ARC_BUF_COMPRESSED(buf));
1893 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1895 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1896 hdr->b_l1hdr.b_freeze_cksum);
1897 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1905 typedef struct procctl {
1913 arc_buf_unwatch(arc_buf_t *buf)
1920 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1921 ctl.prwatch.pr_size = 0;
1922 ctl.prwatch.pr_wflags = 0;
1923 result = write(arc_procfd, &ctl, sizeof (ctl));
1924 ASSERT3U(result, ==, sizeof (ctl));
1931 arc_buf_watch(arc_buf_t *buf)
1938 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1939 ctl.prwatch.pr_size = arc_buf_size(buf);
1940 ctl.prwatch.pr_wflags = WA_WRITE;
1941 result = write(arc_procfd, &ctl, sizeof (ctl));
1942 ASSERT3U(result, ==, sizeof (ctl));
1946 #endif /* illumos */
1948 static arc_buf_contents_t
1949 arc_buf_type(arc_buf_hdr_t *hdr)
1951 arc_buf_contents_t type;
1952 if (HDR_ISTYPE_METADATA(hdr)) {
1953 type = ARC_BUFC_METADATA;
1955 type = ARC_BUFC_DATA;
1957 VERIFY3U(hdr->b_type, ==, type);
1962 arc_is_metadata(arc_buf_t *buf)
1964 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1968 arc_bufc_to_flags(arc_buf_contents_t type)
1972 /* metadata field is 0 if buffer contains normal data */
1974 case ARC_BUFC_METADATA:
1975 return (ARC_FLAG_BUFC_METADATA);
1979 panic("undefined ARC buffer type!");
1980 return ((uint32_t)-1);
1984 arc_buf_thaw(arc_buf_t *buf)
1986 arc_buf_hdr_t *hdr = buf->b_hdr;
1988 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1989 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1991 arc_cksum_verify(buf);
1994 * Compressed buffers do not manipulate the b_freeze_cksum or
1995 * allocate b_thawed.
1997 if (ARC_BUF_COMPRESSED(buf)) {
1998 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1999 arc_hdr_has_uncompressed_buf(hdr));
2003 ASSERT(HDR_HAS_L1HDR(hdr));
2004 arc_cksum_free(hdr);
2006 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
2008 if (zfs_flags & ZFS_DEBUG_MODIFY) {
2009 if (hdr->b_l1hdr.b_thawed != NULL)
2010 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2011 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
2015 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2018 arc_buf_unwatch(buf);
2023 arc_buf_freeze(arc_buf_t *buf)
2025 arc_buf_hdr_t *hdr = buf->b_hdr;
2026 kmutex_t *hash_lock;
2028 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2031 if (ARC_BUF_COMPRESSED(buf)) {
2032 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2033 arc_hdr_has_uncompressed_buf(hdr));
2037 hash_lock = HDR_LOCK(hdr);
2038 mutex_enter(hash_lock);
2040 ASSERT(HDR_HAS_L1HDR(hdr));
2041 ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2042 hdr->b_l1hdr.b_state == arc_anon);
2043 arc_cksum_compute(buf);
2044 mutex_exit(hash_lock);
2048 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2049 * the following functions should be used to ensure that the flags are
2050 * updated in a thread-safe way. When manipulating the flags either
2051 * the hash_lock must be held or the hdr must be undiscoverable. This
2052 * ensures that we're not racing with any other threads when updating
2056 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2058 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2059 hdr->b_flags |= flags;
2063 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2065 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2066 hdr->b_flags &= ~flags;
2070 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2071 * done in a special way since we have to clear and set bits
2072 * at the same time. Consumers that wish to set the compression bits
2073 * must use this function to ensure that the flags are updated in
2074 * thread-safe manner.
2077 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2079 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2082 * Holes and embedded blocks will always have a psize = 0 so
2083 * we ignore the compression of the blkptr and set the
2084 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2085 * Holes and embedded blocks remain anonymous so we don't
2086 * want to uncompress them. Mark them as uncompressed.
2088 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2089 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2090 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
2091 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2092 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2094 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2095 HDR_SET_COMPRESS(hdr, cmp);
2096 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2097 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2102 * Looks for another buf on the same hdr which has the data decompressed, copies
2103 * from it, and returns true. If no such buf exists, returns false.
2106 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
2108 arc_buf_hdr_t *hdr = buf->b_hdr;
2109 boolean_t copied = B_FALSE;
2111 ASSERT(HDR_HAS_L1HDR(hdr));
2112 ASSERT3P(buf->b_data, !=, NULL);
2113 ASSERT(!ARC_BUF_COMPRESSED(buf));
2115 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
2116 from = from->b_next) {
2117 /* can't use our own data buffer */
2122 if (!ARC_BUF_COMPRESSED(from)) {
2123 bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
2130 * There were no decompressed bufs, so there should not be a
2131 * checksum on the hdr either.
2133 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
2139 * Given a buf that has a data buffer attached to it, this function will
2140 * efficiently fill the buf with data of the specified compression setting from
2141 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2142 * are already sharing a data buf, no copy is performed.
2144 * If the buf is marked as compressed but uncompressed data was requested, this
2145 * will allocate a new data buffer for the buf, remove that flag, and fill the
2146 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2147 * uncompressed data, and (since we haven't added support for it yet) if you
2148 * want compressed data your buf must already be marked as compressed and have
2149 * the correct-sized data buffer.
2152 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
2154 arc_buf_hdr_t *hdr = buf->b_hdr;
2155 boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2156 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2158 ASSERT3P(buf->b_data, !=, NULL);
2159 IMPLY(compressed, hdr_compressed);
2160 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2162 if (hdr_compressed == compressed) {
2163 if (!arc_buf_is_shared(buf)) {
2164 bcopy(hdr->b_l1hdr.b_pdata, buf->b_data,
2168 ASSERT(hdr_compressed);
2169 ASSERT(!compressed);
2170 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2173 * If the buf is sharing its data with the hdr, unlink it and
2174 * allocate a new data buffer for the buf.
2176 if (arc_buf_is_shared(buf)) {
2177 ASSERT(ARC_BUF_COMPRESSED(buf));
2179 /* We need to give the buf it's own b_data */
2180 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2182 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2183 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2185 /* Previously overhead was 0; just add new overhead */
2186 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2187 } else if (ARC_BUF_COMPRESSED(buf)) {
2188 /* We need to reallocate the buf's b_data */
2189 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2192 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2194 /* We increased the size of b_data; update overhead */
2195 ARCSTAT_INCR(arcstat_overhead_size,
2196 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2200 * Regardless of the buf's previous compression settings, it
2201 * should not be compressed at the end of this function.
2203 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2206 * Try copying the data from another buf which already has a
2207 * decompressed version. If that's not possible, it's time to
2208 * bite the bullet and decompress the data from the hdr.
2210 if (arc_buf_try_copy_decompressed_data(buf)) {
2211 /* Skip byteswapping and checksumming (already done) */
2212 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
2215 int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2216 hdr->b_l1hdr.b_pdata, buf->b_data,
2217 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2220 * Absent hardware errors or software bugs, this should
2221 * be impossible, but log it anyway so we can debug it.
2225 "hdr %p, compress %d, psize %d, lsize %d",
2226 hdr, HDR_GET_COMPRESS(hdr),
2227 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2228 return (SET_ERROR(EIO));
2233 /* Byteswap the buf's data if necessary */
2234 if (bswap != DMU_BSWAP_NUMFUNCS) {
2235 ASSERT(!HDR_SHARED_DATA(hdr));
2236 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2237 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2240 /* Compute the hdr's checksum if necessary */
2241 arc_cksum_compute(buf);
2247 arc_decompress(arc_buf_t *buf)
2249 return (arc_buf_fill(buf, B_FALSE));
2253 * Return the size of the block, b_pdata, that is stored in the arc_buf_hdr_t.
2256 arc_hdr_size(arc_buf_hdr_t *hdr)
2260 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2261 HDR_GET_PSIZE(hdr) > 0) {
2262 size = HDR_GET_PSIZE(hdr);
2264 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2265 size = HDR_GET_LSIZE(hdr);
2271 * Increment the amount of evictable space in the arc_state_t's refcount.
2272 * We account for the space used by the hdr and the arc buf individually
2273 * so that we can add and remove them from the refcount individually.
2276 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2278 arc_buf_contents_t type = arc_buf_type(hdr);
2280 ASSERT(HDR_HAS_L1HDR(hdr));
2282 if (GHOST_STATE(state)) {
2283 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2284 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2285 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2286 (void) refcount_add_many(&state->arcs_esize[type],
2287 HDR_GET_LSIZE(hdr), hdr);
2291 ASSERT(!GHOST_STATE(state));
2292 if (hdr->b_l1hdr.b_pdata != NULL) {
2293 (void) refcount_add_many(&state->arcs_esize[type],
2294 arc_hdr_size(hdr), hdr);
2296 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2297 buf = buf->b_next) {
2298 if (arc_buf_is_shared(buf))
2300 (void) refcount_add_many(&state->arcs_esize[type],
2301 arc_buf_size(buf), buf);
2306 * Decrement the amount of evictable space in the arc_state_t's refcount.
2307 * We account for the space used by the hdr and the arc buf individually
2308 * so that we can add and remove them from the refcount individually.
2311 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2313 arc_buf_contents_t type = arc_buf_type(hdr);
2315 ASSERT(HDR_HAS_L1HDR(hdr));
2317 if (GHOST_STATE(state)) {
2318 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2319 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2320 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2321 (void) refcount_remove_many(&state->arcs_esize[type],
2322 HDR_GET_LSIZE(hdr), hdr);
2326 ASSERT(!GHOST_STATE(state));
2327 if (hdr->b_l1hdr.b_pdata != NULL) {
2328 (void) refcount_remove_many(&state->arcs_esize[type],
2329 arc_hdr_size(hdr), hdr);
2331 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2332 buf = buf->b_next) {
2333 if (arc_buf_is_shared(buf))
2335 (void) refcount_remove_many(&state->arcs_esize[type],
2336 arc_buf_size(buf), buf);
2341 * Add a reference to this hdr indicating that someone is actively
2342 * referencing that memory. When the refcount transitions from 0 to 1,
2343 * we remove it from the respective arc_state_t list to indicate that
2344 * it is not evictable.
2347 add_reference(arc_buf_hdr_t *hdr, void *tag)
2349 ASSERT(HDR_HAS_L1HDR(hdr));
2350 if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2351 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2352 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2353 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2356 arc_state_t *state = hdr->b_l1hdr.b_state;
2358 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2359 (state != arc_anon)) {
2360 /* We don't use the L2-only state list. */
2361 if (state != arc_l2c_only) {
2362 multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2364 arc_evictable_space_decrement(hdr, state);
2366 /* remove the prefetch flag if we get a reference */
2367 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2372 * Remove a reference from this hdr. When the reference transitions from
2373 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2374 * list making it eligible for eviction.
2377 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2380 arc_state_t *state = hdr->b_l1hdr.b_state;
2382 ASSERT(HDR_HAS_L1HDR(hdr));
2383 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2384 ASSERT(!GHOST_STATE(state));
2387 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2388 * check to prevent usage of the arc_l2c_only list.
2390 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2391 (state != arc_anon)) {
2392 multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2393 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2394 arc_evictable_space_increment(hdr, state);
2400 * Move the supplied buffer to the indicated state. The hash lock
2401 * for the buffer must be held by the caller.
2404 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2405 kmutex_t *hash_lock)
2407 arc_state_t *old_state;
2410 boolean_t update_old, update_new;
2411 arc_buf_contents_t buftype = arc_buf_type(hdr);
2414 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2415 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2416 * L1 hdr doesn't always exist when we change state to arc_anon before
2417 * destroying a header, in which case reallocating to add the L1 hdr is
2420 if (HDR_HAS_L1HDR(hdr)) {
2421 old_state = hdr->b_l1hdr.b_state;
2422 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2423 bufcnt = hdr->b_l1hdr.b_bufcnt;
2424 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pdata != NULL);
2426 old_state = arc_l2c_only;
2429 update_old = B_FALSE;
2431 update_new = update_old;
2433 ASSERT(MUTEX_HELD(hash_lock));
2434 ASSERT3P(new_state, !=, old_state);
2435 ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2436 ASSERT(old_state != arc_anon || bufcnt <= 1);
2439 * If this buffer is evictable, transfer it from the
2440 * old state list to the new state list.
2443 if (old_state != arc_anon && old_state != arc_l2c_only) {
2444 ASSERT(HDR_HAS_L1HDR(hdr));
2445 multilist_remove(old_state->arcs_list[buftype], hdr);
2447 if (GHOST_STATE(old_state)) {
2449 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2450 update_old = B_TRUE;
2452 arc_evictable_space_decrement(hdr, old_state);
2454 if (new_state != arc_anon && new_state != arc_l2c_only) {
2457 * An L1 header always exists here, since if we're
2458 * moving to some L1-cached state (i.e. not l2c_only or
2459 * anonymous), we realloc the header to add an L1hdr
2462 ASSERT(HDR_HAS_L1HDR(hdr));
2463 multilist_insert(new_state->arcs_list[buftype], hdr);
2465 if (GHOST_STATE(new_state)) {
2467 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2468 update_new = B_TRUE;
2470 arc_evictable_space_increment(hdr, new_state);
2474 ASSERT(!HDR_EMPTY(hdr));
2475 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2476 buf_hash_remove(hdr);
2478 /* adjust state sizes (ignore arc_l2c_only) */
2480 if (update_new && new_state != arc_l2c_only) {
2481 ASSERT(HDR_HAS_L1HDR(hdr));
2482 if (GHOST_STATE(new_state)) {
2486 * When moving a header to a ghost state, we first
2487 * remove all arc buffers. Thus, we'll have a
2488 * bufcnt of zero, and no arc buffer to use for
2489 * the reference. As a result, we use the arc
2490 * header pointer for the reference.
2492 (void) refcount_add_many(&new_state->arcs_size,
2493 HDR_GET_LSIZE(hdr), hdr);
2494 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2496 uint32_t buffers = 0;
2499 * Each individual buffer holds a unique reference,
2500 * thus we must remove each of these references one
2503 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2504 buf = buf->b_next) {
2505 ASSERT3U(bufcnt, !=, 0);
2509 * When the arc_buf_t is sharing the data
2510 * block with the hdr, the owner of the
2511 * reference belongs to the hdr. Only
2512 * add to the refcount if the arc_buf_t is
2515 if (arc_buf_is_shared(buf))
2518 (void) refcount_add_many(&new_state->arcs_size,
2519 arc_buf_size(buf), buf);
2521 ASSERT3U(bufcnt, ==, buffers);
2523 if (hdr->b_l1hdr.b_pdata != NULL) {
2524 (void) refcount_add_many(&new_state->arcs_size,
2525 arc_hdr_size(hdr), hdr);
2527 ASSERT(GHOST_STATE(old_state));
2532 if (update_old && old_state != arc_l2c_only) {
2533 ASSERT(HDR_HAS_L1HDR(hdr));
2534 if (GHOST_STATE(old_state)) {
2536 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2539 * When moving a header off of a ghost state,
2540 * the header will not contain any arc buffers.
2541 * We use the arc header pointer for the reference
2542 * which is exactly what we did when we put the
2543 * header on the ghost state.
2546 (void) refcount_remove_many(&old_state->arcs_size,
2547 HDR_GET_LSIZE(hdr), hdr);
2549 uint32_t buffers = 0;
2552 * Each individual buffer holds a unique reference,
2553 * thus we must remove each of these references one
2556 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2557 buf = buf->b_next) {
2558 ASSERT3U(bufcnt, !=, 0);
2562 * When the arc_buf_t is sharing the data
2563 * block with the hdr, the owner of the
2564 * reference belongs to the hdr. Only
2565 * add to the refcount if the arc_buf_t is
2568 if (arc_buf_is_shared(buf))
2571 (void) refcount_remove_many(
2572 &old_state->arcs_size, arc_buf_size(buf),
2575 ASSERT3U(bufcnt, ==, buffers);
2576 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2577 (void) refcount_remove_many(
2578 &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2582 if (HDR_HAS_L1HDR(hdr))
2583 hdr->b_l1hdr.b_state = new_state;
2586 * L2 headers should never be on the L2 state list since they don't
2587 * have L1 headers allocated.
2589 ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2590 multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2594 arc_space_consume(uint64_t space, arc_space_type_t type)
2596 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2599 case ARC_SPACE_DATA:
2600 ARCSTAT_INCR(arcstat_data_size, space);
2602 case ARC_SPACE_META:
2603 ARCSTAT_INCR(arcstat_metadata_size, space);
2605 case ARC_SPACE_OTHER:
2606 ARCSTAT_INCR(arcstat_other_size, space);
2608 case ARC_SPACE_HDRS:
2609 ARCSTAT_INCR(arcstat_hdr_size, space);
2611 case ARC_SPACE_L2HDRS:
2612 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
2616 if (type != ARC_SPACE_DATA)
2617 ARCSTAT_INCR(arcstat_meta_used, space);
2619 atomic_add_64(&arc_size, space);
2623 arc_space_return(uint64_t space, arc_space_type_t type)
2625 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2628 case ARC_SPACE_DATA:
2629 ARCSTAT_INCR(arcstat_data_size, -space);
2631 case ARC_SPACE_META:
2632 ARCSTAT_INCR(arcstat_metadata_size, -space);
2634 case ARC_SPACE_OTHER:
2635 ARCSTAT_INCR(arcstat_other_size, -space);
2637 case ARC_SPACE_HDRS:
2638 ARCSTAT_INCR(arcstat_hdr_size, -space);
2640 case ARC_SPACE_L2HDRS:
2641 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2645 if (type != ARC_SPACE_DATA) {
2646 ASSERT(arc_meta_used >= space);
2647 if (arc_meta_max < arc_meta_used)
2648 arc_meta_max = arc_meta_used;
2649 ARCSTAT_INCR(arcstat_meta_used, -space);
2652 ASSERT(arc_size >= space);
2653 atomic_add_64(&arc_size, -space);
2657 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2658 * with the hdr's b_pdata.
2661 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2664 * The criteria for sharing a hdr's data are:
2665 * 1. the hdr's compression matches the buf's compression
2666 * 2. the hdr doesn't need to be byteswapped
2667 * 3. the hdr isn't already being shared
2668 * 4. the buf is either compressed or it is the last buf in the hdr list
2670 * Criterion #4 maintains the invariant that shared uncompressed
2671 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2672 * might ask, "if a compressed buf is allocated first, won't that be the
2673 * last thing in the list?", but in that case it's impossible to create
2674 * a shared uncompressed buf anyway (because the hdr must be compressed
2675 * to have the compressed buf). You might also think that #3 is
2676 * sufficient to make this guarantee, however it's possible
2677 * (specifically in the rare L2ARC write race mentioned in
2678 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2679 * is sharable, but wasn't at the time of its allocation. Rather than
2680 * allow a new shared uncompressed buf to be created and then shuffle
2681 * the list around to make it the last element, this simply disallows
2682 * sharing if the new buf isn't the first to be added.
2684 ASSERT3P(buf->b_hdr, ==, hdr);
2685 boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2686 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2687 return (buf_compressed == hdr_compressed &&
2688 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2689 !HDR_SHARED_DATA(hdr) &&
2690 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2694 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2695 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2696 * copy was made successfully, or an error code otherwise.
2699 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2700 boolean_t fill, arc_buf_t **ret)
2704 ASSERT(HDR_HAS_L1HDR(hdr));
2705 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2706 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2707 hdr->b_type == ARC_BUFC_METADATA);
2708 ASSERT3P(ret, !=, NULL);
2709 ASSERT3P(*ret, ==, NULL);
2711 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2714 buf->b_next = hdr->b_l1hdr.b_buf;
2717 add_reference(hdr, tag);
2720 * We're about to change the hdr's b_flags. We must either
2721 * hold the hash_lock or be undiscoverable.
2723 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2726 * Only honor requests for compressed bufs if the hdr is actually
2729 if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2730 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2733 * If the hdr's data can be shared then we share the data buffer and
2734 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2735 * sharing it's b_pdata with the arc_buf_t. Otherwise, we allocate a new
2736 * buffer to store the buf's data.
2738 * There is one additional restriction here because we're sharing
2739 * hdr -> buf instead of the usual buf -> hdr: the hdr can't be actively
2740 * involved in an L2ARC write, because if this buf is used by an
2741 * arc_write() then the hdr's data buffer will be released when the
2742 * write completes, even though the L2ARC write might still be using it.
2744 boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr);
2746 /* Set up b_data and sharing */
2748 buf->b_data = hdr->b_l1hdr.b_pdata;
2749 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2750 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2753 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2754 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2756 VERIFY3P(buf->b_data, !=, NULL);
2758 hdr->b_l1hdr.b_buf = buf;
2759 hdr->b_l1hdr.b_bufcnt += 1;
2762 * If the user wants the data from the hdr, we need to either copy or
2763 * decompress the data.
2766 return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
2772 static char *arc_onloan_tag = "onloan";
2775 arc_loaned_bytes_update(int64_t delta)
2777 atomic_add_64(&arc_loaned_bytes, delta);
2779 /* assert that it did not wrap around */
2780 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2784 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2785 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2786 * buffers must be returned to the arc before they can be used by the DMU or
2790 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2792 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2793 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2795 arc_loaned_bytes_update(size);
2801 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2802 enum zio_compress compression_type)
2804 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2805 psize, lsize, compression_type);
2807 arc_loaned_bytes_update(psize);
2814 * Return a loaned arc buffer to the arc.
2817 arc_return_buf(arc_buf_t *buf, void *tag)
2819 arc_buf_hdr_t *hdr = buf->b_hdr;
2821 ASSERT3P(buf->b_data, !=, NULL);
2822 ASSERT(HDR_HAS_L1HDR(hdr));
2823 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2824 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2826 arc_loaned_bytes_update(-arc_buf_size(buf));
2829 /* Detach an arc_buf from a dbuf (tag) */
2831 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2833 arc_buf_hdr_t *hdr = buf->b_hdr;
2835 ASSERT3P(buf->b_data, !=, NULL);
2836 ASSERT(HDR_HAS_L1HDR(hdr));
2837 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2838 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2840 arc_loaned_bytes_update(arc_buf_size(buf));
2844 l2arc_free_data_on_write(void *data, size_t size, arc_buf_contents_t type)
2846 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2848 df->l2df_data = data;
2849 df->l2df_size = size;
2850 df->l2df_type = type;
2851 mutex_enter(&l2arc_free_on_write_mtx);
2852 list_insert_head(l2arc_free_on_write, df);
2853 mutex_exit(&l2arc_free_on_write_mtx);
2857 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2859 arc_state_t *state = hdr->b_l1hdr.b_state;
2860 arc_buf_contents_t type = arc_buf_type(hdr);
2861 uint64_t size = arc_hdr_size(hdr);
2863 /* protected by hash lock, if in the hash table */
2864 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2865 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2866 ASSERT(state != arc_anon && state != arc_l2c_only);
2868 (void) refcount_remove_many(&state->arcs_esize[type],
2871 (void) refcount_remove_many(&state->arcs_size, size, hdr);
2872 if (type == ARC_BUFC_METADATA) {
2873 arc_space_return(size, ARC_SPACE_META);
2875 ASSERT(type == ARC_BUFC_DATA);
2876 arc_space_return(size, ARC_SPACE_DATA);
2879 l2arc_free_data_on_write(hdr->b_l1hdr.b_pdata, size, type);
2883 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2884 * data buffer, we transfer the refcount ownership to the hdr and update
2885 * the appropriate kstats.
2888 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2890 arc_state_t *state = hdr->b_l1hdr.b_state;
2892 ASSERT(arc_can_share(hdr, buf));
2893 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2894 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2897 * Start sharing the data buffer. We transfer the
2898 * refcount ownership to the hdr since it always owns
2899 * the refcount whenever an arc_buf_t is shared.
2901 refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2902 hdr->b_l1hdr.b_pdata = buf->b_data;
2903 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2904 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2907 * Since we've transferred ownership to the hdr we need
2908 * to increment its compressed and uncompressed kstats and
2909 * decrement the overhead size.
2911 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2912 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2913 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2917 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2919 arc_state_t *state = hdr->b_l1hdr.b_state;
2921 ASSERT(arc_buf_is_shared(buf));
2922 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2923 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2926 * We are no longer sharing this buffer so we need
2927 * to transfer its ownership to the rightful owner.
2929 refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2930 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2931 hdr->b_l1hdr.b_pdata = NULL;
2932 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2935 * Since the buffer is no longer shared between
2936 * the arc buf and the hdr, count it as overhead.
2938 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2939 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2940 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2944 * Remove an arc_buf_t from the hdr's buf list and return the last
2945 * arc_buf_t on the list. If no buffers remain on the list then return
2949 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2951 ASSERT(HDR_HAS_L1HDR(hdr));
2952 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2954 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
2955 arc_buf_t *lastbuf = NULL;
2958 * Remove the buf from the hdr list and locate the last
2959 * remaining buffer on the list.
2961 while (*bufp != NULL) {
2963 *bufp = buf->b_next;
2966 * If we've removed a buffer in the middle of
2967 * the list then update the lastbuf and update
2970 if (*bufp != NULL) {
2972 bufp = &(*bufp)->b_next;
2976 ASSERT3P(lastbuf, !=, buf);
2977 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
2978 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
2979 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
2985 * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
2989 arc_buf_destroy_impl(arc_buf_t *buf)
2991 arc_buf_hdr_t *hdr = buf->b_hdr;
2994 * Free up the data associated with the buf but only if we're not
2995 * sharing this with the hdr. If we are sharing it with the hdr, the
2996 * hdr is responsible for doing the free.
2998 if (buf->b_data != NULL) {
3000 * We're about to change the hdr's b_flags. We must either
3001 * hold the hash_lock or be undiscoverable.
3003 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3005 arc_cksum_verify(buf);
3007 arc_buf_unwatch(buf);
3010 if (arc_buf_is_shared(buf)) {
3011 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3013 uint64_t size = arc_buf_size(buf);
3014 arc_free_data_buf(hdr, buf->b_data, size, buf);
3015 ARCSTAT_INCR(arcstat_overhead_size, -size);
3019 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3020 hdr->b_l1hdr.b_bufcnt -= 1;
3023 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3025 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3027 * If the current arc_buf_t is sharing its data buffer with the
3028 * hdr, then reassign the hdr's b_pdata to share it with the new
3029 * buffer at the end of the list. The shared buffer is always
3030 * the last one on the hdr's buffer list.
3032 * There is an equivalent case for compressed bufs, but since
3033 * they aren't guaranteed to be the last buf in the list and
3034 * that is an exceedingly rare case, we just allow that space be
3035 * wasted temporarily.
3037 if (lastbuf != NULL) {
3038 /* Only one buf can be shared at once */
3039 VERIFY(!arc_buf_is_shared(lastbuf));
3040 /* hdr is uncompressed so can't have compressed buf */
3041 VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3043 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
3044 arc_hdr_free_pdata(hdr);
3047 * We must setup a new shared block between the
3048 * last buffer and the hdr. The data would have
3049 * been allocated by the arc buf so we need to transfer
3050 * ownership to the hdr since it's now being shared.
3052 arc_share_buf(hdr, lastbuf);
3054 } else if (HDR_SHARED_DATA(hdr)) {
3056 * Uncompressed shared buffers are always at the end
3057 * of the list. Compressed buffers don't have the
3058 * same requirements. This makes it hard to
3059 * simply assert that the lastbuf is shared so
3060 * we rely on the hdr's compression flags to determine
3061 * if we have a compressed, shared buffer.
3063 ASSERT3P(lastbuf, !=, NULL);
3064 ASSERT(arc_buf_is_shared(lastbuf) ||
3065 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
3069 * Free the checksum if we're removing the last uncompressed buf from
3072 if (!arc_hdr_has_uncompressed_buf(hdr)) {
3073 arc_cksum_free(hdr);
3076 /* clean up the buf */
3078 kmem_cache_free(buf_cache, buf);
3082 arc_hdr_alloc_pdata(arc_buf_hdr_t *hdr)
3084 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3085 ASSERT(HDR_HAS_L1HDR(hdr));
3086 ASSERT(!HDR_SHARED_DATA(hdr));
3088 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3089 hdr->b_l1hdr.b_pdata = arc_get_data_buf(hdr, arc_hdr_size(hdr), hdr);
3090 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3091 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
3093 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3094 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3098 arc_hdr_free_pdata(arc_buf_hdr_t *hdr)
3100 ASSERT(HDR_HAS_L1HDR(hdr));
3101 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
3104 * If the hdr is currently being written to the l2arc then
3105 * we defer freeing the data by adding it to the l2arc_free_on_write
3106 * list. The l2arc will free the data once it's finished
3107 * writing it to the l2arc device.
3109 if (HDR_L2_WRITING(hdr)) {
3110 arc_hdr_free_on_write(hdr);
3111 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3113 arc_free_data_buf(hdr, hdr->b_l1hdr.b_pdata,
3114 arc_hdr_size(hdr), hdr);
3116 hdr->b_l1hdr.b_pdata = NULL;
3117 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3119 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3120 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3123 static arc_buf_hdr_t *
3124 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3125 enum zio_compress compression_type, arc_buf_contents_t type)
3129 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3131 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3132 ASSERT(HDR_EMPTY(hdr));
3133 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3134 ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3135 HDR_SET_PSIZE(hdr, psize);
3136 HDR_SET_LSIZE(hdr, lsize);
3140 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3141 arc_hdr_set_compress(hdr, compression_type);
3143 hdr->b_l1hdr.b_state = arc_anon;
3144 hdr->b_l1hdr.b_arc_access = 0;
3145 hdr->b_l1hdr.b_bufcnt = 0;
3146 hdr->b_l1hdr.b_buf = NULL;
3149 * Allocate the hdr's buffer. This will contain either
3150 * the compressed or uncompressed data depending on the block
3151 * it references and compressed arc enablement.
3153 arc_hdr_alloc_pdata(hdr);
3154 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3160 * Transition between the two allocation states for the arc_buf_hdr struct.
3161 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3162 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3163 * version is used when a cache buffer is only in the L2ARC in order to reduce
3166 static arc_buf_hdr_t *
3167 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3169 ASSERT(HDR_HAS_L2HDR(hdr));
3171 arc_buf_hdr_t *nhdr;
3172 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3174 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3175 (old == hdr_l2only_cache && new == hdr_full_cache));
3177 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3179 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3180 buf_hash_remove(hdr);
3182 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3184 if (new == hdr_full_cache) {
3185 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3187 * arc_access and arc_change_state need to be aware that a
3188 * header has just come out of L2ARC, so we set its state to
3189 * l2c_only even though it's about to change.
3191 nhdr->b_l1hdr.b_state = arc_l2c_only;
3193 /* Verify previous threads set to NULL before freeing */
3194 ASSERT3P(nhdr->b_l1hdr.b_pdata, ==, NULL);
3196 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3197 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3198 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3201 * If we've reached here, We must have been called from
3202 * arc_evict_hdr(), as such we should have already been
3203 * removed from any ghost list we were previously on
3204 * (which protects us from racing with arc_evict_state),
3205 * thus no locking is needed during this check.
3207 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3210 * A buffer must not be moved into the arc_l2c_only
3211 * state if it's not finished being written out to the
3212 * l2arc device. Otherwise, the b_l1hdr.b_pdata field
3213 * might try to be accessed, even though it was removed.
3215 VERIFY(!HDR_L2_WRITING(hdr));
3216 VERIFY3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3219 if (hdr->b_l1hdr.b_thawed != NULL) {
3220 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3221 hdr->b_l1hdr.b_thawed = NULL;
3225 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3228 * The header has been reallocated so we need to re-insert it into any
3231 (void) buf_hash_insert(nhdr, NULL);
3233 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3235 mutex_enter(&dev->l2ad_mtx);
3238 * We must place the realloc'ed header back into the list at
3239 * the same spot. Otherwise, if it's placed earlier in the list,
3240 * l2arc_write_buffers() could find it during the function's
3241 * write phase, and try to write it out to the l2arc.
3243 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3244 list_remove(&dev->l2ad_buflist, hdr);
3246 mutex_exit(&dev->l2ad_mtx);
3249 * Since we're using the pointer address as the tag when
3250 * incrementing and decrementing the l2ad_alloc refcount, we
3251 * must remove the old pointer (that we're about to destroy) and
3252 * add the new pointer to the refcount. Otherwise we'd remove
3253 * the wrong pointer address when calling arc_hdr_destroy() later.
3256 (void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3257 (void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3259 buf_discard_identity(hdr);
3260 kmem_cache_free(old, hdr);
3266 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3267 * The buf is returned thawed since we expect the consumer to modify it.
3270 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3272 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3273 ZIO_COMPRESS_OFF, type);
3274 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3276 arc_buf_t *buf = NULL;
3277 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3284 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3285 * for bufs containing metadata.
3288 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3289 enum zio_compress compression_type)
3291 ASSERT3U(lsize, >, 0);
3292 ASSERT3U(lsize, >=, psize);
3293 ASSERT(compression_type > ZIO_COMPRESS_OFF);
3294 ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3296 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3297 compression_type, ARC_BUFC_DATA);
3298 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3300 arc_buf_t *buf = NULL;
3301 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3303 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3309 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3311 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3312 l2arc_dev_t *dev = l2hdr->b_dev;
3313 uint64_t asize = arc_hdr_size(hdr);
3315 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3316 ASSERT(HDR_HAS_L2HDR(hdr));
3318 list_remove(&dev->l2ad_buflist, hdr);
3320 ARCSTAT_INCR(arcstat_l2_asize, -asize);
3321 ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
3323 vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3325 (void) refcount_remove_many(&dev->l2ad_alloc, asize, hdr);
3326 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3330 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3332 if (HDR_HAS_L1HDR(hdr)) {
3333 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3334 hdr->b_l1hdr.b_bufcnt > 0);
3335 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3336 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3338 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3339 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3341 if (!HDR_EMPTY(hdr))
3342 buf_discard_identity(hdr);
3344 if (HDR_HAS_L2HDR(hdr)) {
3345 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3346 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3349 mutex_enter(&dev->l2ad_mtx);
3352 * Even though we checked this conditional above, we
3353 * need to check this again now that we have the
3354 * l2ad_mtx. This is because we could be racing with
3355 * another thread calling l2arc_evict() which might have
3356 * destroyed this header's L2 portion as we were waiting
3357 * to acquire the l2ad_mtx. If that happens, we don't
3358 * want to re-destroy the header's L2 portion.
3360 if (HDR_HAS_L2HDR(hdr)) {
3362 arc_hdr_l2hdr_destroy(hdr);
3366 mutex_exit(&dev->l2ad_mtx);
3369 if (HDR_HAS_L1HDR(hdr)) {
3370 arc_cksum_free(hdr);
3372 while (hdr->b_l1hdr.b_buf != NULL)
3373 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3376 if (hdr->b_l1hdr.b_thawed != NULL) {
3377 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3378 hdr->b_l1hdr.b_thawed = NULL;
3382 if (hdr->b_l1hdr.b_pdata != NULL) {
3383 arc_hdr_free_pdata(hdr);
3387 ASSERT3P(hdr->b_hash_next, ==, NULL);
3388 if (HDR_HAS_L1HDR(hdr)) {
3389 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3390 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3391 kmem_cache_free(hdr_full_cache, hdr);
3393 kmem_cache_free(hdr_l2only_cache, hdr);
3398 arc_buf_destroy(arc_buf_t *buf, void* tag)
3400 arc_buf_hdr_t *hdr = buf->b_hdr;
3401 kmutex_t *hash_lock = HDR_LOCK(hdr);
3403 if (hdr->b_l1hdr.b_state == arc_anon) {
3404 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3405 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3406 VERIFY0(remove_reference(hdr, NULL, tag));
3407 arc_hdr_destroy(hdr);
3411 mutex_enter(hash_lock);
3412 ASSERT3P(hdr, ==, buf->b_hdr);
3413 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3414 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3415 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3416 ASSERT3P(buf->b_data, !=, NULL);
3418 (void) remove_reference(hdr, hash_lock, tag);
3419 arc_buf_destroy_impl(buf);
3420 mutex_exit(hash_lock);
3424 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3425 * state of the header is dependent on its state prior to entering this
3426 * function. The following transitions are possible:
3428 * - arc_mru -> arc_mru_ghost
3429 * - arc_mfu -> arc_mfu_ghost
3430 * - arc_mru_ghost -> arc_l2c_only
3431 * - arc_mru_ghost -> deleted
3432 * - arc_mfu_ghost -> arc_l2c_only
3433 * - arc_mfu_ghost -> deleted
3436 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3438 arc_state_t *evicted_state, *state;
3439 int64_t bytes_evicted = 0;
3441 ASSERT(MUTEX_HELD(hash_lock));
3442 ASSERT(HDR_HAS_L1HDR(hdr));
3444 state = hdr->b_l1hdr.b_state;
3445 if (GHOST_STATE(state)) {
3446 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3447 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3450 * l2arc_write_buffers() relies on a header's L1 portion
3451 * (i.e. its b_pdata field) during its write phase.
3452 * Thus, we cannot push a header onto the arc_l2c_only
3453 * state (removing it's L1 piece) until the header is
3454 * done being written to the l2arc.
3456 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3457 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3458 return (bytes_evicted);
3461 ARCSTAT_BUMP(arcstat_deleted);
3462 bytes_evicted += HDR_GET_LSIZE(hdr);
3464 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3466 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3467 if (HDR_HAS_L2HDR(hdr)) {
3469 * This buffer is cached on the 2nd Level ARC;
3470 * don't destroy the header.
3472 arc_change_state(arc_l2c_only, hdr, hash_lock);
3474 * dropping from L1+L2 cached to L2-only,
3475 * realloc to remove the L1 header.
3477 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3480 arc_change_state(arc_anon, hdr, hash_lock);
3481 arc_hdr_destroy(hdr);
3483 return (bytes_evicted);
3486 ASSERT(state == arc_mru || state == arc_mfu);
3487 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3489 /* prefetch buffers have a minimum lifespan */
3490 if (HDR_IO_IN_PROGRESS(hdr) ||
3491 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3492 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3493 arc_min_prefetch_lifespan)) {
3494 ARCSTAT_BUMP(arcstat_evict_skip);
3495 return (bytes_evicted);
3498 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3499 while (hdr->b_l1hdr.b_buf) {
3500 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3501 if (!mutex_tryenter(&buf->b_evict_lock)) {
3502 ARCSTAT_BUMP(arcstat_mutex_miss);
3505 if (buf->b_data != NULL)
3506 bytes_evicted += HDR_GET_LSIZE(hdr);
3507 mutex_exit(&buf->b_evict_lock);
3508 arc_buf_destroy_impl(buf);
3511 if (HDR_HAS_L2HDR(hdr)) {
3512 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3514 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3515 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3516 HDR_GET_LSIZE(hdr));
3518 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3519 HDR_GET_LSIZE(hdr));
3523 if (hdr->b_l1hdr.b_bufcnt == 0) {
3524 arc_cksum_free(hdr);
3526 bytes_evicted += arc_hdr_size(hdr);
3529 * If this hdr is being evicted and has a compressed
3530 * buffer then we discard it here before we change states.
3531 * This ensures that the accounting is updated correctly
3532 * in arc_free_data_buf().
3534 arc_hdr_free_pdata(hdr);
3536 arc_change_state(evicted_state, hdr, hash_lock);
3537 ASSERT(HDR_IN_HASH_TABLE(hdr));
3538 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3539 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3542 return (bytes_evicted);
3546 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3547 uint64_t spa, int64_t bytes)
3549 multilist_sublist_t *mls;
3550 uint64_t bytes_evicted = 0;
3552 kmutex_t *hash_lock;
3553 int evict_count = 0;
3555 ASSERT3P(marker, !=, NULL);
3556 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3558 mls = multilist_sublist_lock(ml, idx);
3560 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3561 hdr = multilist_sublist_prev(mls, marker)) {
3562 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3563 (evict_count >= zfs_arc_evict_batch_limit))
3567 * To keep our iteration location, move the marker
3568 * forward. Since we're not holding hdr's hash lock, we
3569 * must be very careful and not remove 'hdr' from the
3570 * sublist. Otherwise, other consumers might mistake the
3571 * 'hdr' as not being on a sublist when they call the
3572 * multilist_link_active() function (they all rely on
3573 * the hash lock protecting concurrent insertions and
3574 * removals). multilist_sublist_move_forward() was
3575 * specifically implemented to ensure this is the case
3576 * (only 'marker' will be removed and re-inserted).
3578 multilist_sublist_move_forward(mls, marker);
3581 * The only case where the b_spa field should ever be
3582 * zero, is the marker headers inserted by
3583 * arc_evict_state(). It's possible for multiple threads
3584 * to be calling arc_evict_state() concurrently (e.g.
3585 * dsl_pool_close() and zio_inject_fault()), so we must
3586 * skip any markers we see from these other threads.
3588 if (hdr->b_spa == 0)
3591 /* we're only interested in evicting buffers of a certain spa */
3592 if (spa != 0 && hdr->b_spa != spa) {
3593 ARCSTAT_BUMP(arcstat_evict_skip);
3597 hash_lock = HDR_LOCK(hdr);
3600 * We aren't calling this function from any code path
3601 * that would already be holding a hash lock, so we're
3602 * asserting on this assumption to be defensive in case
3603 * this ever changes. Without this check, it would be
3604 * possible to incorrectly increment arcstat_mutex_miss
3605 * below (e.g. if the code changed such that we called
3606 * this function with a hash lock held).
3608 ASSERT(!MUTEX_HELD(hash_lock));
3610 if (mutex_tryenter(hash_lock)) {
3611 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3612 mutex_exit(hash_lock);
3614 bytes_evicted += evicted;
3617 * If evicted is zero, arc_evict_hdr() must have
3618 * decided to skip this header, don't increment
3619 * evict_count in this case.
3625 * If arc_size isn't overflowing, signal any
3626 * threads that might happen to be waiting.
3628 * For each header evicted, we wake up a single
3629 * thread. If we used cv_broadcast, we could
3630 * wake up "too many" threads causing arc_size
3631 * to significantly overflow arc_c; since
3632 * arc_get_data_buf() doesn't check for overflow
3633 * when it's woken up (it doesn't because it's
3634 * possible for the ARC to be overflowing while
3635 * full of un-evictable buffers, and the
3636 * function should proceed in this case).
3638 * If threads are left sleeping, due to not
3639 * using cv_broadcast, they will be woken up
3640 * just before arc_reclaim_thread() sleeps.
3642 mutex_enter(&arc_reclaim_lock);
3643 if (!arc_is_overflowing())
3644 cv_signal(&arc_reclaim_waiters_cv);
3645 mutex_exit(&arc_reclaim_lock);
3647 ARCSTAT_BUMP(arcstat_mutex_miss);
3651 multilist_sublist_unlock(mls);
3653 return (bytes_evicted);
3657 * Evict buffers from the given arc state, until we've removed the
3658 * specified number of bytes. Move the removed buffers to the
3659 * appropriate evict state.
3661 * This function makes a "best effort". It skips over any buffers
3662 * it can't get a hash_lock on, and so, may not catch all candidates.
3663 * It may also return without evicting as much space as requested.
3665 * If bytes is specified using the special value ARC_EVICT_ALL, this
3666 * will evict all available (i.e. unlocked and evictable) buffers from
3667 * the given arc state; which is used by arc_flush().
3670 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3671 arc_buf_contents_t type)
3673 uint64_t total_evicted = 0;
3674 multilist_t *ml = state->arcs_list[type];
3676 arc_buf_hdr_t **markers;
3678 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3680 num_sublists = multilist_get_num_sublists(ml);
3683 * If we've tried to evict from each sublist, made some
3684 * progress, but still have not hit the target number of bytes
3685 * to evict, we want to keep trying. The markers allow us to
3686 * pick up where we left off for each individual sublist, rather
3687 * than starting from the tail each time.
3689 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3690 for (int i = 0; i < num_sublists; i++) {
3691 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3694 * A b_spa of 0 is used to indicate that this header is
3695 * a marker. This fact is used in arc_adjust_type() and
3696 * arc_evict_state_impl().
3698 markers[i]->b_spa = 0;
3700 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3701 multilist_sublist_insert_tail(mls, markers[i]);
3702 multilist_sublist_unlock(mls);
3706 * While we haven't hit our target number of bytes to evict, or
3707 * we're evicting all available buffers.
3709 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3711 * Start eviction using a randomly selected sublist,
3712 * this is to try and evenly balance eviction across all
3713 * sublists. Always starting at the same sublist
3714 * (e.g. index 0) would cause evictions to favor certain
3715 * sublists over others.
3717 int sublist_idx = multilist_get_random_index(ml);
3718 uint64_t scan_evicted = 0;
3720 for (int i = 0; i < num_sublists; i++) {
3721 uint64_t bytes_remaining;
3722 uint64_t bytes_evicted;
3724 if (bytes == ARC_EVICT_ALL)
3725 bytes_remaining = ARC_EVICT_ALL;
3726 else if (total_evicted < bytes)
3727 bytes_remaining = bytes - total_evicted;
3731 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3732 markers[sublist_idx], spa, bytes_remaining);
3734 scan_evicted += bytes_evicted;
3735 total_evicted += bytes_evicted;
3737 /* we've reached the end, wrap to the beginning */
3738 if (++sublist_idx >= num_sublists)
3743 * If we didn't evict anything during this scan, we have
3744 * no reason to believe we'll evict more during another
3745 * scan, so break the loop.
3747 if (scan_evicted == 0) {
3748 /* This isn't possible, let's make that obvious */
3749 ASSERT3S(bytes, !=, 0);
3752 * When bytes is ARC_EVICT_ALL, the only way to
3753 * break the loop is when scan_evicted is zero.
3754 * In that case, we actually have evicted enough,
3755 * so we don't want to increment the kstat.
3757 if (bytes != ARC_EVICT_ALL) {
3758 ASSERT3S(total_evicted, <, bytes);
3759 ARCSTAT_BUMP(arcstat_evict_not_enough);
3766 for (int i = 0; i < num_sublists; i++) {
3767 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3768 multilist_sublist_remove(mls, markers[i]);
3769 multilist_sublist_unlock(mls);
3771 kmem_cache_free(hdr_full_cache, markers[i]);
3773 kmem_free(markers, sizeof (*markers) * num_sublists);
3775 return (total_evicted);
3779 * Flush all "evictable" data of the given type from the arc state
3780 * specified. This will not evict any "active" buffers (i.e. referenced).
3782 * When 'retry' is set to B_FALSE, the function will make a single pass
3783 * over the state and evict any buffers that it can. Since it doesn't
3784 * continually retry the eviction, it might end up leaving some buffers
3785 * in the ARC due to lock misses.
3787 * When 'retry' is set to B_TRUE, the function will continually retry the
3788 * eviction until *all* evictable buffers have been removed from the
3789 * state. As a result, if concurrent insertions into the state are
3790 * allowed (e.g. if the ARC isn't shutting down), this function might
3791 * wind up in an infinite loop, continually trying to evict buffers.
3794 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3797 uint64_t evicted = 0;
3799 while (refcount_count(&state->arcs_esize[type]) != 0) {
3800 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3810 * Evict the specified number of bytes from the state specified,
3811 * restricting eviction to the spa and type given. This function
3812 * prevents us from trying to evict more from a state's list than
3813 * is "evictable", and to skip evicting altogether when passed a
3814 * negative value for "bytes". In contrast, arc_evict_state() will
3815 * evict everything it can, when passed a negative value for "bytes".
3818 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3819 arc_buf_contents_t type)
3823 if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3824 delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3825 return (arc_evict_state(state, spa, delta, type));
3832 * Evict metadata buffers from the cache, such that arc_meta_used is
3833 * capped by the arc_meta_limit tunable.
3836 arc_adjust_meta(void)
3838 uint64_t total_evicted = 0;
3842 * If we're over the meta limit, we want to evict enough
3843 * metadata to get back under the meta limit. We don't want to
3844 * evict so much that we drop the MRU below arc_p, though. If
3845 * we're over the meta limit more than we're over arc_p, we
3846 * evict some from the MRU here, and some from the MFU below.
3848 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3849 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3850 refcount_count(&arc_mru->arcs_size) - arc_p));
3852 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3855 * Similar to the above, we want to evict enough bytes to get us
3856 * below the meta limit, but not so much as to drop us below the
3857 * space allotted to the MFU (which is defined as arc_c - arc_p).
3859 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3860 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3862 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3864 return (total_evicted);
3868 * Return the type of the oldest buffer in the given arc state
3870 * This function will select a random sublist of type ARC_BUFC_DATA and
3871 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3872 * is compared, and the type which contains the "older" buffer will be
3875 static arc_buf_contents_t
3876 arc_adjust_type(arc_state_t *state)
3878 multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
3879 multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3880 int data_idx = multilist_get_random_index(data_ml);
3881 int meta_idx = multilist_get_random_index(meta_ml);
3882 multilist_sublist_t *data_mls;
3883 multilist_sublist_t *meta_mls;
3884 arc_buf_contents_t type;
3885 arc_buf_hdr_t *data_hdr;
3886 arc_buf_hdr_t *meta_hdr;
3889 * We keep the sublist lock until we're finished, to prevent
3890 * the headers from being destroyed via arc_evict_state().
3892 data_mls = multilist_sublist_lock(data_ml, data_idx);
3893 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3896 * These two loops are to ensure we skip any markers that
3897 * might be at the tail of the lists due to arc_evict_state().
3900 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3901 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3902 if (data_hdr->b_spa != 0)
3906 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3907 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3908 if (meta_hdr->b_spa != 0)
3912 if (data_hdr == NULL && meta_hdr == NULL) {
3913 type = ARC_BUFC_DATA;
3914 } else if (data_hdr == NULL) {
3915 ASSERT3P(meta_hdr, !=, NULL);
3916 type = ARC_BUFC_METADATA;
3917 } else if (meta_hdr == NULL) {
3918 ASSERT3P(data_hdr, !=, NULL);
3919 type = ARC_BUFC_DATA;
3921 ASSERT3P(data_hdr, !=, NULL);
3922 ASSERT3P(meta_hdr, !=, NULL);
3924 /* The headers can't be on the sublist without an L1 header */
3925 ASSERT(HDR_HAS_L1HDR(data_hdr));
3926 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3928 if (data_hdr->b_l1hdr.b_arc_access <
3929 meta_hdr->b_l1hdr.b_arc_access) {
3930 type = ARC_BUFC_DATA;
3932 type = ARC_BUFC_METADATA;
3936 multilist_sublist_unlock(meta_mls);
3937 multilist_sublist_unlock(data_mls);
3943 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3948 uint64_t total_evicted = 0;
3953 * If we're over arc_meta_limit, we want to correct that before
3954 * potentially evicting data buffers below.
3956 total_evicted += arc_adjust_meta();
3961 * If we're over the target cache size, we want to evict enough
3962 * from the list to get back to our target size. We don't want
3963 * to evict too much from the MRU, such that it drops below
3964 * arc_p. So, if we're over our target cache size more than
3965 * the MRU is over arc_p, we'll evict enough to get back to
3966 * arc_p here, and then evict more from the MFU below.
3968 target = MIN((int64_t)(arc_size - arc_c),
3969 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3970 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3973 * If we're below arc_meta_min, always prefer to evict data.
3974 * Otherwise, try to satisfy the requested number of bytes to
3975 * evict from the type which contains older buffers; in an
3976 * effort to keep newer buffers in the cache regardless of their
3977 * type. If we cannot satisfy the number of bytes from this
3978 * type, spill over into the next type.
3980 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3981 arc_meta_used > arc_meta_min) {
3982 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3983 total_evicted += bytes;
3986 * If we couldn't evict our target number of bytes from
3987 * metadata, we try to get the rest from data.
3992 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3994 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3995 total_evicted += bytes;
3998 * If we couldn't evict our target number of bytes from
3999 * data, we try to get the rest from metadata.
4004 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4010 * Now that we've tried to evict enough from the MRU to get its
4011 * size back to arc_p, if we're still above the target cache
4012 * size, we evict the rest from the MFU.
4014 target = arc_size - arc_c;
4016 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4017 arc_meta_used > arc_meta_min) {
4018 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4019 total_evicted += bytes;
4022 * If we couldn't evict our target number of bytes from
4023 * metadata, we try to get the rest from data.
4028 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4030 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4031 total_evicted += bytes;
4034 * If we couldn't evict our target number of bytes from
4035 * data, we try to get the rest from data.
4040 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4044 * Adjust ghost lists
4046 * In addition to the above, the ARC also defines target values
4047 * for the ghost lists. The sum of the mru list and mru ghost
4048 * list should never exceed the target size of the cache, and
4049 * the sum of the mru list, mfu list, mru ghost list, and mfu
4050 * ghost list should never exceed twice the target size of the
4051 * cache. The following logic enforces these limits on the ghost
4052 * caches, and evicts from them as needed.
4054 target = refcount_count(&arc_mru->arcs_size) +
4055 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4057 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4058 total_evicted += bytes;
4063 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4066 * We assume the sum of the mru list and mfu list is less than
4067 * or equal to arc_c (we enforced this above), which means we
4068 * can use the simpler of the two equations below:
4070 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4071 * mru ghost + mfu ghost <= arc_c
4073 target = refcount_count(&arc_mru_ghost->arcs_size) +
4074 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4076 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4077 total_evicted += bytes;
4082 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4084 return (total_evicted);
4088 arc_flush(spa_t *spa, boolean_t retry)
4093 * If retry is B_TRUE, a spa must not be specified since we have
4094 * no good way to determine if all of a spa's buffers have been
4095 * evicted from an arc state.
4097 ASSERT(!retry || spa == 0);
4100 guid = spa_load_guid(spa);
4102 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4103 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4105 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4106 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4108 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4109 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4111 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4112 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4116 arc_shrink(int64_t to_free)
4118 if (arc_c > arc_c_min) {
4119 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4120 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4121 if (arc_c > arc_c_min + to_free)
4122 atomic_add_64(&arc_c, -to_free);
4126 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4127 if (arc_c > arc_size)
4128 arc_c = MAX(arc_size, arc_c_min);
4130 arc_p = (arc_c >> 1);
4132 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4135 ASSERT(arc_c >= arc_c_min);
4136 ASSERT((int64_t)arc_p >= 0);
4139 if (arc_size > arc_c) {
4140 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
4142 (void) arc_adjust();
4146 static long needfree = 0;
4148 typedef enum free_memory_reason_t {
4153 FMR_PAGES_PP_MAXIMUM,
4157 } free_memory_reason_t;
4159 int64_t last_free_memory;
4160 free_memory_reason_t last_free_reason;
4163 * Additional reserve of pages for pp_reserve.
4165 int64_t arc_pages_pp_reserve = 64;
4168 * Additional reserve of pages for swapfs.
4170 int64_t arc_swapfs_reserve = 64;
4173 * Return the amount of memory that can be consumed before reclaim will be
4174 * needed. Positive if there is sufficient free memory, negative indicates
4175 * the amount of memory that needs to be freed up.
4178 arc_available_memory(void)
4180 int64_t lowest = INT64_MAX;
4182 free_memory_reason_t r = FMR_UNKNOWN;
4186 n = PAGESIZE * (-needfree);
4194 * Cooperate with pagedaemon when it's time for it to scan
4195 * and reclaim some pages.
4197 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4205 * check that we're out of range of the pageout scanner. It starts to
4206 * schedule paging if freemem is less than lotsfree and needfree.
4207 * lotsfree is the high-water mark for pageout, and needfree is the
4208 * number of needed free pages. We add extra pages here to make sure
4209 * the scanner doesn't start up while we're freeing memory.
4211 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4218 * check to make sure that swapfs has enough space so that anon
4219 * reservations can still succeed. anon_resvmem() checks that the
4220 * availrmem is greater than swapfs_minfree, and the number of reserved
4221 * swap pages. We also add a bit of extra here just to prevent
4222 * circumstances from getting really dire.
4224 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4225 desfree - arc_swapfs_reserve);
4228 r = FMR_SWAPFS_MINFREE;
4233 * Check that we have enough availrmem that memory locking (e.g., via
4234 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
4235 * stores the number of pages that cannot be locked; when availrmem
4236 * drops below pages_pp_maximum, page locking mechanisms such as
4237 * page_pp_lock() will fail.)
4239 n = PAGESIZE * (availrmem - pages_pp_maximum -
4240 arc_pages_pp_reserve);
4243 r = FMR_PAGES_PP_MAXIMUM;
4246 #endif /* illumos */
4247 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4249 * If we're on an i386 platform, it's possible that we'll exhaust the
4250 * kernel heap space before we ever run out of available physical
4251 * memory. Most checks of the size of the heap_area compare against
4252 * tune.t_minarmem, which is the minimum available real memory that we
4253 * can have in the system. However, this is generally fixed at 25 pages
4254 * which is so low that it's useless. In this comparison, we seek to
4255 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4256 * heap is allocated. (Or, in the calculation, if less than 1/4th is
4259 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
4260 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
4265 #define zio_arena NULL
4267 #define zio_arena heap_arena
4271 * If zio data pages are being allocated out of a separate heap segment,
4272 * then enforce that the size of available vmem for this arena remains
4273 * above about 1/16th free.
4275 * Note: The 1/16th arena free requirement was put in place
4276 * to aggressively evict memory from the arc in order to avoid
4277 * memory fragmentation issues.
4279 if (zio_arena != NULL) {
4280 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4281 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
4289 * Above limits know nothing about real level of KVA fragmentation.
4290 * Start aggressive reclamation if too little sequential KVA left.
4293 n = (vmem_size(heap_arena, VMEM_MAXFREE) < SPA_MAXBLOCKSIZE) ?
4294 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
4303 /* Every 100 calls, free a small amount */
4304 if (spa_get_random(100) == 0)
4306 #endif /* _KERNEL */
4308 last_free_memory = lowest;
4309 last_free_reason = r;
4310 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4316 * Determine if the system is under memory pressure and is asking
4317 * to reclaim memory. A return value of B_TRUE indicates that the system
4318 * is under memory pressure and that the arc should adjust accordingly.
4321 arc_reclaim_needed(void)
4323 return (arc_available_memory() < 0);
4326 extern kmem_cache_t *zio_buf_cache[];
4327 extern kmem_cache_t *zio_data_buf_cache[];
4328 extern kmem_cache_t *range_seg_cache;
4330 static __noinline void
4331 arc_kmem_reap_now(void)
4334 kmem_cache_t *prev_cache = NULL;
4335 kmem_cache_t *prev_data_cache = NULL;
4337 DTRACE_PROBE(arc__kmem_reap_start);
4339 if (arc_meta_used >= arc_meta_limit) {
4341 * We are exceeding our meta-data cache limit.
4342 * Purge some DNLC entries to release holds on meta-data.
4344 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4348 * Reclaim unused memory from all kmem caches.
4354 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4355 if (zio_buf_cache[i] != prev_cache) {
4356 prev_cache = zio_buf_cache[i];
4357 kmem_cache_reap_now(zio_buf_cache[i]);
4359 if (zio_data_buf_cache[i] != prev_data_cache) {
4360 prev_data_cache = zio_data_buf_cache[i];
4361 kmem_cache_reap_now(zio_data_buf_cache[i]);
4364 kmem_cache_reap_now(buf_cache);
4365 kmem_cache_reap_now(hdr_full_cache);
4366 kmem_cache_reap_now(hdr_l2only_cache);
4367 kmem_cache_reap_now(range_seg_cache);
4370 if (zio_arena != NULL) {
4372 * Ask the vmem arena to reclaim unused memory from its
4375 vmem_qcache_reap(zio_arena);
4378 DTRACE_PROBE(arc__kmem_reap_end);
4382 * Threads can block in arc_get_data_buf() waiting for this thread to evict
4383 * enough data and signal them to proceed. When this happens, the threads in
4384 * arc_get_data_buf() are sleeping while holding the hash lock for their
4385 * particular arc header. Thus, we must be careful to never sleep on a
4386 * hash lock in this thread. This is to prevent the following deadlock:
4388 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
4389 * waiting for the reclaim thread to signal it.
4391 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4392 * fails, and goes to sleep forever.
4394 * This possible deadlock is avoided by always acquiring a hash lock
4395 * using mutex_tryenter() from arc_reclaim_thread().
4398 arc_reclaim_thread(void *dummy __unused)
4400 hrtime_t growtime = 0;
4403 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4405 mutex_enter(&arc_reclaim_lock);
4406 while (!arc_reclaim_thread_exit) {
4407 uint64_t evicted = 0;
4410 * This is necessary in order for the mdb ::arc dcmd to
4411 * show up to date information. Since the ::arc command
4412 * does not call the kstat's update function, without
4413 * this call, the command may show stale stats for the
4414 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4415 * with this change, the data might be up to 1 second
4416 * out of date; but that should suffice. The arc_state_t
4417 * structures can be queried directly if more accurate
4418 * information is needed.
4420 if (arc_ksp != NULL)
4421 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4423 mutex_exit(&arc_reclaim_lock);
4426 * We call arc_adjust() before (possibly) calling
4427 * arc_kmem_reap_now(), so that we can wake up
4428 * arc_get_data_buf() sooner.
4430 evicted = arc_adjust();
4432 int64_t free_memory = arc_available_memory();
4433 if (free_memory < 0) {
4435 arc_no_grow = B_TRUE;
4439 * Wait at least zfs_grow_retry (default 60) seconds
4440 * before considering growing.
4442 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4444 arc_kmem_reap_now();
4447 * If we are still low on memory, shrink the ARC
4448 * so that we have arc_shrink_min free space.
4450 free_memory = arc_available_memory();
4453 (arc_c >> arc_shrink_shift) - free_memory;
4456 to_free = MAX(to_free, ptob(needfree));
4458 arc_shrink(to_free);
4460 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4461 arc_no_grow = B_TRUE;
4462 } else if (gethrtime() >= growtime) {
4463 arc_no_grow = B_FALSE;
4466 mutex_enter(&arc_reclaim_lock);
4469 * If evicted is zero, we couldn't evict anything via
4470 * arc_adjust(). This could be due to hash lock
4471 * collisions, but more likely due to the majority of
4472 * arc buffers being unevictable. Therefore, even if
4473 * arc_size is above arc_c, another pass is unlikely to
4474 * be helpful and could potentially cause us to enter an
4477 if (arc_size <= arc_c || evicted == 0) {
4482 * We're either no longer overflowing, or we
4483 * can't evict anything more, so we should wake
4484 * up any threads before we go to sleep.
4486 cv_broadcast(&arc_reclaim_waiters_cv);
4489 * Block until signaled, or after one second (we
4490 * might need to perform arc_kmem_reap_now()
4491 * even if we aren't being signalled)
4493 CALLB_CPR_SAFE_BEGIN(&cpr);
4494 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4495 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4496 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4500 arc_reclaim_thread_exit = B_FALSE;
4501 cv_broadcast(&arc_reclaim_thread_cv);
4502 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
4506 static u_int arc_dnlc_evicts_arg;
4507 extern struct vfsops zfs_vfsops;
4510 arc_dnlc_evicts_thread(void *dummy __unused)
4515 CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
4517 mutex_enter(&arc_dnlc_evicts_lock);
4518 while (!arc_dnlc_evicts_thread_exit) {
4519 CALLB_CPR_SAFE_BEGIN(&cpr);
4520 (void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
4521 CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
4522 if (arc_dnlc_evicts_arg != 0) {
4523 percent = arc_dnlc_evicts_arg;
4524 mutex_exit(&arc_dnlc_evicts_lock);
4526 vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
4528 mutex_enter(&arc_dnlc_evicts_lock);
4530 * Clear our token only after vnlru_free()
4531 * pass is done, to avoid false queueing of
4534 arc_dnlc_evicts_arg = 0;
4537 arc_dnlc_evicts_thread_exit = FALSE;
4538 cv_broadcast(&arc_dnlc_evicts_cv);
4539 CALLB_CPR_EXIT(&cpr);
4544 dnlc_reduce_cache(void *arg)
4548 percent = (u_int)(uintptr_t)arg;
4549 mutex_enter(&arc_dnlc_evicts_lock);
4550 if (arc_dnlc_evicts_arg == 0) {
4551 arc_dnlc_evicts_arg = percent;
4552 cv_broadcast(&arc_dnlc_evicts_cv);
4554 mutex_exit(&arc_dnlc_evicts_lock);
4558 * Adapt arc info given the number of bytes we are trying to add and
4559 * the state that we are comming from. This function is only called
4560 * when we are adding new content to the cache.
4563 arc_adapt(int bytes, arc_state_t *state)
4566 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4567 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4568 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4570 if (state == arc_l2c_only)
4575 * Adapt the target size of the MRU list:
4576 * - if we just hit in the MRU ghost list, then increase
4577 * the target size of the MRU list.
4578 * - if we just hit in the MFU ghost list, then increase
4579 * the target size of the MFU list by decreasing the
4580 * target size of the MRU list.
4582 if (state == arc_mru_ghost) {
4583 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4584 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4586 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4587 } else if (state == arc_mfu_ghost) {
4590 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4591 mult = MIN(mult, 10);
4593 delta = MIN(bytes * mult, arc_p);
4594 arc_p = MAX(arc_p_min, arc_p - delta);
4596 ASSERT((int64_t)arc_p >= 0);
4598 if (arc_reclaim_needed()) {
4599 cv_signal(&arc_reclaim_thread_cv);
4606 if (arc_c >= arc_c_max)
4610 * If we're within (2 * maxblocksize) bytes of the target
4611 * cache size, increment the target cache size
4613 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
4614 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
4615 atomic_add_64(&arc_c, (int64_t)bytes);
4616 if (arc_c > arc_c_max)
4618 else if (state == arc_anon)
4619 atomic_add_64(&arc_p, (int64_t)bytes);
4623 ASSERT((int64_t)arc_p >= 0);
4627 * Check if arc_size has grown past our upper threshold, determined by
4628 * zfs_arc_overflow_shift.
4631 arc_is_overflowing(void)
4633 /* Always allow at least one block of overflow */
4634 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4635 arc_c >> zfs_arc_overflow_shift);
4637 return (arc_size >= arc_c + overflow);
4641 * Allocate a block and return it to the caller. If we are hitting the
4642 * hard limit for the cache size, we must sleep, waiting for the eviction
4643 * thread to catch up. If we're past the target size but below the hard
4644 * limit, we'll only signal the reclaim thread and continue on.
4647 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4650 arc_state_t *state = hdr->b_l1hdr.b_state;
4651 arc_buf_contents_t type = arc_buf_type(hdr);
4653 arc_adapt(size, state);
4656 * If arc_size is currently overflowing, and has grown past our
4657 * upper limit, we must be adding data faster than the evict
4658 * thread can evict. Thus, to ensure we don't compound the
4659 * problem by adding more data and forcing arc_size to grow even
4660 * further past it's target size, we halt and wait for the
4661 * eviction thread to catch up.
4663 * It's also possible that the reclaim thread is unable to evict
4664 * enough buffers to get arc_size below the overflow limit (e.g.
4665 * due to buffers being un-evictable, or hash lock collisions).
4666 * In this case, we want to proceed regardless if we're
4667 * overflowing; thus we don't use a while loop here.
4669 if (arc_is_overflowing()) {
4670 mutex_enter(&arc_reclaim_lock);
4673 * Now that we've acquired the lock, we may no longer be
4674 * over the overflow limit, lets check.
4676 * We're ignoring the case of spurious wake ups. If that
4677 * were to happen, it'd let this thread consume an ARC
4678 * buffer before it should have (i.e. before we're under
4679 * the overflow limit and were signalled by the reclaim
4680 * thread). As long as that is a rare occurrence, it
4681 * shouldn't cause any harm.
4683 if (arc_is_overflowing()) {
4684 cv_signal(&arc_reclaim_thread_cv);
4685 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4688 mutex_exit(&arc_reclaim_lock);
4691 VERIFY3U(hdr->b_type, ==, type);
4692 if (type == ARC_BUFC_METADATA) {
4693 datap = zio_buf_alloc(size);
4694 arc_space_consume(size, ARC_SPACE_META);
4696 ASSERT(type == ARC_BUFC_DATA);
4697 datap = zio_data_buf_alloc(size);
4698 arc_space_consume(size, ARC_SPACE_DATA);
4702 * Update the state size. Note that ghost states have a
4703 * "ghost size" and so don't need to be updated.
4705 if (!GHOST_STATE(state)) {
4707 (void) refcount_add_many(&state->arcs_size, size, tag);
4710 * If this is reached via arc_read, the link is
4711 * protected by the hash lock. If reached via
4712 * arc_buf_alloc, the header should not be accessed by
4713 * any other thread. And, if reached via arc_read_done,
4714 * the hash lock will protect it if it's found in the
4715 * hash table; otherwise no other thread should be
4716 * trying to [add|remove]_reference it.
4718 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4719 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4720 (void) refcount_add_many(&state->arcs_esize[type],
4725 * If we are growing the cache, and we are adding anonymous
4726 * data, and we have outgrown arc_p, update arc_p
4728 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
4729 (refcount_count(&arc_anon->arcs_size) +
4730 refcount_count(&arc_mru->arcs_size) > arc_p))
4731 arc_p = MIN(arc_c, arc_p + size);
4733 ARCSTAT_BUMP(arcstat_allocated);
4738 * Free the arc data buffer.
4741 arc_free_data_buf(arc_buf_hdr_t *hdr, void *data, uint64_t size, void *tag)
4743 arc_state_t *state = hdr->b_l1hdr.b_state;
4744 arc_buf_contents_t type = arc_buf_type(hdr);
4746 /* protected by hash lock, if in the hash table */
4747 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4748 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4749 ASSERT(state != arc_anon && state != arc_l2c_only);
4751 (void) refcount_remove_many(&state->arcs_esize[type],
4754 (void) refcount_remove_many(&state->arcs_size, size, tag);
4756 VERIFY3U(hdr->b_type, ==, type);
4757 if (type == ARC_BUFC_METADATA) {
4758 zio_buf_free(data, size);
4759 arc_space_return(size, ARC_SPACE_META);
4761 ASSERT(type == ARC_BUFC_DATA);
4762 zio_data_buf_free(data, size);
4763 arc_space_return(size, ARC_SPACE_DATA);
4768 * This routine is called whenever a buffer is accessed.
4769 * NOTE: the hash lock is dropped in this function.
4772 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4776 ASSERT(MUTEX_HELD(hash_lock));
4777 ASSERT(HDR_HAS_L1HDR(hdr));
4779 if (hdr->b_l1hdr.b_state == arc_anon) {
4781 * This buffer is not in the cache, and does not
4782 * appear in our "ghost" list. Add the new buffer
4786 ASSERT0(hdr->b_l1hdr.b_arc_access);
4787 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4788 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4789 arc_change_state(arc_mru, hdr, hash_lock);
4791 } else if (hdr->b_l1hdr.b_state == arc_mru) {
4792 now = ddi_get_lbolt();
4795 * If this buffer is here because of a prefetch, then either:
4796 * - clear the flag if this is a "referencing" read
4797 * (any subsequent access will bump this into the MFU state).
4799 * - move the buffer to the head of the list if this is
4800 * another prefetch (to make it less likely to be evicted).
4802 if (HDR_PREFETCH(hdr)) {
4803 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4804 /* link protected by hash lock */
4805 ASSERT(multilist_link_active(
4806 &hdr->b_l1hdr.b_arc_node));
4808 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4809 ARCSTAT_BUMP(arcstat_mru_hits);
4811 hdr->b_l1hdr.b_arc_access = now;
4816 * This buffer has been "accessed" only once so far,
4817 * but it is still in the cache. Move it to the MFU
4820 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4822 * More than 125ms have passed since we
4823 * instantiated this buffer. Move it to the
4824 * most frequently used state.
4826 hdr->b_l1hdr.b_arc_access = now;
4827 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4828 arc_change_state(arc_mfu, hdr, hash_lock);
4830 ARCSTAT_BUMP(arcstat_mru_hits);
4831 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4832 arc_state_t *new_state;
4834 * This buffer has been "accessed" recently, but
4835 * was evicted from the cache. Move it to the
4839 if (HDR_PREFETCH(hdr)) {
4840 new_state = arc_mru;
4841 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4842 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4843 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4845 new_state = arc_mfu;
4846 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4849 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4850 arc_change_state(new_state, hdr, hash_lock);
4852 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4853 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
4855 * This buffer has been accessed more than once and is
4856 * still in the cache. Keep it in the MFU state.
4858 * NOTE: an add_reference() that occurred when we did
4859 * the arc_read() will have kicked this off the list.
4860 * If it was a prefetch, we will explicitly move it to
4861 * the head of the list now.
4863 if ((HDR_PREFETCH(hdr)) != 0) {
4864 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4865 /* link protected by hash_lock */
4866 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4868 ARCSTAT_BUMP(arcstat_mfu_hits);
4869 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4870 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4871 arc_state_t *new_state = arc_mfu;
4873 * This buffer has been accessed more than once but has
4874 * been evicted from the cache. Move it back to the
4878 if (HDR_PREFETCH(hdr)) {
4880 * This is a prefetch access...
4881 * move this block back to the MRU state.
4883 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4884 new_state = arc_mru;
4887 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4888 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4889 arc_change_state(new_state, hdr, hash_lock);
4891 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4892 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4894 * This buffer is on the 2nd Level ARC.
4897 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4898 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4899 arc_change_state(arc_mfu, hdr, hash_lock);
4901 ASSERT(!"invalid arc state");
4905 /* a generic arc_done_func_t which you can use */
4908 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4910 if (zio == NULL || zio->io_error == 0)
4911 bcopy(buf->b_data, arg, arc_buf_size(buf));
4912 arc_buf_destroy(buf, arg);
4915 /* a generic arc_done_func_t */
4917 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4919 arc_buf_t **bufp = arg;
4920 if (zio && zio->io_error) {
4921 arc_buf_destroy(buf, arg);
4925 ASSERT(buf->b_data);
4930 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4932 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4933 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4934 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4936 if (HDR_COMPRESSION_ENABLED(hdr)) {
4937 ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4938 BP_GET_COMPRESS(bp));
4940 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4941 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4946 arc_read_done(zio_t *zio)
4948 arc_buf_hdr_t *hdr = zio->io_private;
4949 kmutex_t *hash_lock = NULL;
4950 arc_callback_t *callback_list;
4951 arc_callback_t *acb;
4952 boolean_t freeable = B_FALSE;
4953 boolean_t no_zio_error = (zio->io_error == 0);
4956 * The hdr was inserted into hash-table and removed from lists
4957 * prior to starting I/O. We should find this header, since
4958 * it's in the hash table, and it should be legit since it's
4959 * not possible to evict it during the I/O. The only possible
4960 * reason for it not to be found is if we were freed during the
4963 if (HDR_IN_HASH_TABLE(hdr)) {
4964 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4965 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4966 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4967 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4968 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4970 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4973 ASSERT((found == hdr &&
4974 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4975 (found == hdr && HDR_L2_READING(hdr)));
4976 ASSERT3P(hash_lock, !=, NULL);
4980 /* byteswap if necessary */
4981 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4982 if (BP_GET_LEVEL(zio->io_bp) > 0) {
4983 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4985 hdr->b_l1hdr.b_byteswap =
4986 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4989 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4993 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
4994 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4995 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4997 callback_list = hdr->b_l1hdr.b_acb;
4998 ASSERT3P(callback_list, !=, NULL);
5000 if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5002 * Only call arc_access on anonymous buffers. This is because
5003 * if we've issued an I/O for an evicted buffer, we've already
5004 * called arc_access (to prevent any simultaneous readers from
5005 * getting confused).
5007 arc_access(hdr, hash_lock);
5011 * If a read request has a callback (i.e. acb_done is not NULL), then we
5012 * make a buf containing the data according to the parameters which were
5013 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5014 * aren't needlessly decompressing the data multiple times.
5016 int callback_cnt = 0;
5017 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5021 /* This is a demand read since prefetches don't use callbacks */
5024 int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5025 acb->acb_compressed, no_zio_error, &acb->acb_buf);
5027 zio->io_error = error;
5030 hdr->b_l1hdr.b_acb = NULL;
5031 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5032 if (callback_cnt == 0) {
5033 ASSERT(HDR_PREFETCH(hdr));
5034 ASSERT0(hdr->b_l1hdr.b_bufcnt);
5035 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5038 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5039 callback_list != NULL);
5042 arc_hdr_verify(hdr, zio->io_bp);
5044 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5045 if (hdr->b_l1hdr.b_state != arc_anon)
5046 arc_change_state(arc_anon, hdr, hash_lock);
5047 if (HDR_IN_HASH_TABLE(hdr))
5048 buf_hash_remove(hdr);
5049 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5053 * Broadcast before we drop the hash_lock to avoid the possibility
5054 * that the hdr (and hence the cv) might be freed before we get to
5055 * the cv_broadcast().
5057 cv_broadcast(&hdr->b_l1hdr.b_cv);
5059 if (hash_lock != NULL) {
5060 mutex_exit(hash_lock);
5063 * This block was freed while we waited for the read to
5064 * complete. It has been removed from the hash table and
5065 * moved to the anonymous state (so that it won't show up
5068 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5069 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5072 /* execute each callback and free its structure */
5073 while ((acb = callback_list) != NULL) {
5075 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
5077 if (acb->acb_zio_dummy != NULL) {
5078 acb->acb_zio_dummy->io_error = zio->io_error;
5079 zio_nowait(acb->acb_zio_dummy);
5082 callback_list = acb->acb_next;
5083 kmem_free(acb, sizeof (arc_callback_t));
5087 arc_hdr_destroy(hdr);
5091 * "Read" the block at the specified DVA (in bp) via the
5092 * cache. If the block is found in the cache, invoke the provided
5093 * callback immediately and return. Note that the `zio' parameter
5094 * in the callback will be NULL in this case, since no IO was
5095 * required. If the block is not in the cache pass the read request
5096 * on to the spa with a substitute callback function, so that the
5097 * requested block will be added to the cache.
5099 * If a read request arrives for a block that has a read in-progress,
5100 * either wait for the in-progress read to complete (and return the
5101 * results); or, if this is a read with a "done" func, add a record
5102 * to the read to invoke the "done" func when the read completes,
5103 * and return; or just return.
5105 * arc_read_done() will invoke all the requested "done" functions
5106 * for readers of this block.
5109 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
5110 void *private, zio_priority_t priority, int zio_flags,
5111 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5113 arc_buf_hdr_t *hdr = NULL;
5114 kmutex_t *hash_lock = NULL;
5116 uint64_t guid = spa_load_guid(spa);
5117 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5119 ASSERT(!BP_IS_EMBEDDED(bp) ||
5120 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5123 if (!BP_IS_EMBEDDED(bp)) {
5125 * Embedded BP's have no DVA and require no I/O to "read".
5126 * Create an anonymous arc buf to back it.
5128 hdr = buf_hash_find(guid, bp, &hash_lock);
5131 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pdata != NULL) {
5132 arc_buf_t *buf = NULL;
5133 *arc_flags |= ARC_FLAG_CACHED;
5135 if (HDR_IO_IN_PROGRESS(hdr)) {
5137 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5138 priority == ZIO_PRIORITY_SYNC_READ) {
5140 * This sync read must wait for an
5141 * in-progress async read (e.g. a predictive
5142 * prefetch). Async reads are queued
5143 * separately at the vdev_queue layer, so
5144 * this is a form of priority inversion.
5145 * Ideally, we would "inherit" the demand
5146 * i/o's priority by moving the i/o from
5147 * the async queue to the synchronous queue,
5148 * but there is currently no mechanism to do
5149 * so. Track this so that we can evaluate
5150 * the magnitude of this potential performance
5153 * Note that if the prefetch i/o is already
5154 * active (has been issued to the device),
5155 * the prefetch improved performance, because
5156 * we issued it sooner than we would have
5157 * without the prefetch.
5159 DTRACE_PROBE1(arc__sync__wait__for__async,
5160 arc_buf_hdr_t *, hdr);
5161 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
5163 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5164 arc_hdr_clear_flags(hdr,
5165 ARC_FLAG_PREDICTIVE_PREFETCH);
5168 if (*arc_flags & ARC_FLAG_WAIT) {
5169 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5170 mutex_exit(hash_lock);
5173 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5176 arc_callback_t *acb = NULL;
5178 acb = kmem_zalloc(sizeof (arc_callback_t),
5180 acb->acb_done = done;
5181 acb->acb_private = private;
5182 acb->acb_compressed = compressed_read;
5184 acb->acb_zio_dummy = zio_null(pio,
5185 spa, NULL, NULL, NULL, zio_flags);
5187 ASSERT3P(acb->acb_done, !=, NULL);
5188 acb->acb_next = hdr->b_l1hdr.b_acb;
5189 hdr->b_l1hdr.b_acb = acb;
5190 mutex_exit(hash_lock);
5193 mutex_exit(hash_lock);
5197 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5198 hdr->b_l1hdr.b_state == arc_mfu);
5201 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5203 * This is a demand read which does not have to
5204 * wait for i/o because we did a predictive
5205 * prefetch i/o for it, which has completed.
5208 arc__demand__hit__predictive__prefetch,
5209 arc_buf_hdr_t *, hdr);
5211 arcstat_demand_hit_predictive_prefetch);
5212 arc_hdr_clear_flags(hdr,
5213 ARC_FLAG_PREDICTIVE_PREFETCH);
5215 ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5217 /* Get a buf with the desired data in it. */
5218 VERIFY0(arc_buf_alloc_impl(hdr, private,
5219 compressed_read, B_TRUE, &buf));
5220 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
5221 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5222 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5224 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5225 arc_access(hdr, hash_lock);
5226 if (*arc_flags & ARC_FLAG_L2CACHE)
5227 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5228 mutex_exit(hash_lock);
5229 ARCSTAT_BUMP(arcstat_hits);
5230 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5231 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5232 data, metadata, hits);
5235 done(NULL, buf, private);
5237 uint64_t lsize = BP_GET_LSIZE(bp);
5238 uint64_t psize = BP_GET_PSIZE(bp);
5239 arc_callback_t *acb;
5242 boolean_t devw = B_FALSE;
5246 /* this block is not in the cache */
5247 arc_buf_hdr_t *exists = NULL;
5248 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5249 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5250 BP_GET_COMPRESS(bp), type);
5252 if (!BP_IS_EMBEDDED(bp)) {
5253 hdr->b_dva = *BP_IDENTITY(bp);
5254 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5255 exists = buf_hash_insert(hdr, &hash_lock);
5257 if (exists != NULL) {
5258 /* somebody beat us to the hash insert */
5259 mutex_exit(hash_lock);
5260 buf_discard_identity(hdr);
5261 arc_hdr_destroy(hdr);
5262 goto top; /* restart the IO request */
5266 * This block is in the ghost cache. If it was L2-only
5267 * (and thus didn't have an L1 hdr), we realloc the
5268 * header to add an L1 hdr.
5270 if (!HDR_HAS_L1HDR(hdr)) {
5271 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5274 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5275 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5276 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5277 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5278 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5279 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5282 * This is a delicate dance that we play here.
5283 * This hdr is in the ghost list so we access it
5284 * to move it out of the ghost list before we
5285 * initiate the read. If it's a prefetch then
5286 * it won't have a callback so we'll remove the
5287 * reference that arc_buf_alloc_impl() created. We
5288 * do this after we've called arc_access() to
5289 * avoid hitting an assert in remove_reference().
5291 arc_access(hdr, hash_lock);
5292 arc_hdr_alloc_pdata(hdr);
5294 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5295 size = arc_hdr_size(hdr);
5298 * If compression is enabled on the hdr, then will do
5299 * RAW I/O and will store the compressed data in the hdr's
5300 * data block. Otherwise, the hdr's data block will contain
5301 * the uncompressed data.
5303 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5304 zio_flags |= ZIO_FLAG_RAW;
5307 if (*arc_flags & ARC_FLAG_PREFETCH)
5308 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5309 if (*arc_flags & ARC_FLAG_L2CACHE)
5310 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5311 if (BP_GET_LEVEL(bp) > 0)
5312 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5313 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5314 arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5315 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5317 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5318 acb->acb_done = done;
5319 acb->acb_private = private;
5320 acb->acb_compressed = compressed_read;
5322 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5323 hdr->b_l1hdr.b_acb = acb;
5324 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5326 if (HDR_HAS_L2HDR(hdr) &&
5327 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5328 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5329 addr = hdr->b_l2hdr.b_daddr;
5331 * Lock out device removal.
5333 if (vdev_is_dead(vd) ||
5334 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5338 if (priority == ZIO_PRIORITY_ASYNC_READ)
5339 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5341 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5343 if (hash_lock != NULL)
5344 mutex_exit(hash_lock);
5347 * At this point, we have a level 1 cache miss. Try again in
5348 * L2ARC if possible.
5350 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5352 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5353 uint64_t, lsize, zbookmark_phys_t *, zb);
5354 ARCSTAT_BUMP(arcstat_misses);
5355 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5356 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5357 data, metadata, misses);
5362 racct_add_force(curproc, RACCT_READBPS, size);
5363 racct_add_force(curproc, RACCT_READIOPS, 1);
5364 PROC_UNLOCK(curproc);
5367 curthread->td_ru.ru_inblock++;
5370 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5372 * Read from the L2ARC if the following are true:
5373 * 1. The L2ARC vdev was previously cached.
5374 * 2. This buffer still has L2ARC metadata.
5375 * 3. This buffer isn't currently writing to the L2ARC.
5376 * 4. The L2ARC entry wasn't evicted, which may
5377 * also have invalidated the vdev.
5378 * 5. This isn't prefetch and l2arc_noprefetch is set.
5380 if (HDR_HAS_L2HDR(hdr) &&
5381 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5382 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5383 l2arc_read_callback_t *cb;
5386 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5387 ARCSTAT_BUMP(arcstat_l2_hits);
5389 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5391 cb->l2rcb_hdr = hdr;
5394 cb->l2rcb_flags = zio_flags;
5395 uint64_t asize = vdev_psize_to_asize(vd, size);
5396 if (asize != size) {
5397 b_data = zio_data_buf_alloc(asize);
5398 cb->l2rcb_data = b_data;
5400 b_data = hdr->b_l1hdr.b_pdata;
5403 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5404 addr + asize < vd->vdev_psize -
5405 VDEV_LABEL_END_SIZE);
5408 * l2arc read. The SCL_L2ARC lock will be
5409 * released by l2arc_read_done().
5410 * Issue a null zio if the underlying buffer
5411 * was squashed to zero size by compression.
5413 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5414 ZIO_COMPRESS_EMPTY);
5415 rzio = zio_read_phys(pio, vd, addr,
5418 l2arc_read_done, cb, priority,
5419 zio_flags | ZIO_FLAG_DONT_CACHE |
5421 ZIO_FLAG_DONT_PROPAGATE |
5422 ZIO_FLAG_DONT_RETRY, B_FALSE);
5423 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5425 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5427 if (*arc_flags & ARC_FLAG_NOWAIT) {
5432 ASSERT(*arc_flags & ARC_FLAG_WAIT);
5433 if (zio_wait(rzio) == 0)
5436 /* l2arc read error; goto zio_read() */
5438 DTRACE_PROBE1(l2arc__miss,
5439 arc_buf_hdr_t *, hdr);
5440 ARCSTAT_BUMP(arcstat_l2_misses);
5441 if (HDR_L2_WRITING(hdr))
5442 ARCSTAT_BUMP(arcstat_l2_rw_clash);
5443 spa_config_exit(spa, SCL_L2ARC, vd);
5447 spa_config_exit(spa, SCL_L2ARC, vd);
5448 if (l2arc_ndev != 0) {
5449 DTRACE_PROBE1(l2arc__miss,
5450 arc_buf_hdr_t *, hdr);
5451 ARCSTAT_BUMP(arcstat_l2_misses);
5455 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pdata, size,
5456 arc_read_done, hdr, priority, zio_flags, zb);
5458 if (*arc_flags & ARC_FLAG_WAIT)
5459 return (zio_wait(rzio));
5461 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5468 * Notify the arc that a block was freed, and thus will never be used again.
5471 arc_freed(spa_t *spa, const blkptr_t *bp)
5474 kmutex_t *hash_lock;
5475 uint64_t guid = spa_load_guid(spa);
5477 ASSERT(!BP_IS_EMBEDDED(bp));
5479 hdr = buf_hash_find(guid, bp, &hash_lock);
5484 * We might be trying to free a block that is still doing I/O
5485 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5486 * dmu_sync-ed block). If this block is being prefetched, then it
5487 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5488 * until the I/O completes. A block may also have a reference if it is
5489 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5490 * have written the new block to its final resting place on disk but
5491 * without the dedup flag set. This would have left the hdr in the MRU
5492 * state and discoverable. When the txg finally syncs it detects that
5493 * the block was overridden in open context and issues an override I/O.
5494 * Since this is a dedup block, the override I/O will determine if the
5495 * block is already in the DDT. If so, then it will replace the io_bp
5496 * with the bp from the DDT and allow the I/O to finish. When the I/O
5497 * reaches the done callback, dbuf_write_override_done, it will
5498 * check to see if the io_bp and io_bp_override are identical.
5499 * If they are not, then it indicates that the bp was replaced with
5500 * the bp in the DDT and the override bp is freed. This allows
5501 * us to arrive here with a reference on a block that is being
5502 * freed. So if we have an I/O in progress, or a reference to
5503 * this hdr, then we don't destroy the hdr.
5505 if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5506 refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5507 arc_change_state(arc_anon, hdr, hash_lock);
5508 arc_hdr_destroy(hdr);
5509 mutex_exit(hash_lock);
5511 mutex_exit(hash_lock);
5517 * Release this buffer from the cache, making it an anonymous buffer. This
5518 * must be done after a read and prior to modifying the buffer contents.
5519 * If the buffer has more than one reference, we must make
5520 * a new hdr for the buffer.
5523 arc_release(arc_buf_t *buf, void *tag)
5525 arc_buf_hdr_t *hdr = buf->b_hdr;
5528 * It would be nice to assert that if it's DMU metadata (level >
5529 * 0 || it's the dnode file), then it must be syncing context.
5530 * But we don't know that information at this level.
5533 mutex_enter(&buf->b_evict_lock);
5535 ASSERT(HDR_HAS_L1HDR(hdr));
5538 * We don't grab the hash lock prior to this check, because if
5539 * the buffer's header is in the arc_anon state, it won't be
5540 * linked into the hash table.
5542 if (hdr->b_l1hdr.b_state == arc_anon) {
5543 mutex_exit(&buf->b_evict_lock);
5544 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5545 ASSERT(!HDR_IN_HASH_TABLE(hdr));
5546 ASSERT(!HDR_HAS_L2HDR(hdr));
5547 ASSERT(HDR_EMPTY(hdr));
5548 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5549 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5550 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5552 hdr->b_l1hdr.b_arc_access = 0;
5555 * If the buf is being overridden then it may already
5556 * have a hdr that is not empty.
5558 buf_discard_identity(hdr);
5564 kmutex_t *hash_lock = HDR_LOCK(hdr);
5565 mutex_enter(hash_lock);
5568 * This assignment is only valid as long as the hash_lock is
5569 * held, we must be careful not to reference state or the
5570 * b_state field after dropping the lock.
5572 arc_state_t *state = hdr->b_l1hdr.b_state;
5573 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5574 ASSERT3P(state, !=, arc_anon);
5576 /* this buffer is not on any list */
5577 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
5579 if (HDR_HAS_L2HDR(hdr)) {
5580 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5583 * We have to recheck this conditional again now that
5584 * we're holding the l2ad_mtx to prevent a race with
5585 * another thread which might be concurrently calling
5586 * l2arc_evict(). In that case, l2arc_evict() might have
5587 * destroyed the header's L2 portion as we were waiting
5588 * to acquire the l2ad_mtx.
5590 if (HDR_HAS_L2HDR(hdr)) {
5592 arc_hdr_l2hdr_destroy(hdr);
5595 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5599 * Do we have more than one buf?
5601 if (hdr->b_l1hdr.b_bufcnt > 1) {
5602 arc_buf_hdr_t *nhdr;
5603 uint64_t spa = hdr->b_spa;
5604 uint64_t psize = HDR_GET_PSIZE(hdr);
5605 uint64_t lsize = HDR_GET_LSIZE(hdr);
5606 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5607 arc_buf_contents_t type = arc_buf_type(hdr);
5608 VERIFY3U(hdr->b_type, ==, type);
5610 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5611 (void) remove_reference(hdr, hash_lock, tag);
5613 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5614 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5615 ASSERT(ARC_BUF_LAST(buf));
5619 * Pull the data off of this hdr and attach it to
5620 * a new anonymous hdr. Also find the last buffer
5621 * in the hdr's buffer list.
5623 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5624 ASSERT3P(lastbuf, !=, NULL);
5627 * If the current arc_buf_t and the hdr are sharing their data
5628 * buffer, then we must stop sharing that block.
5630 if (arc_buf_is_shared(buf)) {
5631 VERIFY(!arc_buf_is_shared(lastbuf));
5634 * First, sever the block sharing relationship between
5635 * buf and the arc_buf_hdr_t.
5637 arc_unshare_buf(hdr, buf);
5640 * Now we need to recreate the hdr's b_pdata. Since we
5641 * have lastbuf handy, we try to share with it, but if
5642 * we can't then we allocate a new b_pdata and copy the
5643 * data from buf into it.
5645 if (arc_can_share(hdr, lastbuf)) {
5646 arc_share_buf(hdr, lastbuf);
5648 arc_hdr_alloc_pdata(hdr);
5649 bcopy(buf->b_data, hdr->b_l1hdr.b_pdata, psize);
5651 VERIFY3P(lastbuf->b_data, !=, NULL);
5652 } else if (HDR_SHARED_DATA(hdr)) {
5654 * Uncompressed shared buffers are always at the end
5655 * of the list. Compressed buffers don't have the
5656 * same requirements. This makes it hard to
5657 * simply assert that the lastbuf is shared so
5658 * we rely on the hdr's compression flags to determine
5659 * if we have a compressed, shared buffer.
5661 ASSERT(arc_buf_is_shared(lastbuf) ||
5662 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
5663 ASSERT(!ARC_BUF_SHARED(buf));
5665 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5666 ASSERT3P(state, !=, arc_l2c_only);
5668 (void) refcount_remove_many(&state->arcs_size,
5669 arc_buf_size(buf), buf);
5671 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5672 ASSERT3P(state, !=, arc_l2c_only);
5673 (void) refcount_remove_many(&state->arcs_esize[type],
5674 arc_buf_size(buf), buf);
5677 hdr->b_l1hdr.b_bufcnt -= 1;
5678 arc_cksum_verify(buf);
5680 arc_buf_unwatch(buf);
5683 mutex_exit(hash_lock);
5686 * Allocate a new hdr. The new hdr will contain a b_pdata
5687 * buffer which will be freed in arc_write().
5689 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5690 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5691 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5692 ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5693 VERIFY3U(nhdr->b_type, ==, type);
5694 ASSERT(!HDR_SHARED_DATA(nhdr));
5696 nhdr->b_l1hdr.b_buf = buf;
5697 nhdr->b_l1hdr.b_bufcnt = 1;
5698 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5701 mutex_exit(&buf->b_evict_lock);
5702 (void) refcount_add_many(&arc_anon->arcs_size,
5703 arc_buf_size(buf), buf);
5705 mutex_exit(&buf->b_evict_lock);
5706 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5707 /* protected by hash lock, or hdr is on arc_anon */
5708 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5709 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5710 arc_change_state(arc_anon, hdr, hash_lock);
5711 hdr->b_l1hdr.b_arc_access = 0;
5712 mutex_exit(hash_lock);
5714 buf_discard_identity(hdr);
5720 arc_released(arc_buf_t *buf)
5724 mutex_enter(&buf->b_evict_lock);
5725 released = (buf->b_data != NULL &&
5726 buf->b_hdr->b_l1hdr.b_state == arc_anon);
5727 mutex_exit(&buf->b_evict_lock);
5733 arc_referenced(arc_buf_t *buf)
5737 mutex_enter(&buf->b_evict_lock);
5738 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5739 mutex_exit(&buf->b_evict_lock);
5740 return (referenced);
5745 arc_write_ready(zio_t *zio)
5747 arc_write_callback_t *callback = zio->io_private;
5748 arc_buf_t *buf = callback->awcb_buf;
5749 arc_buf_hdr_t *hdr = buf->b_hdr;
5750 uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5752 ASSERT(HDR_HAS_L1HDR(hdr));
5753 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5754 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5757 * If we're reexecuting this zio because the pool suspended, then
5758 * cleanup any state that was previously set the first time the
5759 * callback was invoked.
5761 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5762 arc_cksum_free(hdr);
5764 arc_buf_unwatch(buf);
5766 if (hdr->b_l1hdr.b_pdata != NULL) {
5767 if (arc_buf_is_shared(buf)) {
5768 arc_unshare_buf(hdr, buf);
5770 arc_hdr_free_pdata(hdr);
5774 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5775 ASSERT(!HDR_SHARED_DATA(hdr));
5776 ASSERT(!arc_buf_is_shared(buf));
5778 callback->awcb_ready(zio, buf, callback->awcb_private);
5780 if (HDR_IO_IN_PROGRESS(hdr))
5781 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5783 arc_cksum_compute(buf);
5784 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5786 enum zio_compress compress;
5787 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5788 compress = ZIO_COMPRESS_OFF;
5790 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5791 compress = BP_GET_COMPRESS(zio->io_bp);
5793 HDR_SET_PSIZE(hdr, psize);
5794 arc_hdr_set_compress(hdr, compress);
5797 * If the hdr is compressed, then copy the compressed
5798 * zio contents into arc_buf_hdr_t. Otherwise, copy the original
5799 * data buf into the hdr. Ideally, we would like to always copy the
5800 * io_data into b_pdata but the user may have disabled compressed
5801 * arc thus the on-disk block may or may not match what we maintain
5802 * in the hdr's b_pdata field.
5804 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
5805 !ARC_BUF_COMPRESSED(buf)) {
5806 ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=, ZIO_COMPRESS_OFF);
5807 ASSERT3U(psize, >, 0);
5808 arc_hdr_alloc_pdata(hdr);
5809 bcopy(zio->io_data, hdr->b_l1hdr.b_pdata, psize);
5811 ASSERT3P(buf->b_data, ==, zio->io_orig_data);
5812 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5813 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5816 * This hdr is not compressed so we're able to share
5817 * the arc_buf_t data buffer with the hdr.
5819 arc_share_buf(hdr, buf);
5820 ASSERT0(bcmp(zio->io_orig_data, hdr->b_l1hdr.b_pdata,
5821 arc_buf_size(buf)));
5823 arc_hdr_verify(hdr, zio->io_bp);
5827 arc_write_children_ready(zio_t *zio)
5829 arc_write_callback_t *callback = zio->io_private;
5830 arc_buf_t *buf = callback->awcb_buf;
5832 callback->awcb_children_ready(zio, buf, callback->awcb_private);
5836 * The SPA calls this callback for each physical write that happens on behalf
5837 * of a logical write. See the comment in dbuf_write_physdone() for details.
5840 arc_write_physdone(zio_t *zio)
5842 arc_write_callback_t *cb = zio->io_private;
5843 if (cb->awcb_physdone != NULL)
5844 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
5848 arc_write_done(zio_t *zio)
5850 arc_write_callback_t *callback = zio->io_private;
5851 arc_buf_t *buf = callback->awcb_buf;
5852 arc_buf_hdr_t *hdr = buf->b_hdr;
5854 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5856 if (zio->io_error == 0) {
5857 arc_hdr_verify(hdr, zio->io_bp);
5859 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5860 buf_discard_identity(hdr);
5862 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5863 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5866 ASSERT(HDR_EMPTY(hdr));
5870 * If the block to be written was all-zero or compressed enough to be
5871 * embedded in the BP, no write was performed so there will be no
5872 * dva/birth/checksum. The buffer must therefore remain anonymous
5875 if (!HDR_EMPTY(hdr)) {
5876 arc_buf_hdr_t *exists;
5877 kmutex_t *hash_lock;
5879 ASSERT3U(zio->io_error, ==, 0);
5881 arc_cksum_verify(buf);
5883 exists = buf_hash_insert(hdr, &hash_lock);
5884 if (exists != NULL) {
5886 * This can only happen if we overwrite for
5887 * sync-to-convergence, because we remove
5888 * buffers from the hash table when we arc_free().
5890 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5891 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5892 panic("bad overwrite, hdr=%p exists=%p",
5893 (void *)hdr, (void *)exists);
5894 ASSERT(refcount_is_zero(
5895 &exists->b_l1hdr.b_refcnt));
5896 arc_change_state(arc_anon, exists, hash_lock);
5897 mutex_exit(hash_lock);
5898 arc_hdr_destroy(exists);
5899 exists = buf_hash_insert(hdr, &hash_lock);
5900 ASSERT3P(exists, ==, NULL);
5901 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5903 ASSERT(zio->io_prop.zp_nopwrite);
5904 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5905 panic("bad nopwrite, hdr=%p exists=%p",
5906 (void *)hdr, (void *)exists);
5909 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
5910 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5911 ASSERT(BP_GET_DEDUP(zio->io_bp));
5912 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5915 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5916 /* if it's not anon, we are doing a scrub */
5917 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5918 arc_access(hdr, hash_lock);
5919 mutex_exit(hash_lock);
5921 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5924 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5925 callback->awcb_done(zio, buf, callback->awcb_private);
5927 kmem_free(callback, sizeof (arc_write_callback_t));
5931 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5932 boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
5933 arc_done_func_t *children_ready, arc_done_func_t *physdone,
5934 arc_done_func_t *done, void *private, zio_priority_t priority,
5935 int zio_flags, const zbookmark_phys_t *zb)
5937 arc_buf_hdr_t *hdr = buf->b_hdr;
5938 arc_write_callback_t *callback;
5940 zio_prop_t localprop = *zp;
5942 ASSERT3P(ready, !=, NULL);
5943 ASSERT3P(done, !=, NULL);
5944 ASSERT(!HDR_IO_ERROR(hdr));
5945 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5946 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5947 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
5949 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5950 if (ARC_BUF_COMPRESSED(buf)) {
5952 * We're writing a pre-compressed buffer. Make the
5953 * compression algorithm requested by the zio_prop_t match
5954 * the pre-compressed buffer's compression algorithm.
5956 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
5958 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
5959 zio_flags |= ZIO_FLAG_RAW;
5961 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5962 callback->awcb_ready = ready;
5963 callback->awcb_children_ready = children_ready;
5964 callback->awcb_physdone = physdone;
5965 callback->awcb_done = done;
5966 callback->awcb_private = private;
5967 callback->awcb_buf = buf;
5970 * The hdr's b_pdata is now stale, free it now. A new data block
5971 * will be allocated when the zio pipeline calls arc_write_ready().
5973 if (hdr->b_l1hdr.b_pdata != NULL) {
5975 * If the buf is currently sharing the data block with
5976 * the hdr then we need to break that relationship here.
5977 * The hdr will remain with a NULL data pointer and the
5978 * buf will take sole ownership of the block.
5980 if (arc_buf_is_shared(buf)) {
5981 arc_unshare_buf(hdr, buf);
5983 arc_hdr_free_pdata(hdr);
5985 VERIFY3P(buf->b_data, !=, NULL);
5986 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5988 ASSERT(!arc_buf_is_shared(buf));
5989 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5991 zio = zio_write(pio, spa, txg, bp, buf->b_data,
5992 HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
5993 (children_ready != NULL) ? arc_write_children_ready : NULL,
5994 arc_write_physdone, arc_write_done, callback,
5995 priority, zio_flags, zb);
6001 arc_memory_throttle(uint64_t reserve, uint64_t txg)
6004 uint64_t available_memory = ptob(freemem);
6005 static uint64_t page_load = 0;
6006 static uint64_t last_txg = 0;
6008 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
6010 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
6013 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
6016 if (txg > last_txg) {
6021 * If we are in pageout, we know that memory is already tight,
6022 * the arc is already going to be evicting, so we just want to
6023 * continue to let page writes occur as quickly as possible.
6025 if (curproc == pageproc) {
6026 if (page_load > MAX(ptob(minfree), available_memory) / 4)
6027 return (SET_ERROR(ERESTART));
6028 /* Note: reserve is inflated, so we deflate */
6029 page_load += reserve / 8;
6031 } else if (page_load > 0 && arc_reclaim_needed()) {
6032 /* memory is low, delay before restarting */
6033 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6034 return (SET_ERROR(EAGAIN));
6042 arc_tempreserve_clear(uint64_t reserve)
6044 atomic_add_64(&arc_tempreserve, -reserve);
6045 ASSERT((int64_t)arc_tempreserve >= 0);
6049 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
6054 if (reserve > arc_c/4 && !arc_no_grow) {
6055 arc_c = MIN(arc_c_max, reserve * 4);
6056 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
6058 if (reserve > arc_c)
6059 return (SET_ERROR(ENOMEM));
6062 * Don't count loaned bufs as in flight dirty data to prevent long
6063 * network delays from blocking transactions that are ready to be
6064 * assigned to a txg.
6067 /* assert that it has not wrapped around */
6068 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6070 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
6071 arc_loaned_bytes), 0);
6074 * Writes will, almost always, require additional memory allocations
6075 * in order to compress/encrypt/etc the data. We therefore need to
6076 * make sure that there is sufficient available memory for this.
6078 error = arc_memory_throttle(reserve, txg);
6083 * Throttle writes when the amount of dirty data in the cache
6084 * gets too large. We try to keep the cache less than half full
6085 * of dirty blocks so that our sync times don't grow too large.
6086 * Note: if two requests come in concurrently, we might let them
6087 * both succeed, when one of them should fail. Not a huge deal.
6090 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
6091 anon_size > arc_c / 4) {
6092 uint64_t meta_esize =
6093 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6094 uint64_t data_esize =
6095 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6096 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6097 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6098 arc_tempreserve >> 10, meta_esize >> 10,
6099 data_esize >> 10, reserve >> 10, arc_c >> 10);
6100 return (SET_ERROR(ERESTART));
6102 atomic_add_64(&arc_tempreserve, reserve);
6107 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6108 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6110 size->value.ui64 = refcount_count(&state->arcs_size);
6111 evict_data->value.ui64 =
6112 refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6113 evict_metadata->value.ui64 =
6114 refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6118 arc_kstat_update(kstat_t *ksp, int rw)
6120 arc_stats_t *as = ksp->ks_data;
6122 if (rw == KSTAT_WRITE) {
6125 arc_kstat_update_state(arc_anon,
6126 &as->arcstat_anon_size,
6127 &as->arcstat_anon_evictable_data,
6128 &as->arcstat_anon_evictable_metadata);
6129 arc_kstat_update_state(arc_mru,
6130 &as->arcstat_mru_size,
6131 &as->arcstat_mru_evictable_data,
6132 &as->arcstat_mru_evictable_metadata);
6133 arc_kstat_update_state(arc_mru_ghost,
6134 &as->arcstat_mru_ghost_size,
6135 &as->arcstat_mru_ghost_evictable_data,
6136 &as->arcstat_mru_ghost_evictable_metadata);
6137 arc_kstat_update_state(arc_mfu,
6138 &as->arcstat_mfu_size,
6139 &as->arcstat_mfu_evictable_data,
6140 &as->arcstat_mfu_evictable_metadata);
6141 arc_kstat_update_state(arc_mfu_ghost,
6142 &as->arcstat_mfu_ghost_size,
6143 &as->arcstat_mfu_ghost_evictable_data,
6144 &as->arcstat_mfu_ghost_evictable_metadata);
6151 * This function *must* return indices evenly distributed between all
6152 * sublists of the multilist. This is needed due to how the ARC eviction
6153 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6154 * distributed between all sublists and uses this assumption when
6155 * deciding which sublist to evict from and how much to evict from it.
6158 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6160 arc_buf_hdr_t *hdr = obj;
6163 * We rely on b_dva to generate evenly distributed index
6164 * numbers using buf_hash below. So, as an added precaution,
6165 * let's make sure we never add empty buffers to the arc lists.
6167 ASSERT(!HDR_EMPTY(hdr));
6170 * The assumption here, is the hash value for a given
6171 * arc_buf_hdr_t will remain constant throughout it's lifetime
6172 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6173 * Thus, we don't need to store the header's sublist index
6174 * on insertion, as this index can be recalculated on removal.
6176 * Also, the low order bits of the hash value are thought to be
6177 * distributed evenly. Otherwise, in the case that the multilist
6178 * has a power of two number of sublists, each sublists' usage
6179 * would not be evenly distributed.
6181 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6182 multilist_get_num_sublists(ml));
6186 static eventhandler_tag arc_event_lowmem = NULL;
6189 arc_lowmem(void *arg __unused, int howto __unused)
6192 mutex_enter(&arc_reclaim_lock);
6193 /* XXX: Memory deficit should be passed as argument. */
6194 needfree = btoc(arc_c >> arc_shrink_shift);
6195 DTRACE_PROBE(arc__needfree);
6196 cv_signal(&arc_reclaim_thread_cv);
6199 * It is unsafe to block here in arbitrary threads, because we can come
6200 * here from ARC itself and may hold ARC locks and thus risk a deadlock
6201 * with ARC reclaim thread.
6203 if (curproc == pageproc)
6204 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
6205 mutex_exit(&arc_reclaim_lock);
6210 arc_state_init(void)
6212 arc_anon = &ARC_anon;
6214 arc_mru_ghost = &ARC_mru_ghost;
6216 arc_mfu_ghost = &ARC_mfu_ghost;
6217 arc_l2c_only = &ARC_l2c_only;
6219 arc_mru->arcs_list[ARC_BUFC_METADATA] =
6220 multilist_create(sizeof (arc_buf_hdr_t),
6221 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6222 arc_state_multilist_index_func);
6223 arc_mru->arcs_list[ARC_BUFC_DATA] =
6224 multilist_create(sizeof (arc_buf_hdr_t),
6225 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6226 arc_state_multilist_index_func);
6227 arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6228 multilist_create(sizeof (arc_buf_hdr_t),
6229 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6230 arc_state_multilist_index_func);
6231 arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6232 multilist_create(sizeof (arc_buf_hdr_t),
6233 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6234 arc_state_multilist_index_func);
6235 arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6236 multilist_create(sizeof (arc_buf_hdr_t),
6237 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6238 arc_state_multilist_index_func);
6239 arc_mfu->arcs_list[ARC_BUFC_DATA] =
6240 multilist_create(sizeof (arc_buf_hdr_t),
6241 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6242 arc_state_multilist_index_func);
6243 arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6244 multilist_create(sizeof (arc_buf_hdr_t),
6245 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6246 arc_state_multilist_index_func);
6247 arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6248 multilist_create(sizeof (arc_buf_hdr_t),
6249 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6250 arc_state_multilist_index_func);
6251 arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6252 multilist_create(sizeof (arc_buf_hdr_t),
6253 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6254 arc_state_multilist_index_func);
6255 arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6256 multilist_create(sizeof (arc_buf_hdr_t),
6257 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6258 arc_state_multilist_index_func);
6260 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6261 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6262 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6263 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6264 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6265 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6266 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6267 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6268 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6269 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6270 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6271 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6273 refcount_create(&arc_anon->arcs_size);
6274 refcount_create(&arc_mru->arcs_size);
6275 refcount_create(&arc_mru_ghost->arcs_size);
6276 refcount_create(&arc_mfu->arcs_size);
6277 refcount_create(&arc_mfu_ghost->arcs_size);
6278 refcount_create(&arc_l2c_only->arcs_size);
6282 arc_state_fini(void)
6284 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6285 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6286 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6287 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6288 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6289 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6290 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6291 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6292 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6293 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6294 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6295 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6297 refcount_destroy(&arc_anon->arcs_size);
6298 refcount_destroy(&arc_mru->arcs_size);
6299 refcount_destroy(&arc_mru_ghost->arcs_size);
6300 refcount_destroy(&arc_mfu->arcs_size);
6301 refcount_destroy(&arc_mfu_ghost->arcs_size);
6302 refcount_destroy(&arc_l2c_only->arcs_size);
6304 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6305 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6306 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6307 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
6308 multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
6309 multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
6310 multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
6311 multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6323 int i, prefetch_tunable_set = 0;
6326 * allmem is "all memory that we could possibly use".
6330 uint64_t allmem = ptob(physmem - swapfs_minfree);
6332 uint64_t allmem = (physmem * PAGESIZE) / 2;
6335 uint64_t allmem = kmem_size();
6339 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
6340 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
6341 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
6343 mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
6344 cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
6346 /* Convert seconds to clock ticks */
6347 arc_min_prefetch_lifespan = 1 * hz;
6349 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
6350 arc_c_min = MAX(allmem / 32, arc_abs_min);
6351 /* set max to 5/8 of all memory, or all but 1GB, whichever is more */
6352 if (allmem >= 1 << 30)
6353 arc_c_max = allmem - (1 << 30);
6355 arc_c_max = arc_c_min;
6356 arc_c_max = MAX(allmem * 5 / 8, arc_c_max);
6359 * In userland, there's only the memory pressure that we artificially
6360 * create (see arc_available_memory()). Don't let arc_c get too
6361 * small, because it can cause transactions to be larger than
6362 * arc_c, causing arc_tempreserve_space() to fail.
6365 arc_c_min = arc_c_max / 2;
6370 * Allow the tunables to override our calculations if they are
6373 if (zfs_arc_max > arc_abs_min && zfs_arc_max < allmem) {
6374 arc_c_max = zfs_arc_max;
6375 arc_c_min = MIN(arc_c_min, arc_c_max);
6377 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
6378 arc_c_min = zfs_arc_min;
6382 arc_p = (arc_c >> 1);
6385 /* limit meta-data to 1/4 of the arc capacity */
6386 arc_meta_limit = arc_c_max / 4;
6390 * Metadata is stored in the kernel's heap. Don't let us
6391 * use more than half the heap for the ARC.
6393 arc_meta_limit = MIN(arc_meta_limit,
6394 vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6397 /* Allow the tunable to override if it is reasonable */
6398 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6399 arc_meta_limit = zfs_arc_meta_limit;
6401 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6402 arc_c_min = arc_meta_limit / 2;
6404 if (zfs_arc_meta_min > 0) {
6405 arc_meta_min = zfs_arc_meta_min;
6407 arc_meta_min = arc_c_min / 2;
6410 if (zfs_arc_grow_retry > 0)
6411 arc_grow_retry = zfs_arc_grow_retry;
6413 if (zfs_arc_shrink_shift > 0)
6414 arc_shrink_shift = zfs_arc_shrink_shift;
6417 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6419 if (arc_no_grow_shift >= arc_shrink_shift)
6420 arc_no_grow_shift = arc_shrink_shift - 1;
6422 if (zfs_arc_p_min_shift > 0)
6423 arc_p_min_shift = zfs_arc_p_min_shift;
6425 /* if kmem_flags are set, lets try to use less memory */
6426 if (kmem_debugging())
6428 if (arc_c < arc_c_min)
6431 zfs_arc_min = arc_c_min;
6432 zfs_arc_max = arc_c_max;
6437 arc_reclaim_thread_exit = B_FALSE;
6438 arc_dnlc_evicts_thread_exit = FALSE;
6440 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6441 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6443 if (arc_ksp != NULL) {
6444 arc_ksp->ks_data = &arc_stats;
6445 arc_ksp->ks_update = arc_kstat_update;
6446 kstat_install(arc_ksp);
6449 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6450 TS_RUN, minclsyspri);
6453 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
6454 EVENTHANDLER_PRI_FIRST);
6457 (void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
6458 TS_RUN, minclsyspri);
6464 * Calculate maximum amount of dirty data per pool.
6466 * If it has been set by /etc/system, take that.
6467 * Otherwise, use a percentage of physical memory defined by
6468 * zfs_dirty_data_max_percent (default 10%) with a cap at
6469 * zfs_dirty_data_max_max (default 4GB).
6471 if (zfs_dirty_data_max == 0) {
6472 zfs_dirty_data_max = ptob(physmem) *
6473 zfs_dirty_data_max_percent / 100;
6474 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6475 zfs_dirty_data_max_max);
6479 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
6480 prefetch_tunable_set = 1;
6483 if (prefetch_tunable_set == 0) {
6484 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
6486 printf(" add \"vfs.zfs.prefetch_disable=0\" "
6487 "to /boot/loader.conf.\n");
6488 zfs_prefetch_disable = 1;
6491 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
6492 prefetch_tunable_set == 0) {
6493 printf("ZFS NOTICE: Prefetch is disabled by default if less "
6494 "than 4GB of RAM is present;\n"
6495 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
6496 "to /boot/loader.conf.\n");
6497 zfs_prefetch_disable = 1;
6500 /* Warn about ZFS memory and address space requirements. */
6501 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
6502 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
6503 "expect unstable behavior.\n");
6505 if (allmem < 512 * (1 << 20)) {
6506 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
6507 "expect unstable behavior.\n");
6508 printf(" Consider tuning vm.kmem_size and "
6509 "vm.kmem_size_max\n");
6510 printf(" in /boot/loader.conf.\n");
6518 mutex_enter(&arc_reclaim_lock);
6519 arc_reclaim_thread_exit = B_TRUE;
6521 * The reclaim thread will set arc_reclaim_thread_exit back to
6522 * B_FALSE when it is finished exiting; we're waiting for that.
6524 while (arc_reclaim_thread_exit) {
6525 cv_signal(&arc_reclaim_thread_cv);
6526 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6528 mutex_exit(&arc_reclaim_lock);
6530 /* Use B_TRUE to ensure *all* buffers are evicted */
6531 arc_flush(NULL, B_TRUE);
6533 mutex_enter(&arc_dnlc_evicts_lock);
6534 arc_dnlc_evicts_thread_exit = TRUE;
6536 * The user evicts thread will set arc_user_evicts_thread_exit
6537 * to FALSE when it is finished exiting; we're waiting for that.
6539 while (arc_dnlc_evicts_thread_exit) {
6540 cv_signal(&arc_dnlc_evicts_cv);
6541 cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
6543 mutex_exit(&arc_dnlc_evicts_lock);
6547 if (arc_ksp != NULL) {
6548 kstat_delete(arc_ksp);
6552 mutex_destroy(&arc_reclaim_lock);
6553 cv_destroy(&arc_reclaim_thread_cv);
6554 cv_destroy(&arc_reclaim_waiters_cv);
6556 mutex_destroy(&arc_dnlc_evicts_lock);
6557 cv_destroy(&arc_dnlc_evicts_cv);
6562 ASSERT0(arc_loaned_bytes);
6565 if (arc_event_lowmem != NULL)
6566 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
6573 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6574 * It uses dedicated storage devices to hold cached data, which are populated
6575 * using large infrequent writes. The main role of this cache is to boost
6576 * the performance of random read workloads. The intended L2ARC devices
6577 * include short-stroked disks, solid state disks, and other media with
6578 * substantially faster read latency than disk.
6580 * +-----------------------+
6582 * +-----------------------+
6585 * l2arc_feed_thread() arc_read()
6589 * +---------------+ |
6591 * +---------------+ |
6596 * +-------+ +-------+
6598 * | cache | | cache |
6599 * +-------+ +-------+
6600 * +=========+ .-----.
6601 * : L2ARC : |-_____-|
6602 * : devices : | Disks |
6603 * +=========+ `-_____-'
6605 * Read requests are satisfied from the following sources, in order:
6608 * 2) vdev cache of L2ARC devices
6610 * 4) vdev cache of disks
6613 * Some L2ARC device types exhibit extremely slow write performance.
6614 * To accommodate for this there are some significant differences between
6615 * the L2ARC and traditional cache design:
6617 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
6618 * the ARC behave as usual, freeing buffers and placing headers on ghost
6619 * lists. The ARC does not send buffers to the L2ARC during eviction as
6620 * this would add inflated write latencies for all ARC memory pressure.
6622 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6623 * It does this by periodically scanning buffers from the eviction-end of
6624 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6625 * not already there. It scans until a headroom of buffers is satisfied,
6626 * which itself is a buffer for ARC eviction. If a compressible buffer is
6627 * found during scanning and selected for writing to an L2ARC device, we
6628 * temporarily boost scanning headroom during the next scan cycle to make
6629 * sure we adapt to compression effects (which might significantly reduce
6630 * the data volume we write to L2ARC). The thread that does this is
6631 * l2arc_feed_thread(), illustrated below; example sizes are included to
6632 * provide a better sense of ratio than this diagram:
6635 * +---------------------+----------+
6636 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
6637 * +---------------------+----------+ | o L2ARC eligible
6638 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
6639 * +---------------------+----------+ |
6640 * 15.9 Gbytes ^ 32 Mbytes |
6642 * l2arc_feed_thread()
6644 * l2arc write hand <--[oooo]--'
6648 * +==============================+
6649 * L2ARC dev |####|#|###|###| |####| ... |
6650 * +==============================+
6653 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6654 * evicted, then the L2ARC has cached a buffer much sooner than it probably
6655 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
6656 * safe to say that this is an uncommon case, since buffers at the end of
6657 * the ARC lists have moved there due to inactivity.
6659 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6660 * then the L2ARC simply misses copying some buffers. This serves as a
6661 * pressure valve to prevent heavy read workloads from both stalling the ARC
6662 * with waits and clogging the L2ARC with writes. This also helps prevent
6663 * the potential for the L2ARC to churn if it attempts to cache content too
6664 * quickly, such as during backups of the entire pool.
6666 * 5. After system boot and before the ARC has filled main memory, there are
6667 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
6668 * lists can remain mostly static. Instead of searching from tail of these
6669 * lists as pictured, the l2arc_feed_thread() will search from the list heads
6670 * for eligible buffers, greatly increasing its chance of finding them.
6672 * The L2ARC device write speed is also boosted during this time so that
6673 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
6674 * there are no L2ARC reads, and no fear of degrading read performance
6675 * through increased writes.
6677 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6678 * the vdev queue can aggregate them into larger and fewer writes. Each
6679 * device is written to in a rotor fashion, sweeping writes through
6680 * available space then repeating.
6682 * 7. The L2ARC does not store dirty content. It never needs to flush
6683 * write buffers back to disk based storage.
6685 * 8. If an ARC buffer is written (and dirtied) which also exists in the
6686 * L2ARC, the now stale L2ARC buffer is immediately dropped.
6688 * The performance of the L2ARC can be tweaked by a number of tunables, which
6689 * may be necessary for different workloads:
6691 * l2arc_write_max max write bytes per interval
6692 * l2arc_write_boost extra write bytes during device warmup
6693 * l2arc_noprefetch skip caching prefetched buffers
6694 * l2arc_headroom number of max device writes to precache
6695 * l2arc_headroom_boost when we find compressed buffers during ARC
6696 * scanning, we multiply headroom by this
6697 * percentage factor for the next scan cycle,
6698 * since more compressed buffers are likely to
6700 * l2arc_feed_secs seconds between L2ARC writing
6702 * Tunables may be removed or added as future performance improvements are
6703 * integrated, and also may become zpool properties.
6705 * There are three key functions that control how the L2ARC warms up:
6707 * l2arc_write_eligible() check if a buffer is eligible to cache
6708 * l2arc_write_size() calculate how much to write
6709 * l2arc_write_interval() calculate sleep delay between writes
6711 * These three functions determine what to write, how much, and how quickly
6716 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
6719 * A buffer is *not* eligible for the L2ARC if it:
6720 * 1. belongs to a different spa.
6721 * 2. is already cached on the L2ARC.
6722 * 3. has an I/O in progress (it may be an incomplete read).
6723 * 4. is flagged not eligible (zfs property).
6725 if (hdr->b_spa != spa_guid) {
6726 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
6729 if (HDR_HAS_L2HDR(hdr)) {
6730 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
6733 if (HDR_IO_IN_PROGRESS(hdr)) {
6734 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
6737 if (!HDR_L2CACHE(hdr)) {
6738 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
6746 l2arc_write_size(void)
6751 * Make sure our globals have meaningful values in case the user
6754 size = l2arc_write_max;
6756 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6757 "be greater than zero, resetting it to the default (%d)",
6759 size = l2arc_write_max = L2ARC_WRITE_SIZE;
6762 if (arc_warm == B_FALSE)
6763 size += l2arc_write_boost;
6770 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
6772 clock_t interval, next, now;
6775 * If the ARC lists are busy, increase our write rate; if the
6776 * lists are stale, idle back. This is achieved by checking
6777 * how much we previously wrote - if it was more than half of
6778 * what we wanted, schedule the next write much sooner.
6780 if (l2arc_feed_again && wrote > (wanted / 2))
6781 interval = (hz * l2arc_feed_min_ms) / 1000;
6783 interval = hz * l2arc_feed_secs;
6785 now = ddi_get_lbolt();
6786 next = MAX(now, MIN(now + interval, began + interval));
6792 * Cycle through L2ARC devices. This is how L2ARC load balances.
6793 * If a device is returned, this also returns holding the spa config lock.
6795 static l2arc_dev_t *
6796 l2arc_dev_get_next(void)
6798 l2arc_dev_t *first, *next = NULL;
6801 * Lock out the removal of spas (spa_namespace_lock), then removal
6802 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
6803 * both locks will be dropped and a spa config lock held instead.
6805 mutex_enter(&spa_namespace_lock);
6806 mutex_enter(&l2arc_dev_mtx);
6808 /* if there are no vdevs, there is nothing to do */
6809 if (l2arc_ndev == 0)
6813 next = l2arc_dev_last;
6815 /* loop around the list looking for a non-faulted vdev */
6817 next = list_head(l2arc_dev_list);
6819 next = list_next(l2arc_dev_list, next);
6821 next = list_head(l2arc_dev_list);
6824 /* if we have come back to the start, bail out */
6827 else if (next == first)
6830 } while (vdev_is_dead(next->l2ad_vdev));
6832 /* if we were unable to find any usable vdevs, return NULL */
6833 if (vdev_is_dead(next->l2ad_vdev))
6836 l2arc_dev_last = next;
6839 mutex_exit(&l2arc_dev_mtx);
6842 * Grab the config lock to prevent the 'next' device from being
6843 * removed while we are writing to it.
6846 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
6847 mutex_exit(&spa_namespace_lock);
6853 * Free buffers that were tagged for destruction.
6856 l2arc_do_free_on_write()
6859 l2arc_data_free_t *df, *df_prev;
6861 mutex_enter(&l2arc_free_on_write_mtx);
6862 buflist = l2arc_free_on_write;
6864 for (df = list_tail(buflist); df; df = df_prev) {
6865 df_prev = list_prev(buflist, df);
6866 ASSERT3P(df->l2df_data, !=, NULL);
6867 if (df->l2df_type == ARC_BUFC_METADATA) {
6868 zio_buf_free(df->l2df_data, df->l2df_size);
6870 ASSERT(df->l2df_type == ARC_BUFC_DATA);
6871 zio_data_buf_free(df->l2df_data, df->l2df_size);
6873 list_remove(buflist, df);
6874 kmem_free(df, sizeof (l2arc_data_free_t));
6877 mutex_exit(&l2arc_free_on_write_mtx);
6881 * A write to a cache device has completed. Update all headers to allow
6882 * reads from these buffers to begin.
6885 l2arc_write_done(zio_t *zio)
6887 l2arc_write_callback_t *cb;
6890 arc_buf_hdr_t *head, *hdr, *hdr_prev;
6891 kmutex_t *hash_lock;
6892 int64_t bytes_dropped = 0;
6894 cb = zio->io_private;
6895 ASSERT3P(cb, !=, NULL);
6896 dev = cb->l2wcb_dev;
6897 ASSERT3P(dev, !=, NULL);
6898 head = cb->l2wcb_head;
6899 ASSERT3P(head, !=, NULL);
6900 buflist = &dev->l2ad_buflist;
6901 ASSERT3P(buflist, !=, NULL);
6902 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6903 l2arc_write_callback_t *, cb);
6905 if (zio->io_error != 0)
6906 ARCSTAT_BUMP(arcstat_l2_writes_error);
6909 * All writes completed, or an error was hit.
6912 mutex_enter(&dev->l2ad_mtx);
6913 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
6914 hdr_prev = list_prev(buflist, hdr);
6916 hash_lock = HDR_LOCK(hdr);
6919 * We cannot use mutex_enter or else we can deadlock
6920 * with l2arc_write_buffers (due to swapping the order
6921 * the hash lock and l2ad_mtx are taken).
6923 if (!mutex_tryenter(hash_lock)) {
6925 * Missed the hash lock. We must retry so we
6926 * don't leave the ARC_FLAG_L2_WRITING bit set.
6928 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6931 * We don't want to rescan the headers we've
6932 * already marked as having been written out, so
6933 * we reinsert the head node so we can pick up
6934 * where we left off.
6936 list_remove(buflist, head);
6937 list_insert_after(buflist, hdr, head);
6939 mutex_exit(&dev->l2ad_mtx);
6942 * We wait for the hash lock to become available
6943 * to try and prevent busy waiting, and increase
6944 * the chance we'll be able to acquire the lock
6945 * the next time around.
6947 mutex_enter(hash_lock);
6948 mutex_exit(hash_lock);
6953 * We could not have been moved into the arc_l2c_only
6954 * state while in-flight due to our ARC_FLAG_L2_WRITING
6955 * bit being set. Let's just ensure that's being enforced.
6957 ASSERT(HDR_HAS_L1HDR(hdr));
6959 if (zio->io_error != 0) {
6961 * Error - drop L2ARC entry.
6963 list_remove(buflist, hdr);
6965 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
6967 ARCSTAT_INCR(arcstat_l2_asize, -arc_hdr_size(hdr));
6968 ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
6970 bytes_dropped += arc_hdr_size(hdr);
6971 (void) refcount_remove_many(&dev->l2ad_alloc,
6972 arc_hdr_size(hdr), hdr);
6976 * Allow ARC to begin reads and ghost list evictions to
6979 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6981 mutex_exit(hash_lock);
6984 atomic_inc_64(&l2arc_writes_done);
6985 list_remove(buflist, head);
6986 ASSERT(!HDR_HAS_L1HDR(head));
6987 kmem_cache_free(hdr_l2only_cache, head);
6988 mutex_exit(&dev->l2ad_mtx);
6990 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6992 l2arc_do_free_on_write();
6994 kmem_free(cb, sizeof (l2arc_write_callback_t));
6998 * A read to a cache device completed. Validate buffer contents before
6999 * handing over to the regular ARC routines.
7002 l2arc_read_done(zio_t *zio)
7004 l2arc_read_callback_t *cb;
7006 kmutex_t *hash_lock;
7007 boolean_t valid_cksum;
7009 ASSERT3P(zio->io_vd, !=, NULL);
7010 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7012 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7014 cb = zio->io_private;
7015 ASSERT3P(cb, !=, NULL);
7016 hdr = cb->l2rcb_hdr;
7017 ASSERT3P(hdr, !=, NULL);
7019 hash_lock = HDR_LOCK(hdr);
7020 mutex_enter(hash_lock);
7021 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7024 * If the data was read into a temporary buffer,
7025 * move it and free the buffer.
7027 if (cb->l2rcb_data != NULL) {
7028 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7029 if (zio->io_error == 0) {
7030 bcopy(cb->l2rcb_data, hdr->b_l1hdr.b_pdata,
7035 * The following must be done regardless of whether
7036 * there was an error:
7037 * - free the temporary buffer
7038 * - point zio to the real ARC buffer
7039 * - set zio size accordingly
7040 * These are required because zio is either re-used for
7041 * an I/O of the block in the case of the error
7042 * or the zio is passed to arc_read_done() and it
7045 zio_data_buf_free(cb->l2rcb_data, zio->io_size);
7046 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7047 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_pdata;
7050 ASSERT3P(zio->io_data, !=, NULL);
7053 * Check this survived the L2ARC journey.
7055 ASSERT3P(zio->io_data, ==, hdr->b_l1hdr.b_pdata);
7056 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
7057 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
7059 valid_cksum = arc_cksum_is_equal(hdr, zio);
7060 if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7061 mutex_exit(hash_lock);
7062 zio->io_private = hdr;
7065 mutex_exit(hash_lock);
7067 * Buffer didn't survive caching. Increment stats and
7068 * reissue to the original storage device.
7070 if (zio->io_error != 0) {
7071 ARCSTAT_BUMP(arcstat_l2_io_error);
7073 zio->io_error = SET_ERROR(EIO);
7076 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7079 * If there's no waiter, issue an async i/o to the primary
7080 * storage now. If there *is* a waiter, the caller must
7081 * issue the i/o in a context where it's OK to block.
7083 if (zio->io_waiter == NULL) {
7084 zio_t *pio = zio_unique_parent(zio);
7086 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7088 zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7089 hdr->b_l1hdr.b_pdata, zio->io_size, arc_read_done,
7090 hdr, zio->io_priority, cb->l2rcb_flags,
7095 kmem_free(cb, sizeof (l2arc_read_callback_t));
7099 * This is the list priority from which the L2ARC will search for pages to
7100 * cache. This is used within loops (0..3) to cycle through lists in the
7101 * desired order. This order can have a significant effect on cache
7104 * Currently the metadata lists are hit first, MFU then MRU, followed by
7105 * the data lists. This function returns a locked list, and also returns
7108 static multilist_sublist_t *
7109 l2arc_sublist_lock(int list_num)
7111 multilist_t *ml = NULL;
7114 ASSERT(list_num >= 0 && list_num <= 3);
7118 ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
7121 ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
7124 ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
7127 ml = arc_mru->arcs_list[ARC_BUFC_DATA];
7132 * Return a randomly-selected sublist. This is acceptable
7133 * because the caller feeds only a little bit of data for each
7134 * call (8MB). Subsequent calls will result in different
7135 * sublists being selected.
7137 idx = multilist_get_random_index(ml);
7138 return (multilist_sublist_lock(ml, idx));
7142 * Evict buffers from the device write hand to the distance specified in
7143 * bytes. This distance may span populated buffers, it may span nothing.
7144 * This is clearing a region on the L2ARC device ready for writing.
7145 * If the 'all' boolean is set, every buffer is evicted.
7148 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7151 arc_buf_hdr_t *hdr, *hdr_prev;
7152 kmutex_t *hash_lock;
7155 buflist = &dev->l2ad_buflist;
7157 if (!all && dev->l2ad_first) {
7159 * This is the first sweep through the device. There is
7165 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7167 * When nearing the end of the device, evict to the end
7168 * before the device write hand jumps to the start.
7170 taddr = dev->l2ad_end;
7172 taddr = dev->l2ad_hand + distance;
7174 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7175 uint64_t, taddr, boolean_t, all);
7178 mutex_enter(&dev->l2ad_mtx);
7179 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
7180 hdr_prev = list_prev(buflist, hdr);
7182 hash_lock = HDR_LOCK(hdr);
7185 * We cannot use mutex_enter or else we can deadlock
7186 * with l2arc_write_buffers (due to swapping the order
7187 * the hash lock and l2ad_mtx are taken).
7189 if (!mutex_tryenter(hash_lock)) {
7191 * Missed the hash lock. Retry.
7193 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
7194 mutex_exit(&dev->l2ad_mtx);
7195 mutex_enter(hash_lock);
7196 mutex_exit(hash_lock);
7200 if (HDR_L2_WRITE_HEAD(hdr)) {
7202 * We hit a write head node. Leave it for
7203 * l2arc_write_done().
7205 list_remove(buflist, hdr);
7206 mutex_exit(hash_lock);
7210 if (!all && HDR_HAS_L2HDR(hdr) &&
7211 (hdr->b_l2hdr.b_daddr >= taddr ||
7212 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
7214 * We've evicted to the target address,
7215 * or the end of the device.
7217 mutex_exit(hash_lock);
7221 ASSERT(HDR_HAS_L2HDR(hdr));
7222 if (!HDR_HAS_L1HDR(hdr)) {
7223 ASSERT(!HDR_L2_READING(hdr));
7225 * This doesn't exist in the ARC. Destroy.
7226 * arc_hdr_destroy() will call list_remove()
7227 * and decrement arcstat_l2_size.
7229 arc_change_state(arc_anon, hdr, hash_lock);
7230 arc_hdr_destroy(hdr);
7232 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
7233 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
7235 * Invalidate issued or about to be issued
7236 * reads, since we may be about to write
7237 * over this location.
7239 if (HDR_L2_READING(hdr)) {
7240 ARCSTAT_BUMP(arcstat_l2_evict_reading);
7241 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7244 /* Ensure this header has finished being written */
7245 ASSERT(!HDR_L2_WRITING(hdr));
7247 arc_hdr_l2hdr_destroy(hdr);
7249 mutex_exit(hash_lock);
7251 mutex_exit(&dev->l2ad_mtx);
7255 * Find and write ARC buffers to the L2ARC device.
7257 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7258 * for reading until they have completed writing.
7259 * The headroom_boost is an in-out parameter used to maintain headroom boost
7260 * state between calls to this function.
7262 * Returns the number of bytes actually written (which may be smaller than
7263 * the delta by which the device hand has changed due to alignment).
7266 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7268 arc_buf_hdr_t *hdr, *hdr_prev, *head;
7269 uint64_t write_asize, write_psize, write_sz, headroom;
7271 l2arc_write_callback_t *cb;
7273 uint64_t guid = spa_load_guid(spa);
7276 ASSERT3P(dev->l2ad_vdev, !=, NULL);
7279 write_sz = write_asize = write_psize = 0;
7281 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7282 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7284 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
7286 * Copy buffers for L2ARC writing.
7288 for (try = 0; try <= 3; try++) {
7289 multilist_sublist_t *mls = l2arc_sublist_lock(try);
7290 uint64_t passed_sz = 0;
7292 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
7295 * L2ARC fast warmup.
7297 * Until the ARC is warm and starts to evict, read from the
7298 * head of the ARC lists rather than the tail.
7300 if (arc_warm == B_FALSE)
7301 hdr = multilist_sublist_head(mls);
7303 hdr = multilist_sublist_tail(mls);
7305 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
7307 headroom = target_sz * l2arc_headroom;
7308 if (zfs_compressed_arc_enabled)
7309 headroom = (headroom * l2arc_headroom_boost) / 100;
7311 for (; hdr; hdr = hdr_prev) {
7312 kmutex_t *hash_lock;
7314 if (arc_warm == B_FALSE)
7315 hdr_prev = multilist_sublist_next(mls, hdr);
7317 hdr_prev = multilist_sublist_prev(mls, hdr);
7318 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
7319 HDR_GET_LSIZE(hdr));
7321 hash_lock = HDR_LOCK(hdr);
7322 if (!mutex_tryenter(hash_lock)) {
7323 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
7325 * Skip this buffer rather than waiting.
7330 passed_sz += HDR_GET_LSIZE(hdr);
7331 if (passed_sz > headroom) {
7335 mutex_exit(hash_lock);
7336 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
7340 if (!l2arc_write_eligible(guid, hdr)) {
7341 mutex_exit(hash_lock);
7346 * We rely on the L1 portion of the header below, so
7347 * it's invalid for this header to have been evicted out
7348 * of the ghost cache, prior to being written out. The
7349 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7351 ASSERT(HDR_HAS_L1HDR(hdr));
7353 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7354 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
7355 ASSERT3U(arc_hdr_size(hdr), >, 0);
7356 uint64_t size = arc_hdr_size(hdr);
7357 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7360 if ((write_psize + asize) > target_sz) {
7362 mutex_exit(hash_lock);
7363 ARCSTAT_BUMP(arcstat_l2_write_full);
7369 * Insert a dummy header on the buflist so
7370 * l2arc_write_done() can find where the
7371 * write buffers begin without searching.
7373 mutex_enter(&dev->l2ad_mtx);
7374 list_insert_head(&dev->l2ad_buflist, head);
7375 mutex_exit(&dev->l2ad_mtx);
7378 sizeof (l2arc_write_callback_t), KM_SLEEP);
7379 cb->l2wcb_dev = dev;
7380 cb->l2wcb_head = head;
7381 pio = zio_root(spa, l2arc_write_done, cb,
7383 ARCSTAT_BUMP(arcstat_l2_write_pios);
7386 hdr->b_l2hdr.b_dev = dev;
7387 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7388 arc_hdr_set_flags(hdr,
7389 ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7391 mutex_enter(&dev->l2ad_mtx);
7392 list_insert_head(&dev->l2ad_buflist, hdr);
7393 mutex_exit(&dev->l2ad_mtx);
7395 (void) refcount_add_many(&dev->l2ad_alloc, size, hdr);
7398 * Normally the L2ARC can use the hdr's data, but if
7399 * we're sharing data between the hdr and one of its
7400 * bufs, L2ARC needs its own copy of the data so that
7401 * the ZIO below can't race with the buf consumer. To
7402 * ensure that this copy will be available for the
7403 * lifetime of the ZIO and be cleaned up afterwards, we
7404 * add it to the l2arc_free_on_write queue.
7407 if (!HDR_SHARED_DATA(hdr) && size == asize) {
7408 to_write = hdr->b_l1hdr.b_pdata;
7410 arc_buf_contents_t type = arc_buf_type(hdr);
7411 if (type == ARC_BUFC_METADATA) {
7412 to_write = zio_buf_alloc(asize);
7414 ASSERT3U(type, ==, ARC_BUFC_DATA);
7415 to_write = zio_data_buf_alloc(asize);
7418 bcopy(hdr->b_l1hdr.b_pdata, to_write, size);
7420 bzero(to_write + size, asize - size);
7421 l2arc_free_data_on_write(to_write, asize, type);
7423 wzio = zio_write_phys(pio, dev->l2ad_vdev,
7424 hdr->b_l2hdr.b_daddr, asize, to_write,
7425 ZIO_CHECKSUM_OFF, NULL, hdr,
7426 ZIO_PRIORITY_ASYNC_WRITE,
7427 ZIO_FLAG_CANFAIL, B_FALSE);
7429 write_sz += HDR_GET_LSIZE(hdr);
7430 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7433 write_asize += size;
7434 write_psize += asize;
7435 dev->l2ad_hand += asize;
7437 mutex_exit(hash_lock);
7439 (void) zio_nowait(wzio);
7442 multilist_sublist_unlock(mls);
7448 /* No buffers selected for writing? */
7451 ASSERT(!HDR_HAS_L1HDR(head));
7452 kmem_cache_free(hdr_l2only_cache, head);
7456 ASSERT3U(write_psize, <=, target_sz);
7457 ARCSTAT_BUMP(arcstat_l2_writes_sent);
7458 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
7459 ARCSTAT_INCR(arcstat_l2_size, write_sz);
7460 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
7461 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
7464 * Bump device hand to the device start if it is approaching the end.
7465 * l2arc_evict() will already have evicted ahead for this case.
7467 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7468 dev->l2ad_hand = dev->l2ad_start;
7469 dev->l2ad_first = B_FALSE;
7472 dev->l2ad_writing = B_TRUE;
7473 (void) zio_wait(pio);
7474 dev->l2ad_writing = B_FALSE;
7476 return (write_asize);
7480 * This thread feeds the L2ARC at regular intervals. This is the beating
7481 * heart of the L2ARC.
7484 l2arc_feed_thread(void *dummy __unused)
7489 uint64_t size, wrote;
7490 clock_t begin, next = ddi_get_lbolt();
7492 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7494 mutex_enter(&l2arc_feed_thr_lock);
7496 while (l2arc_thread_exit == 0) {
7497 CALLB_CPR_SAFE_BEGIN(&cpr);
7498 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7499 next - ddi_get_lbolt());
7500 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7501 next = ddi_get_lbolt() + hz;
7504 * Quick check for L2ARC devices.
7506 mutex_enter(&l2arc_dev_mtx);
7507 if (l2arc_ndev == 0) {
7508 mutex_exit(&l2arc_dev_mtx);
7511 mutex_exit(&l2arc_dev_mtx);
7512 begin = ddi_get_lbolt();
7515 * This selects the next l2arc device to write to, and in
7516 * doing so the next spa to feed from: dev->l2ad_spa. This
7517 * will return NULL if there are now no l2arc devices or if
7518 * they are all faulted.
7520 * If a device is returned, its spa's config lock is also
7521 * held to prevent device removal. l2arc_dev_get_next()
7522 * will grab and release l2arc_dev_mtx.
7524 if ((dev = l2arc_dev_get_next()) == NULL)
7527 spa = dev->l2ad_spa;
7528 ASSERT3P(spa, !=, NULL);
7531 * If the pool is read-only then force the feed thread to
7532 * sleep a little longer.
7534 if (!spa_writeable(spa)) {
7535 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7536 spa_config_exit(spa, SCL_L2ARC, dev);
7541 * Avoid contributing to memory pressure.
7543 if (arc_reclaim_needed()) {
7544 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7545 spa_config_exit(spa, SCL_L2ARC, dev);
7549 ARCSTAT_BUMP(arcstat_l2_feeds);
7551 size = l2arc_write_size();
7554 * Evict L2ARC buffers that will be overwritten.
7556 l2arc_evict(dev, size, B_FALSE);
7559 * Write ARC buffers.
7561 wrote = l2arc_write_buffers(spa, dev, size);
7564 * Calculate interval between writes.
7566 next = l2arc_write_interval(begin, size, wrote);
7567 spa_config_exit(spa, SCL_L2ARC, dev);
7570 l2arc_thread_exit = 0;
7571 cv_broadcast(&l2arc_feed_thr_cv);
7572 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
7577 l2arc_vdev_present(vdev_t *vd)
7581 mutex_enter(&l2arc_dev_mtx);
7582 for (dev = list_head(l2arc_dev_list); dev != NULL;
7583 dev = list_next(l2arc_dev_list, dev)) {
7584 if (dev->l2ad_vdev == vd)
7587 mutex_exit(&l2arc_dev_mtx);
7589 return (dev != NULL);
7593 * Add a vdev for use by the L2ARC. By this point the spa has already
7594 * validated the vdev and opened it.
7597 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7599 l2arc_dev_t *adddev;
7601 ASSERT(!l2arc_vdev_present(vd));
7603 vdev_ashift_optimize(vd);
7606 * Create a new l2arc device entry.
7608 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7609 adddev->l2ad_spa = spa;
7610 adddev->l2ad_vdev = vd;
7611 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7612 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7613 adddev->l2ad_hand = adddev->l2ad_start;
7614 adddev->l2ad_first = B_TRUE;
7615 adddev->l2ad_writing = B_FALSE;
7617 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7619 * This is a list of all ARC buffers that are still valid on the
7622 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7623 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7625 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7626 refcount_create(&adddev->l2ad_alloc);
7629 * Add device to global list
7631 mutex_enter(&l2arc_dev_mtx);
7632 list_insert_head(l2arc_dev_list, adddev);
7633 atomic_inc_64(&l2arc_ndev);
7634 mutex_exit(&l2arc_dev_mtx);
7638 * Remove a vdev from the L2ARC.
7641 l2arc_remove_vdev(vdev_t *vd)
7643 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7646 * Find the device by vdev
7648 mutex_enter(&l2arc_dev_mtx);
7649 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7650 nextdev = list_next(l2arc_dev_list, dev);
7651 if (vd == dev->l2ad_vdev) {
7656 ASSERT3P(remdev, !=, NULL);
7659 * Remove device from global list
7661 list_remove(l2arc_dev_list, remdev);
7662 l2arc_dev_last = NULL; /* may have been invalidated */
7663 atomic_dec_64(&l2arc_ndev);
7664 mutex_exit(&l2arc_dev_mtx);
7667 * Clear all buflists and ARC references. L2ARC device flush.
7669 l2arc_evict(remdev, 0, B_TRUE);
7670 list_destroy(&remdev->l2ad_buflist);
7671 mutex_destroy(&remdev->l2ad_mtx);
7672 refcount_destroy(&remdev->l2ad_alloc);
7673 kmem_free(remdev, sizeof (l2arc_dev_t));
7679 l2arc_thread_exit = 0;
7681 l2arc_writes_sent = 0;
7682 l2arc_writes_done = 0;
7684 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7685 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7686 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7687 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7689 l2arc_dev_list = &L2ARC_dev_list;
7690 l2arc_free_on_write = &L2ARC_free_on_write;
7691 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7692 offsetof(l2arc_dev_t, l2ad_node));
7693 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7694 offsetof(l2arc_data_free_t, l2df_list_node));
7701 * This is called from dmu_fini(), which is called from spa_fini();
7702 * Because of this, we can assume that all l2arc devices have
7703 * already been removed when the pools themselves were removed.
7706 l2arc_do_free_on_write();
7708 mutex_destroy(&l2arc_feed_thr_lock);
7709 cv_destroy(&l2arc_feed_thr_cv);
7710 mutex_destroy(&l2arc_dev_mtx);
7711 mutex_destroy(&l2arc_free_on_write_mtx);
7713 list_destroy(l2arc_dev_list);
7714 list_destroy(l2arc_free_on_write);
7720 if (!(spa_mode_global & FWRITE))
7723 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7724 TS_RUN, minclsyspri);
7730 if (!(spa_mode_global & FWRITE))
7733 mutex_enter(&l2arc_feed_thr_lock);
7734 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7735 l2arc_thread_exit = 1;
7736 while (l2arc_thread_exit != 0)
7737 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7738 mutex_exit(&l2arc_feed_thr_lock);