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, 2016 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;
308 * The number of sublists used for each of the arc state lists. If this
309 * is not set to a suitable value by the user, it will be configured to
310 * the number of CPUs on the system in arc_init().
312 int zfs_arc_num_sublists_per_state = 0;
314 /* number of seconds before growing cache again */
315 static int arc_grow_retry = 60;
317 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
318 int zfs_arc_overflow_shift = 8;
320 /* shift of arc_c for calculating both min and max arc_p */
321 static int arc_p_min_shift = 4;
323 /* log2(fraction of arc to reclaim) */
324 static int arc_shrink_shift = 7;
327 * log2(fraction of ARC which must be free to allow growing).
328 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
329 * when reading a new block into the ARC, we will evict an equal-sized block
332 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
333 * we will still not allow it to grow.
335 int arc_no_grow_shift = 5;
339 * minimum lifespan of a prefetch block in clock ticks
340 * (initialized in arc_init())
342 static int arc_min_prefetch_lifespan;
345 * If this percent of memory is free, don't throttle.
347 int arc_lotsfree_percent = 10;
350 extern boolean_t zfs_prefetch_disable;
353 * The arc has filled available memory and has now warmed up.
355 static boolean_t arc_warm;
358 * These tunables are for performance analysis.
360 uint64_t zfs_arc_max;
361 uint64_t zfs_arc_min;
362 uint64_t zfs_arc_meta_limit = 0;
363 uint64_t zfs_arc_meta_min = 0;
364 int zfs_arc_grow_retry = 0;
365 int zfs_arc_shrink_shift = 0;
366 int zfs_arc_p_min_shift = 0;
367 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
368 u_int zfs_arc_free_target = 0;
370 /* Absolute min for arc min / max is 16MB. */
371 static uint64_t arc_abs_min = 16 << 20;
373 boolean_t zfs_compressed_arc_enabled = B_TRUE;
375 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
376 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
377 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
378 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
380 #if defined(__FreeBSD__) && defined(_KERNEL)
382 arc_free_target_init(void *unused __unused)
385 zfs_arc_free_target = vm_pageout_wakeup_thresh;
387 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
388 arc_free_target_init, NULL);
390 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
391 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
392 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
393 SYSCTL_DECL(_vfs_zfs);
394 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
395 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
396 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
397 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
398 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
399 &zfs_arc_average_blocksize, 0,
400 "ARC average blocksize");
401 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
402 &arc_shrink_shift, 0,
403 "log2(fraction of arc to reclaim)");
404 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
405 &zfs_compressed_arc_enabled, 0, "Enable compressed ARC");
408 * We don't have a tunable for arc_free_target due to the dependency on
409 * pagedaemon initialisation.
411 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
412 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
413 sysctl_vfs_zfs_arc_free_target, "IU",
414 "Desired number of free pages below which ARC triggers reclaim");
417 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
422 val = zfs_arc_free_target;
423 err = sysctl_handle_int(oidp, &val, 0, req);
424 if (err != 0 || req->newptr == NULL)
429 if (val > vm_cnt.v_page_count)
432 zfs_arc_free_target = val;
438 * Must be declared here, before the definition of corresponding kstat
439 * macro which uses the same names will confuse the compiler.
441 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
442 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
443 sysctl_vfs_zfs_arc_meta_limit, "QU",
444 "ARC metadata limit");
448 * Note that buffers can be in one of 6 states:
449 * ARC_anon - anonymous (discussed below)
450 * ARC_mru - recently used, currently cached
451 * ARC_mru_ghost - recentely used, no longer in cache
452 * ARC_mfu - frequently used, currently cached
453 * ARC_mfu_ghost - frequently used, no longer in cache
454 * ARC_l2c_only - exists in L2ARC but not other states
455 * When there are no active references to the buffer, they are
456 * are linked onto a list in one of these arc states. These are
457 * the only buffers that can be evicted or deleted. Within each
458 * state there are multiple lists, one for meta-data and one for
459 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
460 * etc.) is tracked separately so that it can be managed more
461 * explicitly: favored over data, limited explicitly.
463 * Anonymous buffers are buffers that are not associated with
464 * a DVA. These are buffers that hold dirty block copies
465 * before they are written to stable storage. By definition,
466 * they are "ref'd" and are considered part of arc_mru
467 * that cannot be freed. Generally, they will aquire a DVA
468 * as they are written and migrate onto the arc_mru list.
470 * The ARC_l2c_only state is for buffers that are in the second
471 * level ARC but no longer in any of the ARC_m* lists. The second
472 * level ARC itself may also contain buffers that are in any of
473 * the ARC_m* states - meaning that a buffer can exist in two
474 * places. The reason for the ARC_l2c_only state is to keep the
475 * buffer header in the hash table, so that reads that hit the
476 * second level ARC benefit from these fast lookups.
479 typedef struct arc_state {
481 * list of evictable buffers
483 multilist_t arcs_list[ARC_BUFC_NUMTYPES];
485 * total amount of evictable data in this state
487 refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
489 * total amount of data in this state; this includes: evictable,
490 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
492 refcount_t arcs_size;
496 static arc_state_t ARC_anon;
497 static arc_state_t ARC_mru;
498 static arc_state_t ARC_mru_ghost;
499 static arc_state_t ARC_mfu;
500 static arc_state_t ARC_mfu_ghost;
501 static arc_state_t ARC_l2c_only;
503 typedef struct arc_stats {
504 kstat_named_t arcstat_hits;
505 kstat_named_t arcstat_misses;
506 kstat_named_t arcstat_demand_data_hits;
507 kstat_named_t arcstat_demand_data_misses;
508 kstat_named_t arcstat_demand_metadata_hits;
509 kstat_named_t arcstat_demand_metadata_misses;
510 kstat_named_t arcstat_prefetch_data_hits;
511 kstat_named_t arcstat_prefetch_data_misses;
512 kstat_named_t arcstat_prefetch_metadata_hits;
513 kstat_named_t arcstat_prefetch_metadata_misses;
514 kstat_named_t arcstat_mru_hits;
515 kstat_named_t arcstat_mru_ghost_hits;
516 kstat_named_t arcstat_mfu_hits;
517 kstat_named_t arcstat_mfu_ghost_hits;
518 kstat_named_t arcstat_allocated;
519 kstat_named_t arcstat_deleted;
521 * Number of buffers that could not be evicted because the hash lock
522 * was held by another thread. The lock may not necessarily be held
523 * by something using the same buffer, since hash locks are shared
524 * by multiple buffers.
526 kstat_named_t arcstat_mutex_miss;
528 * Number of buffers skipped because they have I/O in progress, are
529 * indrect prefetch buffers that have not lived long enough, or are
530 * not from the spa we're trying to evict from.
532 kstat_named_t arcstat_evict_skip;
534 * Number of times arc_evict_state() was unable to evict enough
535 * buffers to reach it's target amount.
537 kstat_named_t arcstat_evict_not_enough;
538 kstat_named_t arcstat_evict_l2_cached;
539 kstat_named_t arcstat_evict_l2_eligible;
540 kstat_named_t arcstat_evict_l2_ineligible;
541 kstat_named_t arcstat_evict_l2_skip;
542 kstat_named_t arcstat_hash_elements;
543 kstat_named_t arcstat_hash_elements_max;
544 kstat_named_t arcstat_hash_collisions;
545 kstat_named_t arcstat_hash_chains;
546 kstat_named_t arcstat_hash_chain_max;
547 kstat_named_t arcstat_p;
548 kstat_named_t arcstat_c;
549 kstat_named_t arcstat_c_min;
550 kstat_named_t arcstat_c_max;
551 kstat_named_t arcstat_size;
553 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pdata.
554 * Note that the compressed bytes may match the uncompressed bytes
555 * if the block is either not compressed or compressed arc is disabled.
557 kstat_named_t arcstat_compressed_size;
559 * Uncompressed size of the data stored in b_pdata. If compressed
560 * arc is disabled then this value will be identical to the stat
563 kstat_named_t arcstat_uncompressed_size;
565 * Number of bytes stored in all the arc_buf_t's. This is classified
566 * as "overhead" since this data is typically short-lived and will
567 * be evicted from the arc when it becomes unreferenced unless the
568 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
569 * values have been set (see comment in dbuf.c for more information).
571 kstat_named_t arcstat_overhead_size;
573 * Number of bytes consumed by internal ARC structures necessary
574 * for tracking purposes; these structures are not actually
575 * backed by ARC buffers. This includes arc_buf_hdr_t structures
576 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
577 * caches), and arc_buf_t structures (allocated via arc_buf_t
580 kstat_named_t arcstat_hdr_size;
582 * Number of bytes consumed by ARC buffers of type equal to
583 * ARC_BUFC_DATA. This is generally consumed by buffers backing
584 * on disk user data (e.g. plain file contents).
586 kstat_named_t arcstat_data_size;
588 * Number of bytes consumed by ARC buffers of type equal to
589 * ARC_BUFC_METADATA. This is generally consumed by buffers
590 * backing on disk data that is used for internal ZFS
591 * structures (e.g. ZAP, dnode, indirect blocks, etc).
593 kstat_named_t arcstat_metadata_size;
595 * Number of bytes consumed by various buffers and structures
596 * not actually backed with ARC buffers. This includes bonus
597 * buffers (allocated directly via zio_buf_* functions),
598 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
599 * cache), and dnode_t structures (allocated via dnode_t cache).
601 kstat_named_t arcstat_other_size;
603 * Total number of bytes consumed by ARC buffers residing in the
604 * arc_anon state. This includes *all* buffers in the arc_anon
605 * state; e.g. data, metadata, evictable, and unevictable buffers
606 * are all included in this value.
608 kstat_named_t arcstat_anon_size;
610 * Number of bytes consumed by ARC buffers that meet the
611 * following criteria: backing buffers of type ARC_BUFC_DATA,
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_data;
617 * Number of bytes consumed by ARC buffers that meet the
618 * following criteria: backing buffers of type ARC_BUFC_METADATA,
619 * residing in the arc_anon state, and are eligible for eviction
620 * (e.g. have no outstanding holds on the buffer).
622 kstat_named_t arcstat_anon_evictable_metadata;
624 * Total number of bytes consumed by ARC buffers residing in the
625 * arc_mru state. This includes *all* buffers in the arc_mru
626 * state; e.g. data, metadata, evictable, and unevictable buffers
627 * are all included in this value.
629 kstat_named_t arcstat_mru_size;
631 * Number of bytes consumed by ARC buffers that meet the
632 * following criteria: backing buffers of type ARC_BUFC_DATA,
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_data;
638 * Number of bytes consumed by ARC buffers that meet the
639 * following criteria: backing buffers of type ARC_BUFC_METADATA,
640 * residing in the arc_mru state, and are eligible for eviction
641 * (e.g. have no outstanding holds on the buffer).
643 kstat_named_t arcstat_mru_evictable_metadata;
645 * Total number of bytes that *would have been* consumed by ARC
646 * buffers in the arc_mru_ghost state. The key thing to note
647 * here, is the fact that this size doesn't actually indicate
648 * RAM consumption. The ghost lists only consist of headers and
649 * don't actually have ARC buffers linked off of these headers.
650 * Thus, *if* the headers had associated ARC buffers, these
651 * buffers *would have* consumed this number of bytes.
653 kstat_named_t arcstat_mru_ghost_size;
655 * Number of bytes that *would have been* consumed by ARC
656 * buffers that are eligible for eviction, of type
657 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
659 kstat_named_t arcstat_mru_ghost_evictable_data;
661 * Number of bytes that *would have been* consumed by ARC
662 * buffers that are eligible for eviction, of type
663 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
665 kstat_named_t arcstat_mru_ghost_evictable_metadata;
667 * Total number of bytes consumed by ARC buffers residing in the
668 * arc_mfu state. This includes *all* buffers in the arc_mfu
669 * state; e.g. data, metadata, evictable, and unevictable buffers
670 * are all included in this value.
672 kstat_named_t arcstat_mfu_size;
674 * Number of bytes consumed by ARC buffers that are eligible for
675 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
678 kstat_named_t arcstat_mfu_evictable_data;
680 * Number of bytes consumed by ARC buffers that are eligible for
681 * eviction, of type ARC_BUFC_METADATA, and reside in the
684 kstat_named_t arcstat_mfu_evictable_metadata;
686 * Total number of bytes that *would have been* consumed by ARC
687 * buffers in the arc_mfu_ghost state. See the comment above
688 * arcstat_mru_ghost_size for more details.
690 kstat_named_t arcstat_mfu_ghost_size;
692 * Number of bytes that *would have been* consumed by ARC
693 * buffers that are eligible for eviction, of type
694 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
696 kstat_named_t arcstat_mfu_ghost_evictable_data;
698 * Number of bytes that *would have been* consumed by ARC
699 * buffers that are eligible for eviction, of type
700 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
702 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
703 kstat_named_t arcstat_l2_hits;
704 kstat_named_t arcstat_l2_misses;
705 kstat_named_t arcstat_l2_feeds;
706 kstat_named_t arcstat_l2_rw_clash;
707 kstat_named_t arcstat_l2_read_bytes;
708 kstat_named_t arcstat_l2_write_bytes;
709 kstat_named_t arcstat_l2_writes_sent;
710 kstat_named_t arcstat_l2_writes_done;
711 kstat_named_t arcstat_l2_writes_error;
712 kstat_named_t arcstat_l2_writes_lock_retry;
713 kstat_named_t arcstat_l2_evict_lock_retry;
714 kstat_named_t arcstat_l2_evict_reading;
715 kstat_named_t arcstat_l2_evict_l1cached;
716 kstat_named_t arcstat_l2_free_on_write;
717 kstat_named_t arcstat_l2_abort_lowmem;
718 kstat_named_t arcstat_l2_cksum_bad;
719 kstat_named_t arcstat_l2_io_error;
720 kstat_named_t arcstat_l2_size;
721 kstat_named_t arcstat_l2_asize;
722 kstat_named_t arcstat_l2_hdr_size;
723 kstat_named_t arcstat_l2_write_trylock_fail;
724 kstat_named_t arcstat_l2_write_passed_headroom;
725 kstat_named_t arcstat_l2_write_spa_mismatch;
726 kstat_named_t arcstat_l2_write_in_l2;
727 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
728 kstat_named_t arcstat_l2_write_not_cacheable;
729 kstat_named_t arcstat_l2_write_full;
730 kstat_named_t arcstat_l2_write_buffer_iter;
731 kstat_named_t arcstat_l2_write_pios;
732 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
733 kstat_named_t arcstat_l2_write_buffer_list_iter;
734 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
735 kstat_named_t arcstat_memory_throttle_count;
736 kstat_named_t arcstat_meta_used;
737 kstat_named_t arcstat_meta_limit;
738 kstat_named_t arcstat_meta_max;
739 kstat_named_t arcstat_meta_min;
740 kstat_named_t arcstat_sync_wait_for_async;
741 kstat_named_t arcstat_demand_hit_predictive_prefetch;
744 static arc_stats_t arc_stats = {
745 { "hits", KSTAT_DATA_UINT64 },
746 { "misses", KSTAT_DATA_UINT64 },
747 { "demand_data_hits", KSTAT_DATA_UINT64 },
748 { "demand_data_misses", KSTAT_DATA_UINT64 },
749 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
750 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
751 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
752 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
753 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
754 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
755 { "mru_hits", KSTAT_DATA_UINT64 },
756 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
757 { "mfu_hits", KSTAT_DATA_UINT64 },
758 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
759 { "allocated", KSTAT_DATA_UINT64 },
760 { "deleted", KSTAT_DATA_UINT64 },
761 { "mutex_miss", KSTAT_DATA_UINT64 },
762 { "evict_skip", KSTAT_DATA_UINT64 },
763 { "evict_not_enough", KSTAT_DATA_UINT64 },
764 { "evict_l2_cached", KSTAT_DATA_UINT64 },
765 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
766 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
767 { "evict_l2_skip", KSTAT_DATA_UINT64 },
768 { "hash_elements", KSTAT_DATA_UINT64 },
769 { "hash_elements_max", KSTAT_DATA_UINT64 },
770 { "hash_collisions", KSTAT_DATA_UINT64 },
771 { "hash_chains", KSTAT_DATA_UINT64 },
772 { "hash_chain_max", KSTAT_DATA_UINT64 },
773 { "p", KSTAT_DATA_UINT64 },
774 { "c", KSTAT_DATA_UINT64 },
775 { "c_min", KSTAT_DATA_UINT64 },
776 { "c_max", KSTAT_DATA_UINT64 },
777 { "size", KSTAT_DATA_UINT64 },
778 { "compressed_size", KSTAT_DATA_UINT64 },
779 { "uncompressed_size", KSTAT_DATA_UINT64 },
780 { "overhead_size", KSTAT_DATA_UINT64 },
781 { "hdr_size", KSTAT_DATA_UINT64 },
782 { "data_size", KSTAT_DATA_UINT64 },
783 { "metadata_size", KSTAT_DATA_UINT64 },
784 { "other_size", KSTAT_DATA_UINT64 },
785 { "anon_size", KSTAT_DATA_UINT64 },
786 { "anon_evictable_data", KSTAT_DATA_UINT64 },
787 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
788 { "mru_size", KSTAT_DATA_UINT64 },
789 { "mru_evictable_data", KSTAT_DATA_UINT64 },
790 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
791 { "mru_ghost_size", KSTAT_DATA_UINT64 },
792 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
793 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
794 { "mfu_size", KSTAT_DATA_UINT64 },
795 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
796 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
797 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
798 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
799 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
800 { "l2_hits", KSTAT_DATA_UINT64 },
801 { "l2_misses", KSTAT_DATA_UINT64 },
802 { "l2_feeds", KSTAT_DATA_UINT64 },
803 { "l2_rw_clash", KSTAT_DATA_UINT64 },
804 { "l2_read_bytes", KSTAT_DATA_UINT64 },
805 { "l2_write_bytes", KSTAT_DATA_UINT64 },
806 { "l2_writes_sent", KSTAT_DATA_UINT64 },
807 { "l2_writes_done", KSTAT_DATA_UINT64 },
808 { "l2_writes_error", KSTAT_DATA_UINT64 },
809 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
810 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
811 { "l2_evict_reading", KSTAT_DATA_UINT64 },
812 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
813 { "l2_free_on_write", KSTAT_DATA_UINT64 },
814 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
815 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
816 { "l2_io_error", KSTAT_DATA_UINT64 },
817 { "l2_size", KSTAT_DATA_UINT64 },
818 { "l2_asize", KSTAT_DATA_UINT64 },
819 { "l2_hdr_size", KSTAT_DATA_UINT64 },
820 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
821 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
822 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
823 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
824 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
825 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
826 { "l2_write_full", KSTAT_DATA_UINT64 },
827 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
828 { "l2_write_pios", KSTAT_DATA_UINT64 },
829 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
830 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
831 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
832 { "memory_throttle_count", KSTAT_DATA_UINT64 },
833 { "arc_meta_used", KSTAT_DATA_UINT64 },
834 { "arc_meta_limit", KSTAT_DATA_UINT64 },
835 { "arc_meta_max", KSTAT_DATA_UINT64 },
836 { "arc_meta_min", KSTAT_DATA_UINT64 },
837 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
838 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
841 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
843 #define ARCSTAT_INCR(stat, val) \
844 atomic_add_64(&arc_stats.stat.value.ui64, (val))
846 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
847 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
849 #define ARCSTAT_MAX(stat, val) { \
851 while ((val) > (m = arc_stats.stat.value.ui64) && \
852 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
856 #define ARCSTAT_MAXSTAT(stat) \
857 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
860 * We define a macro to allow ARC hits/misses to be easily broken down by
861 * two separate conditions, giving a total of four different subtypes for
862 * each of hits and misses (so eight statistics total).
864 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
867 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
869 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
873 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
875 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
880 static arc_state_t *arc_anon;
881 static arc_state_t *arc_mru;
882 static arc_state_t *arc_mru_ghost;
883 static arc_state_t *arc_mfu;
884 static arc_state_t *arc_mfu_ghost;
885 static arc_state_t *arc_l2c_only;
888 * There are several ARC variables that are critical to export as kstats --
889 * but we don't want to have to grovel around in the kstat whenever we wish to
890 * manipulate them. For these variables, we therefore define them to be in
891 * terms of the statistic variable. This assures that we are not introducing
892 * the possibility of inconsistency by having shadow copies of the variables,
893 * while still allowing the code to be readable.
895 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
896 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
897 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
898 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
899 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
900 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
901 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
902 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
903 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
905 /* compressed size of entire arc */
906 #define arc_compressed_size ARCSTAT(arcstat_compressed_size)
907 /* uncompressed size of entire arc */
908 #define arc_uncompressed_size ARCSTAT(arcstat_uncompressed_size)
909 /* number of bytes in the arc from arc_buf_t's */
910 #define arc_overhead_size ARCSTAT(arcstat_overhead_size)
912 static int arc_no_grow; /* Don't try to grow cache size */
913 static uint64_t arc_tempreserve;
914 static uint64_t arc_loaned_bytes;
916 typedef struct arc_callback arc_callback_t;
918 struct arc_callback {
920 arc_done_func_t *acb_done;
922 boolean_t acb_compressed;
923 zio_t *acb_zio_dummy;
924 arc_callback_t *acb_next;
927 typedef struct arc_write_callback arc_write_callback_t;
929 struct arc_write_callback {
931 arc_done_func_t *awcb_ready;
932 arc_done_func_t *awcb_children_ready;
933 arc_done_func_t *awcb_physdone;
934 arc_done_func_t *awcb_done;
939 * ARC buffers are separated into multiple structs as a memory saving measure:
940 * - Common fields struct, always defined, and embedded within it:
941 * - L2-only fields, always allocated but undefined when not in L2ARC
942 * - L1-only fields, only allocated when in L1ARC
944 * Buffer in L1 Buffer only in L2
945 * +------------------------+ +------------------------+
946 * | arc_buf_hdr_t | | arc_buf_hdr_t |
950 * +------------------------+ +------------------------+
951 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
952 * | (undefined if L1-only) | | |
953 * +------------------------+ +------------------------+
954 * | l1arc_buf_hdr_t |
959 * +------------------------+
961 * Because it's possible for the L2ARC to become extremely large, we can wind
962 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
963 * is minimized by only allocating the fields necessary for an L1-cached buffer
964 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
965 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
966 * words in pointers. arc_hdr_realloc() is used to switch a header between
967 * these two allocation states.
969 typedef struct l1arc_buf_hdr {
970 kmutex_t b_freeze_lock;
971 zio_cksum_t *b_freeze_cksum;
974 * Used for debugging with kmem_flags - by allocating and freeing
975 * b_thawed when the buffer is thawed, we get a record of the stack
976 * trace that thawed it.
983 /* for waiting on writes to complete */
987 /* protected by arc state mutex */
988 arc_state_t *b_state;
989 multilist_node_t b_arc_node;
991 /* updated atomically */
992 clock_t b_arc_access;
994 /* self protecting */
997 arc_callback_t *b_acb;
1001 typedef struct l2arc_dev l2arc_dev_t;
1003 typedef struct l2arc_buf_hdr {
1004 /* protected by arc_buf_hdr mutex */
1005 l2arc_dev_t *b_dev; /* L2ARC device */
1006 uint64_t b_daddr; /* disk address, offset byte */
1008 list_node_t b_l2node;
1011 struct arc_buf_hdr {
1012 /* protected by hash lock */
1016 arc_buf_contents_t b_type;
1017 arc_buf_hdr_t *b_hash_next;
1018 arc_flags_t b_flags;
1021 * This field stores the size of the data buffer after
1022 * compression, and is set in the arc's zio completion handlers.
1023 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1025 * While the block pointers can store up to 32MB in their psize
1026 * field, we can only store up to 32MB minus 512B. This is due
1027 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1028 * a field of zeros represents 512B in the bp). We can't use a
1029 * bias of 1 since we need to reserve a psize of zero, here, to
1030 * represent holes and embedded blocks.
1032 * This isn't a problem in practice, since the maximum size of a
1033 * buffer is limited to 16MB, so we never need to store 32MB in
1034 * this field. Even in the upstream illumos code base, the
1035 * maximum size of a buffer is limited to 16MB.
1040 * This field stores the size of the data buffer before
1041 * compression, and cannot change once set. It is in units
1042 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1044 uint16_t b_lsize; /* immutable */
1045 uint64_t b_spa; /* immutable */
1047 /* L2ARC fields. Undefined when not in L2ARC. */
1048 l2arc_buf_hdr_t b_l2hdr;
1049 /* L1ARC fields. Undefined when in l2arc_only state */
1050 l1arc_buf_hdr_t b_l1hdr;
1053 #if defined(__FreeBSD__) && defined(_KERNEL)
1055 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1060 val = arc_meta_limit;
1061 err = sysctl_handle_64(oidp, &val, 0, req);
1062 if (err != 0 || req->newptr == NULL)
1065 if (val <= 0 || val > arc_c_max)
1068 arc_meta_limit = val;
1073 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1079 err = sysctl_handle_64(oidp, &val, 0, req);
1080 if (err != 0 || req->newptr == NULL)
1083 if (zfs_arc_max == 0) {
1084 /* Loader tunable so blindly set */
1089 if (val < arc_abs_min || val > kmem_size())
1091 if (val < arc_c_min)
1093 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1099 arc_p = (arc_c >> 1);
1101 if (zfs_arc_meta_limit == 0) {
1102 /* limit meta-data to 1/4 of the arc capacity */
1103 arc_meta_limit = arc_c_max / 4;
1106 /* if kmem_flags are set, lets try to use less memory */
1107 if (kmem_debugging())
1110 zfs_arc_max = arc_c;
1116 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1122 err = sysctl_handle_64(oidp, &val, 0, req);
1123 if (err != 0 || req->newptr == NULL)
1126 if (zfs_arc_min == 0) {
1127 /* Loader tunable so blindly set */
1132 if (val < arc_abs_min || val > arc_c_max)
1137 if (zfs_arc_meta_min == 0)
1138 arc_meta_min = arc_c_min / 2;
1140 if (arc_c < arc_c_min)
1143 zfs_arc_min = arc_c_min;
1149 #define GHOST_STATE(state) \
1150 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
1151 (state) == arc_l2c_only)
1153 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1154 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1155 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1156 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1157 #define HDR_COMPRESSION_ENABLED(hdr) \
1158 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1160 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1161 #define HDR_L2_READING(hdr) \
1162 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1163 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1164 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1165 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1166 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1167 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1169 #define HDR_ISTYPE_METADATA(hdr) \
1170 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1171 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1173 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1174 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1176 /* For storing compression mode in b_flags */
1177 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1179 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1180 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1181 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1182 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1184 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
1185 #define ARC_BUF_SHARED(buf) ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1186 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1192 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1193 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1196 * Hash table routines
1199 #define HT_LOCK_PAD CACHE_LINE_SIZE
1204 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1208 #define BUF_LOCKS 256
1209 typedef struct buf_hash_table {
1211 arc_buf_hdr_t **ht_table;
1212 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1215 static buf_hash_table_t buf_hash_table;
1217 #define BUF_HASH_INDEX(spa, dva, birth) \
1218 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1219 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1220 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1221 #define HDR_LOCK(hdr) \
1222 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1224 uint64_t zfs_crc64_table[256];
1230 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1231 #define L2ARC_HEADROOM 2 /* num of writes */
1233 * If we discover during ARC scan any buffers to be compressed, we boost
1234 * our headroom for the next scanning cycle by this percentage multiple.
1236 #define L2ARC_HEADROOM_BOOST 200
1237 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1238 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1240 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1241 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1243 /* L2ARC Performance Tunables */
1244 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1245 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1246 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1247 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1248 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1249 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1250 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1251 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1252 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1254 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1255 &l2arc_write_max, 0, "max write size");
1256 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1257 &l2arc_write_boost, 0, "extra write during warmup");
1258 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1259 &l2arc_headroom, 0, "number of dev writes");
1260 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1261 &l2arc_feed_secs, 0, "interval seconds");
1262 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1263 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1265 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1266 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1267 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1268 &l2arc_feed_again, 0, "turbo warmup");
1269 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1270 &l2arc_norw, 0, "no reads during writes");
1272 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1273 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1274 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1275 &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1276 "size of anonymous state");
1277 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1278 &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1279 "size of anonymous state");
1281 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1282 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1283 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1284 &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1285 "size of metadata in mru state");
1286 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1287 &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1288 "size of data in mru state");
1290 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1291 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1292 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1293 &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1294 "size of metadata in mru ghost state");
1295 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1296 &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1297 "size of data in mru ghost state");
1299 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1300 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1301 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1302 &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1303 "size of metadata in mfu state");
1304 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1305 &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1306 "size of data in mfu state");
1308 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1309 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1310 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1311 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1312 "size of metadata in mfu ghost state");
1313 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1314 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1315 "size of data in mfu ghost state");
1317 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1318 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1324 vdev_t *l2ad_vdev; /* vdev */
1325 spa_t *l2ad_spa; /* spa */
1326 uint64_t l2ad_hand; /* next write location */
1327 uint64_t l2ad_start; /* first addr on device */
1328 uint64_t l2ad_end; /* last addr on device */
1329 boolean_t l2ad_first; /* first sweep through */
1330 boolean_t l2ad_writing; /* currently writing */
1331 kmutex_t l2ad_mtx; /* lock for buffer list */
1332 list_t l2ad_buflist; /* buffer list */
1333 list_node_t l2ad_node; /* device list node */
1334 refcount_t l2ad_alloc; /* allocated bytes */
1337 static list_t L2ARC_dev_list; /* device list */
1338 static list_t *l2arc_dev_list; /* device list pointer */
1339 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1340 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1341 static list_t L2ARC_free_on_write; /* free after write buf list */
1342 static list_t *l2arc_free_on_write; /* free after write list ptr */
1343 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1344 static uint64_t l2arc_ndev; /* number of devices */
1346 typedef struct l2arc_read_callback {
1347 arc_buf_hdr_t *l2rcb_hdr; /* read header */
1348 blkptr_t l2rcb_bp; /* original blkptr */
1349 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1350 int l2rcb_flags; /* original flags */
1351 void *l2rcb_data; /* temporary buffer */
1352 } l2arc_read_callback_t;
1354 typedef struct l2arc_write_callback {
1355 l2arc_dev_t *l2wcb_dev; /* device info */
1356 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1357 } l2arc_write_callback_t;
1359 typedef struct l2arc_data_free {
1360 /* protected by l2arc_free_on_write_mtx */
1363 arc_buf_contents_t l2df_type;
1364 list_node_t l2df_list_node;
1365 } l2arc_data_free_t;
1367 static kmutex_t l2arc_feed_thr_lock;
1368 static kcondvar_t l2arc_feed_thr_cv;
1369 static uint8_t l2arc_thread_exit;
1371 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1372 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1373 static void arc_hdr_free_pdata(arc_buf_hdr_t *hdr);
1374 static void arc_hdr_alloc_pdata(arc_buf_hdr_t *);
1375 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1376 static boolean_t arc_is_overflowing();
1377 static void arc_buf_watch(arc_buf_t *);
1379 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1380 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1381 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1382 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1384 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1385 static void l2arc_read_done(zio_t *);
1388 l2arc_trim(const arc_buf_hdr_t *hdr)
1390 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1392 ASSERT(HDR_HAS_L2HDR(hdr));
1393 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1395 if (HDR_GET_PSIZE(hdr) != 0) {
1396 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1397 HDR_GET_PSIZE(hdr), 0);
1402 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1404 uint8_t *vdva = (uint8_t *)dva;
1405 uint64_t crc = -1ULL;
1408 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1410 for (i = 0; i < sizeof (dva_t); i++)
1411 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1413 crc ^= (spa>>8) ^ birth;
1418 #define HDR_EMPTY(hdr) \
1419 ((hdr)->b_dva.dva_word[0] == 0 && \
1420 (hdr)->b_dva.dva_word[1] == 0)
1422 #define HDR_EQUAL(spa, dva, birth, hdr) \
1423 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1424 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1425 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1428 buf_discard_identity(arc_buf_hdr_t *hdr)
1430 hdr->b_dva.dva_word[0] = 0;
1431 hdr->b_dva.dva_word[1] = 0;
1435 static arc_buf_hdr_t *
1436 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1438 const dva_t *dva = BP_IDENTITY(bp);
1439 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1440 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1441 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1444 mutex_enter(hash_lock);
1445 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1446 hdr = hdr->b_hash_next) {
1447 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1452 mutex_exit(hash_lock);
1458 * Insert an entry into the hash table. If there is already an element
1459 * equal to elem in the hash table, then the already existing element
1460 * will be returned and the new element will not be inserted.
1461 * Otherwise returns NULL.
1462 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1464 static arc_buf_hdr_t *
1465 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1467 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1468 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1469 arc_buf_hdr_t *fhdr;
1472 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1473 ASSERT(hdr->b_birth != 0);
1474 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1476 if (lockp != NULL) {
1478 mutex_enter(hash_lock);
1480 ASSERT(MUTEX_HELD(hash_lock));
1483 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1484 fhdr = fhdr->b_hash_next, i++) {
1485 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1489 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1490 buf_hash_table.ht_table[idx] = hdr;
1491 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1493 /* collect some hash table performance data */
1495 ARCSTAT_BUMP(arcstat_hash_collisions);
1497 ARCSTAT_BUMP(arcstat_hash_chains);
1499 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1502 ARCSTAT_BUMP(arcstat_hash_elements);
1503 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1509 buf_hash_remove(arc_buf_hdr_t *hdr)
1511 arc_buf_hdr_t *fhdr, **hdrp;
1512 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1514 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1515 ASSERT(HDR_IN_HASH_TABLE(hdr));
1517 hdrp = &buf_hash_table.ht_table[idx];
1518 while ((fhdr = *hdrp) != hdr) {
1519 ASSERT3P(fhdr, !=, NULL);
1520 hdrp = &fhdr->b_hash_next;
1522 *hdrp = hdr->b_hash_next;
1523 hdr->b_hash_next = NULL;
1524 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1526 /* collect some hash table performance data */
1527 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1529 if (buf_hash_table.ht_table[idx] &&
1530 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1531 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1535 * Global data structures and functions for the buf kmem cache.
1537 static kmem_cache_t *hdr_full_cache;
1538 static kmem_cache_t *hdr_l2only_cache;
1539 static kmem_cache_t *buf_cache;
1546 kmem_free(buf_hash_table.ht_table,
1547 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1548 for (i = 0; i < BUF_LOCKS; i++)
1549 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1550 kmem_cache_destroy(hdr_full_cache);
1551 kmem_cache_destroy(hdr_l2only_cache);
1552 kmem_cache_destroy(buf_cache);
1556 * Constructor callback - called when the cache is empty
1557 * and a new buf is requested.
1561 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1563 arc_buf_hdr_t *hdr = vbuf;
1565 bzero(hdr, HDR_FULL_SIZE);
1566 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1567 refcount_create(&hdr->b_l1hdr.b_refcnt);
1568 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1569 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1570 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1577 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1579 arc_buf_hdr_t *hdr = vbuf;
1581 bzero(hdr, HDR_L2ONLY_SIZE);
1582 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1589 buf_cons(void *vbuf, void *unused, int kmflag)
1591 arc_buf_t *buf = vbuf;
1593 bzero(buf, sizeof (arc_buf_t));
1594 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1595 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1601 * Destructor callback - called when a cached buf is
1602 * no longer required.
1606 hdr_full_dest(void *vbuf, void *unused)
1608 arc_buf_hdr_t *hdr = vbuf;
1610 ASSERT(HDR_EMPTY(hdr));
1611 cv_destroy(&hdr->b_l1hdr.b_cv);
1612 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1613 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1614 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1615 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1620 hdr_l2only_dest(void *vbuf, void *unused)
1622 arc_buf_hdr_t *hdr = vbuf;
1624 ASSERT(HDR_EMPTY(hdr));
1625 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1630 buf_dest(void *vbuf, void *unused)
1632 arc_buf_t *buf = vbuf;
1634 mutex_destroy(&buf->b_evict_lock);
1635 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1639 * Reclaim callback -- invoked when memory is low.
1643 hdr_recl(void *unused)
1645 dprintf("hdr_recl called\n");
1647 * umem calls the reclaim func when we destroy the buf cache,
1648 * which is after we do arc_fini().
1651 cv_signal(&arc_reclaim_thread_cv);
1658 uint64_t hsize = 1ULL << 12;
1662 * The hash table is big enough to fill all of physical memory
1663 * with an average block size of zfs_arc_average_blocksize (default 8K).
1664 * By default, the table will take up
1665 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1667 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1670 buf_hash_table.ht_mask = hsize - 1;
1671 buf_hash_table.ht_table =
1672 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1673 if (buf_hash_table.ht_table == NULL) {
1674 ASSERT(hsize > (1ULL << 8));
1679 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1680 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1681 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1682 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1684 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1685 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1687 for (i = 0; i < 256; i++)
1688 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1689 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1691 for (i = 0; i < BUF_LOCKS; i++) {
1692 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1693 NULL, MUTEX_DEFAULT, NULL);
1698 * This is the size that the buf occupies in memory. If the buf is compressed,
1699 * it will correspond to the compressed size. You should use this method of
1700 * getting the buf size unless you explicitly need the logical size.
1703 arc_buf_size(arc_buf_t *buf)
1705 return (ARC_BUF_COMPRESSED(buf) ?
1706 HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1710 arc_buf_lsize(arc_buf_t *buf)
1712 return (HDR_GET_LSIZE(buf->b_hdr));
1716 arc_get_compression(arc_buf_t *buf)
1718 return (ARC_BUF_COMPRESSED(buf) ?
1719 HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1722 #define ARC_MINTIME (hz>>4) /* 62 ms */
1724 static inline boolean_t
1725 arc_buf_is_shared(arc_buf_t *buf)
1727 boolean_t shared = (buf->b_data != NULL &&
1728 buf->b_data == buf->b_hdr->b_l1hdr.b_pdata);
1729 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1730 IMPLY(shared, ARC_BUF_SHARED(buf));
1731 IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1734 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1735 * already being shared" requirement prevents us from doing that.
1742 * Free the checksum associated with this header. If there is no checksum, this
1746 arc_cksum_free(arc_buf_hdr_t *hdr)
1748 ASSERT(HDR_HAS_L1HDR(hdr));
1749 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1750 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1751 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1752 hdr->b_l1hdr.b_freeze_cksum = NULL;
1754 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1758 * Return true iff at least one of the bufs on hdr is not compressed.
1761 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1763 for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1764 if (!ARC_BUF_COMPRESSED(b)) {
1772 * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1773 * matches the checksum that is stored in the hdr. If there is no checksum,
1774 * or if the buf is compressed, this is a no-op.
1777 arc_cksum_verify(arc_buf_t *buf)
1779 arc_buf_hdr_t *hdr = buf->b_hdr;
1782 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1785 if (ARC_BUF_COMPRESSED(buf)) {
1786 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1787 arc_hdr_has_uncompressed_buf(hdr));
1791 ASSERT(HDR_HAS_L1HDR(hdr));
1793 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1794 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1795 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1799 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1800 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1801 panic("buffer modified while frozen!");
1802 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1806 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1808 enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1809 boolean_t valid_cksum;
1811 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1812 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1815 * We rely on the blkptr's checksum to determine if the block
1816 * is valid or not. When compressed arc is enabled, the l2arc
1817 * writes the block to the l2arc just as it appears in the pool.
1818 * This allows us to use the blkptr's checksum to validate the
1819 * data that we just read off of the l2arc without having to store
1820 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1821 * arc is disabled, then the data written to the l2arc is always
1822 * uncompressed and won't match the block as it exists in the main
1823 * pool. When this is the case, we must first compress it if it is
1824 * compressed on the main pool before we can validate the checksum.
1826 if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1827 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1828 uint64_t lsize = HDR_GET_LSIZE(hdr);
1831 void *cbuf = zio_buf_alloc(HDR_GET_PSIZE(hdr));
1832 csize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1833 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1834 if (csize < HDR_GET_PSIZE(hdr)) {
1836 * Compressed blocks are always a multiple of the
1837 * smallest ashift in the pool. Ideally, we would
1838 * like to round up the csize to the next
1839 * spa_min_ashift but that value may have changed
1840 * since the block was last written. Instead,
1841 * we rely on the fact that the hdr's psize
1842 * was set to the psize of the block when it was
1843 * last written. We set the csize to that value
1844 * and zero out any part that should not contain
1847 bzero((char *)cbuf + csize, HDR_GET_PSIZE(hdr) - csize);
1848 csize = HDR_GET_PSIZE(hdr);
1850 zio_push_transform(zio, cbuf, csize, HDR_GET_PSIZE(hdr), NULL);
1854 * Block pointers always store the checksum for the logical data.
1855 * If the block pointer has the gang bit set, then the checksum
1856 * it represents is for the reconstituted data and not for an
1857 * individual gang member. The zio pipeline, however, must be able to
1858 * determine the checksum of each of the gang constituents so it
1859 * treats the checksum comparison differently than what we need
1860 * for l2arc blocks. This prevents us from using the
1861 * zio_checksum_error() interface directly. Instead we must call the
1862 * zio_checksum_error_impl() so that we can ensure the checksum is
1863 * generated using the correct checksum algorithm and accounts for the
1864 * logical I/O size and not just a gang fragment.
1866 valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1867 BP_GET_CHECKSUM(zio->io_bp), zio->io_data, zio->io_size,
1868 zio->io_offset, NULL) == 0);
1869 zio_pop_transforms(zio);
1870 return (valid_cksum);
1874 * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1875 * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1876 * isn't modified later on. If buf is compressed or there is already a checksum
1877 * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1880 arc_cksum_compute(arc_buf_t *buf)
1882 arc_buf_hdr_t *hdr = buf->b_hdr;
1884 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1887 ASSERT(HDR_HAS_L1HDR(hdr));
1889 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1890 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1891 ASSERT(arc_hdr_has_uncompressed_buf(hdr));
1892 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1894 } else if (ARC_BUF_COMPRESSED(buf)) {
1895 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1899 ASSERT(!ARC_BUF_COMPRESSED(buf));
1900 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1902 fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1903 hdr->b_l1hdr.b_freeze_cksum);
1904 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1912 typedef struct procctl {
1920 arc_buf_unwatch(arc_buf_t *buf)
1927 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1928 ctl.prwatch.pr_size = 0;
1929 ctl.prwatch.pr_wflags = 0;
1930 result = write(arc_procfd, &ctl, sizeof (ctl));
1931 ASSERT3U(result, ==, sizeof (ctl));
1938 arc_buf_watch(arc_buf_t *buf)
1945 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1946 ctl.prwatch.pr_size = arc_buf_size(buf);
1947 ctl.prwatch.pr_wflags = WA_WRITE;
1948 result = write(arc_procfd, &ctl, sizeof (ctl));
1949 ASSERT3U(result, ==, sizeof (ctl));
1953 #endif /* illumos */
1955 static arc_buf_contents_t
1956 arc_buf_type(arc_buf_hdr_t *hdr)
1958 arc_buf_contents_t type;
1959 if (HDR_ISTYPE_METADATA(hdr)) {
1960 type = ARC_BUFC_METADATA;
1962 type = ARC_BUFC_DATA;
1964 VERIFY3U(hdr->b_type, ==, type);
1969 arc_is_metadata(arc_buf_t *buf)
1971 return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1975 arc_bufc_to_flags(arc_buf_contents_t type)
1979 /* metadata field is 0 if buffer contains normal data */
1981 case ARC_BUFC_METADATA:
1982 return (ARC_FLAG_BUFC_METADATA);
1986 panic("undefined ARC buffer type!");
1987 return ((uint32_t)-1);
1991 arc_buf_thaw(arc_buf_t *buf)
1993 arc_buf_hdr_t *hdr = buf->b_hdr;
1995 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1996 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1998 arc_cksum_verify(buf);
2001 * Compressed buffers do not manipulate the b_freeze_cksum or
2002 * allocate b_thawed.
2004 if (ARC_BUF_COMPRESSED(buf)) {
2005 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2006 arc_hdr_has_uncompressed_buf(hdr));
2010 ASSERT(HDR_HAS_L1HDR(hdr));
2011 arc_cksum_free(hdr);
2013 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
2015 if (zfs_flags & ZFS_DEBUG_MODIFY) {
2016 if (hdr->b_l1hdr.b_thawed != NULL)
2017 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2018 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
2022 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2025 arc_buf_unwatch(buf);
2030 arc_buf_freeze(arc_buf_t *buf)
2032 arc_buf_hdr_t *hdr = buf->b_hdr;
2033 kmutex_t *hash_lock;
2035 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2038 if (ARC_BUF_COMPRESSED(buf)) {
2039 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2040 arc_hdr_has_uncompressed_buf(hdr));
2044 hash_lock = HDR_LOCK(hdr);
2045 mutex_enter(hash_lock);
2047 ASSERT(HDR_HAS_L1HDR(hdr));
2048 ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2049 hdr->b_l1hdr.b_state == arc_anon);
2050 arc_cksum_compute(buf);
2051 mutex_exit(hash_lock);
2055 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2056 * the following functions should be used to ensure that the flags are
2057 * updated in a thread-safe way. When manipulating the flags either
2058 * the hash_lock must be held or the hdr must be undiscoverable. This
2059 * ensures that we're not racing with any other threads when updating
2063 arc_hdr_set_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 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2072 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2073 hdr->b_flags &= ~flags;
2077 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2078 * done in a special way since we have to clear and set bits
2079 * at the same time. Consumers that wish to set the compression bits
2080 * must use this function to ensure that the flags are updated in
2081 * thread-safe manner.
2084 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2086 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2089 * Holes and embedded blocks will always have a psize = 0 so
2090 * we ignore the compression of the blkptr and set the
2091 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2092 * Holes and embedded blocks remain anonymous so we don't
2093 * want to uncompress them. Mark them as uncompressed.
2095 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2096 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2097 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
2098 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2099 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2101 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2102 HDR_SET_COMPRESS(hdr, cmp);
2103 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2104 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2109 * Looks for another buf on the same hdr which has the data decompressed, copies
2110 * from it, and returns true. If no such buf exists, returns false.
2113 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
2115 arc_buf_hdr_t *hdr = buf->b_hdr;
2116 boolean_t copied = B_FALSE;
2118 ASSERT(HDR_HAS_L1HDR(hdr));
2119 ASSERT3P(buf->b_data, !=, NULL);
2120 ASSERT(!ARC_BUF_COMPRESSED(buf));
2122 for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
2123 from = from->b_next) {
2124 /* can't use our own data buffer */
2129 if (!ARC_BUF_COMPRESSED(from)) {
2130 bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
2137 * There were no decompressed bufs, so there should not be a
2138 * checksum on the hdr either.
2140 EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
2146 * Given a buf that has a data buffer attached to it, this function will
2147 * efficiently fill the buf with data of the specified compression setting from
2148 * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2149 * are already sharing a data buf, no copy is performed.
2151 * If the buf is marked as compressed but uncompressed data was requested, this
2152 * will allocate a new data buffer for the buf, remove that flag, and fill the
2153 * buf with uncompressed data. You can't request a compressed buf on a hdr with
2154 * uncompressed data, and (since we haven't added support for it yet) if you
2155 * want compressed data your buf must already be marked as compressed and have
2156 * the correct-sized data buffer.
2159 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
2161 arc_buf_hdr_t *hdr = buf->b_hdr;
2162 boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2163 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2165 ASSERT3P(buf->b_data, !=, NULL);
2166 IMPLY(compressed, hdr_compressed);
2167 IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2169 if (hdr_compressed == compressed) {
2170 if (!arc_buf_is_shared(buf)) {
2171 bcopy(hdr->b_l1hdr.b_pdata, buf->b_data,
2175 ASSERT(hdr_compressed);
2176 ASSERT(!compressed);
2177 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2180 * If the buf is sharing its data with the hdr, unlink it and
2181 * allocate a new data buffer for the buf.
2183 if (arc_buf_is_shared(buf)) {
2184 ASSERT(ARC_BUF_COMPRESSED(buf));
2186 /* We need to give the buf it's own b_data */
2187 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2189 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2190 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2192 /* Previously overhead was 0; just add new overhead */
2193 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2194 } else if (ARC_BUF_COMPRESSED(buf)) {
2195 /* We need to reallocate the buf's b_data */
2196 arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2199 arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2201 /* We increased the size of b_data; update overhead */
2202 ARCSTAT_INCR(arcstat_overhead_size,
2203 HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2207 * Regardless of the buf's previous compression settings, it
2208 * should not be compressed at the end of this function.
2210 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2213 * Try copying the data from another buf which already has a
2214 * decompressed version. If that's not possible, it's time to
2215 * bite the bullet and decompress the data from the hdr.
2217 if (arc_buf_try_copy_decompressed_data(buf)) {
2218 /* Skip byteswapping and checksumming (already done) */
2219 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
2222 int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2223 hdr->b_l1hdr.b_pdata, buf->b_data,
2224 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2227 * Absent hardware errors or software bugs, this should
2228 * be impossible, but log it anyway so we can debug it.
2232 "hdr %p, compress %d, psize %d, lsize %d",
2233 hdr, HDR_GET_COMPRESS(hdr),
2234 HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2235 return (SET_ERROR(EIO));
2240 /* Byteswap the buf's data if necessary */
2241 if (bswap != DMU_BSWAP_NUMFUNCS) {
2242 ASSERT(!HDR_SHARED_DATA(hdr));
2243 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2244 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2247 /* Compute the hdr's checksum if necessary */
2248 arc_cksum_compute(buf);
2254 arc_decompress(arc_buf_t *buf)
2256 return (arc_buf_fill(buf, B_FALSE));
2260 * Return the size of the block, b_pdata, that is stored in the arc_buf_hdr_t.
2263 arc_hdr_size(arc_buf_hdr_t *hdr)
2267 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2268 HDR_GET_PSIZE(hdr) > 0) {
2269 size = HDR_GET_PSIZE(hdr);
2271 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2272 size = HDR_GET_LSIZE(hdr);
2278 * Increment the amount of evictable space in the arc_state_t's refcount.
2279 * We account for the space used by the hdr and the arc buf individually
2280 * so that we can add and remove them from the refcount individually.
2283 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2285 arc_buf_contents_t type = arc_buf_type(hdr);
2287 ASSERT(HDR_HAS_L1HDR(hdr));
2289 if (GHOST_STATE(state)) {
2290 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2291 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2292 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2293 (void) refcount_add_many(&state->arcs_esize[type],
2294 HDR_GET_LSIZE(hdr), hdr);
2298 ASSERT(!GHOST_STATE(state));
2299 if (hdr->b_l1hdr.b_pdata != NULL) {
2300 (void) refcount_add_many(&state->arcs_esize[type],
2301 arc_hdr_size(hdr), hdr);
2303 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2304 buf = buf->b_next) {
2305 if (arc_buf_is_shared(buf))
2307 (void) refcount_add_many(&state->arcs_esize[type],
2308 arc_buf_size(buf), buf);
2313 * Decrement the amount of evictable space in the arc_state_t's refcount.
2314 * We account for the space used by the hdr and the arc buf individually
2315 * so that we can add and remove them from the refcount individually.
2318 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2320 arc_buf_contents_t type = arc_buf_type(hdr);
2322 ASSERT(HDR_HAS_L1HDR(hdr));
2324 if (GHOST_STATE(state)) {
2325 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2326 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2327 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2328 (void) refcount_remove_many(&state->arcs_esize[type],
2329 HDR_GET_LSIZE(hdr), hdr);
2333 ASSERT(!GHOST_STATE(state));
2334 if (hdr->b_l1hdr.b_pdata != NULL) {
2335 (void) refcount_remove_many(&state->arcs_esize[type],
2336 arc_hdr_size(hdr), hdr);
2338 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2339 buf = buf->b_next) {
2340 if (arc_buf_is_shared(buf))
2342 (void) refcount_remove_many(&state->arcs_esize[type],
2343 arc_buf_size(buf), buf);
2348 * Add a reference to this hdr indicating that someone is actively
2349 * referencing that memory. When the refcount transitions from 0 to 1,
2350 * we remove it from the respective arc_state_t list to indicate that
2351 * it is not evictable.
2354 add_reference(arc_buf_hdr_t *hdr, void *tag)
2356 ASSERT(HDR_HAS_L1HDR(hdr));
2357 if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2358 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2359 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2360 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2363 arc_state_t *state = hdr->b_l1hdr.b_state;
2365 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2366 (state != arc_anon)) {
2367 /* We don't use the L2-only state list. */
2368 if (state != arc_l2c_only) {
2369 multilist_remove(&state->arcs_list[arc_buf_type(hdr)],
2371 arc_evictable_space_decrement(hdr, state);
2373 /* remove the prefetch flag if we get a reference */
2374 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2379 * Remove a reference from this hdr. When the reference transitions from
2380 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2381 * list making it eligible for eviction.
2384 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2387 arc_state_t *state = hdr->b_l1hdr.b_state;
2389 ASSERT(HDR_HAS_L1HDR(hdr));
2390 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2391 ASSERT(!GHOST_STATE(state));
2394 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2395 * check to prevent usage of the arc_l2c_only list.
2397 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2398 (state != arc_anon)) {
2399 multilist_insert(&state->arcs_list[arc_buf_type(hdr)], hdr);
2400 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2401 arc_evictable_space_increment(hdr, state);
2407 * Move the supplied buffer to the indicated state. The hash lock
2408 * for the buffer must be held by the caller.
2411 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2412 kmutex_t *hash_lock)
2414 arc_state_t *old_state;
2417 boolean_t update_old, update_new;
2418 arc_buf_contents_t buftype = arc_buf_type(hdr);
2421 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2422 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2423 * L1 hdr doesn't always exist when we change state to arc_anon before
2424 * destroying a header, in which case reallocating to add the L1 hdr is
2427 if (HDR_HAS_L1HDR(hdr)) {
2428 old_state = hdr->b_l1hdr.b_state;
2429 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2430 bufcnt = hdr->b_l1hdr.b_bufcnt;
2431 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pdata != NULL);
2433 old_state = arc_l2c_only;
2436 update_old = B_FALSE;
2438 update_new = update_old;
2440 ASSERT(MUTEX_HELD(hash_lock));
2441 ASSERT3P(new_state, !=, old_state);
2442 ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2443 ASSERT(old_state != arc_anon || bufcnt <= 1);
2446 * If this buffer is evictable, transfer it from the
2447 * old state list to the new state list.
2450 if (old_state != arc_anon && old_state != arc_l2c_only) {
2451 ASSERT(HDR_HAS_L1HDR(hdr));
2452 multilist_remove(&old_state->arcs_list[buftype], hdr);
2454 if (GHOST_STATE(old_state)) {
2456 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2457 update_old = B_TRUE;
2459 arc_evictable_space_decrement(hdr, old_state);
2461 if (new_state != arc_anon && new_state != arc_l2c_only) {
2464 * An L1 header always exists here, since if we're
2465 * moving to some L1-cached state (i.e. not l2c_only or
2466 * anonymous), we realloc the header to add an L1hdr
2469 ASSERT(HDR_HAS_L1HDR(hdr));
2470 multilist_insert(&new_state->arcs_list[buftype], hdr);
2472 if (GHOST_STATE(new_state)) {
2474 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2475 update_new = B_TRUE;
2477 arc_evictable_space_increment(hdr, new_state);
2481 ASSERT(!HDR_EMPTY(hdr));
2482 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2483 buf_hash_remove(hdr);
2485 /* adjust state sizes (ignore arc_l2c_only) */
2487 if (update_new && new_state != arc_l2c_only) {
2488 ASSERT(HDR_HAS_L1HDR(hdr));
2489 if (GHOST_STATE(new_state)) {
2493 * When moving a header to a ghost state, we first
2494 * remove all arc buffers. Thus, we'll have a
2495 * bufcnt of zero, and no arc buffer to use for
2496 * the reference. As a result, we use the arc
2497 * header pointer for the reference.
2499 (void) refcount_add_many(&new_state->arcs_size,
2500 HDR_GET_LSIZE(hdr), hdr);
2501 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2503 uint32_t buffers = 0;
2506 * Each individual buffer holds a unique reference,
2507 * thus we must remove each of these references one
2510 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2511 buf = buf->b_next) {
2512 ASSERT3U(bufcnt, !=, 0);
2516 * When the arc_buf_t is sharing the data
2517 * block with the hdr, the owner of the
2518 * reference belongs to the hdr. Only
2519 * add to the refcount if the arc_buf_t is
2522 if (arc_buf_is_shared(buf))
2525 (void) refcount_add_many(&new_state->arcs_size,
2526 arc_buf_size(buf), buf);
2528 ASSERT3U(bufcnt, ==, buffers);
2530 if (hdr->b_l1hdr.b_pdata != NULL) {
2531 (void) refcount_add_many(&new_state->arcs_size,
2532 arc_hdr_size(hdr), hdr);
2534 ASSERT(GHOST_STATE(old_state));
2539 if (update_old && old_state != arc_l2c_only) {
2540 ASSERT(HDR_HAS_L1HDR(hdr));
2541 if (GHOST_STATE(old_state)) {
2543 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2546 * When moving a header off of a ghost state,
2547 * the header will not contain any arc buffers.
2548 * We use the arc header pointer for the reference
2549 * which is exactly what we did when we put the
2550 * header on the ghost state.
2553 (void) refcount_remove_many(&old_state->arcs_size,
2554 HDR_GET_LSIZE(hdr), hdr);
2556 uint32_t buffers = 0;
2559 * Each individual buffer holds a unique reference,
2560 * thus we must remove each of these references one
2563 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2564 buf = buf->b_next) {
2565 ASSERT3U(bufcnt, !=, 0);
2569 * When the arc_buf_t is sharing the data
2570 * block with the hdr, the owner of the
2571 * reference belongs to the hdr. Only
2572 * add to the refcount if the arc_buf_t is
2575 if (arc_buf_is_shared(buf))
2578 (void) refcount_remove_many(
2579 &old_state->arcs_size, arc_buf_size(buf),
2582 ASSERT3U(bufcnt, ==, buffers);
2583 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2584 (void) refcount_remove_many(
2585 &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2589 if (HDR_HAS_L1HDR(hdr))
2590 hdr->b_l1hdr.b_state = new_state;
2593 * L2 headers should never be on the L2 state list since they don't
2594 * have L1 headers allocated.
2596 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2597 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2601 arc_space_consume(uint64_t space, arc_space_type_t type)
2603 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2606 case ARC_SPACE_DATA:
2607 ARCSTAT_INCR(arcstat_data_size, space);
2609 case ARC_SPACE_META:
2610 ARCSTAT_INCR(arcstat_metadata_size, space);
2612 case ARC_SPACE_OTHER:
2613 ARCSTAT_INCR(arcstat_other_size, space);
2615 case ARC_SPACE_HDRS:
2616 ARCSTAT_INCR(arcstat_hdr_size, space);
2618 case ARC_SPACE_L2HDRS:
2619 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
2623 if (type != ARC_SPACE_DATA)
2624 ARCSTAT_INCR(arcstat_meta_used, space);
2626 atomic_add_64(&arc_size, space);
2630 arc_space_return(uint64_t space, arc_space_type_t type)
2632 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2635 case ARC_SPACE_DATA:
2636 ARCSTAT_INCR(arcstat_data_size, -space);
2638 case ARC_SPACE_META:
2639 ARCSTAT_INCR(arcstat_metadata_size, -space);
2641 case ARC_SPACE_OTHER:
2642 ARCSTAT_INCR(arcstat_other_size, -space);
2644 case ARC_SPACE_HDRS:
2645 ARCSTAT_INCR(arcstat_hdr_size, -space);
2647 case ARC_SPACE_L2HDRS:
2648 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2652 if (type != ARC_SPACE_DATA) {
2653 ASSERT(arc_meta_used >= space);
2654 if (arc_meta_max < arc_meta_used)
2655 arc_meta_max = arc_meta_used;
2656 ARCSTAT_INCR(arcstat_meta_used, -space);
2659 ASSERT(arc_size >= space);
2660 atomic_add_64(&arc_size, -space);
2664 * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2665 * with the hdr's b_pdata.
2668 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2671 * The criteria for sharing a hdr's data are:
2672 * 1. the hdr's compression matches the buf's compression
2673 * 2. the hdr doesn't need to be byteswapped
2674 * 3. the hdr isn't already being shared
2675 * 4. the buf is either compressed or it is the last buf in the hdr list
2677 * Criterion #4 maintains the invariant that shared uncompressed
2678 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2679 * might ask, "if a compressed buf is allocated first, won't that be the
2680 * last thing in the list?", but in that case it's impossible to create
2681 * a shared uncompressed buf anyway (because the hdr must be compressed
2682 * to have the compressed buf). You might also think that #3 is
2683 * sufficient to make this guarantee, however it's possible
2684 * (specifically in the rare L2ARC write race mentioned in
2685 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2686 * is sharable, but wasn't at the time of its allocation. Rather than
2687 * allow a new shared uncompressed buf to be created and then shuffle
2688 * the list around to make it the last element, this simply disallows
2689 * sharing if the new buf isn't the first to be added.
2691 ASSERT3P(buf->b_hdr, ==, hdr);
2692 boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2693 boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2694 return (buf_compressed == hdr_compressed &&
2695 hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2696 !HDR_SHARED_DATA(hdr) &&
2697 (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2701 * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2702 * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2703 * copy was made successfully, or an error code otherwise.
2706 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2707 boolean_t fill, arc_buf_t **ret)
2711 ASSERT(HDR_HAS_L1HDR(hdr));
2712 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2713 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2714 hdr->b_type == ARC_BUFC_METADATA);
2715 ASSERT3P(ret, !=, NULL);
2716 ASSERT3P(*ret, ==, NULL);
2718 buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2721 buf->b_next = hdr->b_l1hdr.b_buf;
2724 add_reference(hdr, tag);
2727 * We're about to change the hdr's b_flags. We must either
2728 * hold the hash_lock or be undiscoverable.
2730 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2733 * Only honor requests for compressed bufs if the hdr is actually
2736 if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2737 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2740 * If the hdr's data can be shared then we share the data buffer and
2741 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2742 * sharing it's b_pdata with the arc_buf_t. Otherwise, we allocate a new
2743 * buffer to store the buf's data.
2745 * There is one additional restriction here because we're sharing
2746 * hdr -> buf instead of the usual buf -> hdr: the hdr can't be actively
2747 * involved in an L2ARC write, because if this buf is used by an
2748 * arc_write() then the hdr's data buffer will be released when the
2749 * write completes, even though the L2ARC write might still be using it.
2751 boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr);
2753 /* Set up b_data and sharing */
2755 buf->b_data = hdr->b_l1hdr.b_pdata;
2756 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2757 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2760 arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2761 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2763 VERIFY3P(buf->b_data, !=, NULL);
2765 hdr->b_l1hdr.b_buf = buf;
2766 hdr->b_l1hdr.b_bufcnt += 1;
2769 * If the user wants the data from the hdr, we need to either copy or
2770 * decompress the data.
2773 return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
2779 static char *arc_onloan_tag = "onloan";
2782 arc_loaned_bytes_update(int64_t delta)
2784 atomic_add_64(&arc_loaned_bytes, delta);
2786 /* assert that it did not wrap around */
2787 ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2791 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2792 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2793 * buffers must be returned to the arc before they can be used by the DMU or
2797 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2799 arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2800 is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2802 arc_loaned_bytes_update(size);
2808 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2809 enum zio_compress compression_type)
2811 arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2812 psize, lsize, compression_type);
2814 arc_loaned_bytes_update(psize);
2821 * Return a loaned arc buffer to the arc.
2824 arc_return_buf(arc_buf_t *buf, void *tag)
2826 arc_buf_hdr_t *hdr = buf->b_hdr;
2828 ASSERT3P(buf->b_data, !=, NULL);
2829 ASSERT(HDR_HAS_L1HDR(hdr));
2830 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2831 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2833 arc_loaned_bytes_update(-arc_buf_size(buf));
2836 /* Detach an arc_buf from a dbuf (tag) */
2838 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2840 arc_buf_hdr_t *hdr = buf->b_hdr;
2842 ASSERT3P(buf->b_data, !=, NULL);
2843 ASSERT(HDR_HAS_L1HDR(hdr));
2844 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2845 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2847 arc_loaned_bytes_update(arc_buf_size(buf));
2851 l2arc_free_data_on_write(void *data, size_t size, arc_buf_contents_t type)
2853 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2855 df->l2df_data = data;
2856 df->l2df_size = size;
2857 df->l2df_type = type;
2858 mutex_enter(&l2arc_free_on_write_mtx);
2859 list_insert_head(l2arc_free_on_write, df);
2860 mutex_exit(&l2arc_free_on_write_mtx);
2864 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2866 arc_state_t *state = hdr->b_l1hdr.b_state;
2867 arc_buf_contents_t type = arc_buf_type(hdr);
2868 uint64_t size = arc_hdr_size(hdr);
2870 /* protected by hash lock, if in the hash table */
2871 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2872 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2873 ASSERT(state != arc_anon && state != arc_l2c_only);
2875 (void) refcount_remove_many(&state->arcs_esize[type],
2878 (void) refcount_remove_many(&state->arcs_size, size, hdr);
2879 if (type == ARC_BUFC_METADATA) {
2880 arc_space_return(size, ARC_SPACE_META);
2882 ASSERT(type == ARC_BUFC_DATA);
2883 arc_space_return(size, ARC_SPACE_DATA);
2886 l2arc_free_data_on_write(hdr->b_l1hdr.b_pdata, size, type);
2890 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2891 * data buffer, we transfer the refcount ownership to the hdr and update
2892 * the appropriate kstats.
2895 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2897 arc_state_t *state = hdr->b_l1hdr.b_state;
2899 ASSERT(arc_can_share(hdr, buf));
2900 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2901 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2904 * Start sharing the data buffer. We transfer the
2905 * refcount ownership to the hdr since it always owns
2906 * the refcount whenever an arc_buf_t is shared.
2908 refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2909 hdr->b_l1hdr.b_pdata = buf->b_data;
2910 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2911 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2914 * Since we've transferred ownership to the hdr we need
2915 * to increment its compressed and uncompressed kstats and
2916 * decrement the overhead size.
2918 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2919 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2920 ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2924 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2926 arc_state_t *state = hdr->b_l1hdr.b_state;
2928 ASSERT(arc_buf_is_shared(buf));
2929 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2930 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2933 * We are no longer sharing this buffer so we need
2934 * to transfer its ownership to the rightful owner.
2936 refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2937 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2938 hdr->b_l1hdr.b_pdata = NULL;
2939 buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2942 * Since the buffer is no longer shared between
2943 * the arc buf and the hdr, count it as overhead.
2945 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2946 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2947 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2951 * Remove an arc_buf_t from the hdr's buf list and return the last
2952 * arc_buf_t on the list. If no buffers remain on the list then return
2956 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2958 ASSERT(HDR_HAS_L1HDR(hdr));
2959 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2961 arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
2962 arc_buf_t *lastbuf = NULL;
2965 * Remove the buf from the hdr list and locate the last
2966 * remaining buffer on the list.
2968 while (*bufp != NULL) {
2970 *bufp = buf->b_next;
2973 * If we've removed a buffer in the middle of
2974 * the list then update the lastbuf and update
2977 if (*bufp != NULL) {
2979 bufp = &(*bufp)->b_next;
2983 ASSERT3P(lastbuf, !=, buf);
2984 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
2985 IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
2986 IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
2992 * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
2996 arc_buf_destroy_impl(arc_buf_t *buf)
2998 arc_buf_hdr_t *hdr = buf->b_hdr;
3001 * Free up the data associated with the buf but only if we're not
3002 * sharing this with the hdr. If we are sharing it with the hdr, the
3003 * hdr is responsible for doing the free.
3005 if (buf->b_data != NULL) {
3007 * We're about to change the hdr's b_flags. We must either
3008 * hold the hash_lock or be undiscoverable.
3010 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3012 arc_cksum_verify(buf);
3014 arc_buf_unwatch(buf);
3017 if (arc_buf_is_shared(buf)) {
3018 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3020 uint64_t size = arc_buf_size(buf);
3021 arc_free_data_buf(hdr, buf->b_data, size, buf);
3022 ARCSTAT_INCR(arcstat_overhead_size, -size);
3026 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3027 hdr->b_l1hdr.b_bufcnt -= 1;
3030 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3032 if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3034 * If the current arc_buf_t is sharing its data buffer with the
3035 * hdr, then reassign the hdr's b_pdata to share it with the new
3036 * buffer at the end of the list. The shared buffer is always
3037 * the last one on the hdr's buffer list.
3039 * There is an equivalent case for compressed bufs, but since
3040 * they aren't guaranteed to be the last buf in the list and
3041 * that is an exceedingly rare case, we just allow that space be
3042 * wasted temporarily.
3044 if (lastbuf != NULL) {
3045 /* Only one buf can be shared at once */
3046 VERIFY(!arc_buf_is_shared(lastbuf));
3047 /* hdr is uncompressed so can't have compressed buf */
3048 VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3050 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
3051 arc_hdr_free_pdata(hdr);
3054 * We must setup a new shared block between the
3055 * last buffer and the hdr. The data would have
3056 * been allocated by the arc buf so we need to transfer
3057 * ownership to the hdr since it's now being shared.
3059 arc_share_buf(hdr, lastbuf);
3061 } else if (HDR_SHARED_DATA(hdr)) {
3063 * Uncompressed shared buffers are always at the end
3064 * of the list. Compressed buffers don't have the
3065 * same requirements. This makes it hard to
3066 * simply assert that the lastbuf is shared so
3067 * we rely on the hdr's compression flags to determine
3068 * if we have a compressed, shared buffer.
3070 ASSERT3P(lastbuf, !=, NULL);
3071 ASSERT(arc_buf_is_shared(lastbuf) ||
3072 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
3076 * Free the checksum if we're removing the last uncompressed buf from
3079 if (!arc_hdr_has_uncompressed_buf(hdr)) {
3080 arc_cksum_free(hdr);
3083 /* clean up the buf */
3085 kmem_cache_free(buf_cache, buf);
3089 arc_hdr_alloc_pdata(arc_buf_hdr_t *hdr)
3091 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3092 ASSERT(HDR_HAS_L1HDR(hdr));
3093 ASSERT(!HDR_SHARED_DATA(hdr));
3095 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3096 hdr->b_l1hdr.b_pdata = arc_get_data_buf(hdr, arc_hdr_size(hdr), hdr);
3097 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3098 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
3100 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3101 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3105 arc_hdr_free_pdata(arc_buf_hdr_t *hdr)
3107 ASSERT(HDR_HAS_L1HDR(hdr));
3108 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
3111 * If the hdr is currently being written to the l2arc then
3112 * we defer freeing the data by adding it to the l2arc_free_on_write
3113 * list. The l2arc will free the data once it's finished
3114 * writing it to the l2arc device.
3116 if (HDR_L2_WRITING(hdr)) {
3117 arc_hdr_free_on_write(hdr);
3118 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3120 arc_free_data_buf(hdr, hdr->b_l1hdr.b_pdata,
3121 arc_hdr_size(hdr), hdr);
3123 hdr->b_l1hdr.b_pdata = NULL;
3124 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3126 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3127 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3130 static arc_buf_hdr_t *
3131 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3132 enum zio_compress compression_type, arc_buf_contents_t type)
3136 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3138 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3139 ASSERT(HDR_EMPTY(hdr));
3140 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3141 ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3142 HDR_SET_PSIZE(hdr, psize);
3143 HDR_SET_LSIZE(hdr, lsize);
3147 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3148 arc_hdr_set_compress(hdr, compression_type);
3150 hdr->b_l1hdr.b_state = arc_anon;
3151 hdr->b_l1hdr.b_arc_access = 0;
3152 hdr->b_l1hdr.b_bufcnt = 0;
3153 hdr->b_l1hdr.b_buf = NULL;
3156 * Allocate the hdr's buffer. This will contain either
3157 * the compressed or uncompressed data depending on the block
3158 * it references and compressed arc enablement.
3160 arc_hdr_alloc_pdata(hdr);
3161 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3167 * Transition between the two allocation states for the arc_buf_hdr struct.
3168 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3169 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3170 * version is used when a cache buffer is only in the L2ARC in order to reduce
3173 static arc_buf_hdr_t *
3174 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3176 ASSERT(HDR_HAS_L2HDR(hdr));
3178 arc_buf_hdr_t *nhdr;
3179 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3181 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3182 (old == hdr_l2only_cache && new == hdr_full_cache));
3184 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3186 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3187 buf_hash_remove(hdr);
3189 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3191 if (new == hdr_full_cache) {
3192 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3194 * arc_access and arc_change_state need to be aware that a
3195 * header has just come out of L2ARC, so we set its state to
3196 * l2c_only even though it's about to change.
3198 nhdr->b_l1hdr.b_state = arc_l2c_only;
3200 /* Verify previous threads set to NULL before freeing */
3201 ASSERT3P(nhdr->b_l1hdr.b_pdata, ==, NULL);
3203 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3204 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3205 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3208 * If we've reached here, We must have been called from
3209 * arc_evict_hdr(), as such we should have already been
3210 * removed from any ghost list we were previously on
3211 * (which protects us from racing with arc_evict_state),
3212 * thus no locking is needed during this check.
3214 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3217 * A buffer must not be moved into the arc_l2c_only
3218 * state if it's not finished being written out to the
3219 * l2arc device. Otherwise, the b_l1hdr.b_pdata field
3220 * might try to be accessed, even though it was removed.
3222 VERIFY(!HDR_L2_WRITING(hdr));
3223 VERIFY3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3226 if (hdr->b_l1hdr.b_thawed != NULL) {
3227 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3228 hdr->b_l1hdr.b_thawed = NULL;
3232 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3235 * The header has been reallocated so we need to re-insert it into any
3238 (void) buf_hash_insert(nhdr, NULL);
3240 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3242 mutex_enter(&dev->l2ad_mtx);
3245 * We must place the realloc'ed header back into the list at
3246 * the same spot. Otherwise, if it's placed earlier in the list,
3247 * l2arc_write_buffers() could find it during the function's
3248 * write phase, and try to write it out to the l2arc.
3250 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3251 list_remove(&dev->l2ad_buflist, hdr);
3253 mutex_exit(&dev->l2ad_mtx);
3256 * Since we're using the pointer address as the tag when
3257 * incrementing and decrementing the l2ad_alloc refcount, we
3258 * must remove the old pointer (that we're about to destroy) and
3259 * add the new pointer to the refcount. Otherwise we'd remove
3260 * the wrong pointer address when calling arc_hdr_destroy() later.
3263 (void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3264 (void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3266 buf_discard_identity(hdr);
3267 kmem_cache_free(old, hdr);
3273 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3274 * The buf is returned thawed since we expect the consumer to modify it.
3277 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3279 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3280 ZIO_COMPRESS_OFF, type);
3281 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3283 arc_buf_t *buf = NULL;
3284 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3291 * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3292 * for bufs containing metadata.
3295 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3296 enum zio_compress compression_type)
3298 ASSERT3U(lsize, >, 0);
3299 ASSERT3U(lsize, >=, psize);
3300 ASSERT(compression_type > ZIO_COMPRESS_OFF);
3301 ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3303 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3304 compression_type, ARC_BUFC_DATA);
3305 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3307 arc_buf_t *buf = NULL;
3308 VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3310 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3316 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3318 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3319 l2arc_dev_t *dev = l2hdr->b_dev;
3320 uint64_t asize = arc_hdr_size(hdr);
3322 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3323 ASSERT(HDR_HAS_L2HDR(hdr));
3325 list_remove(&dev->l2ad_buflist, hdr);
3327 ARCSTAT_INCR(arcstat_l2_asize, -asize);
3328 ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
3330 vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3332 (void) refcount_remove_many(&dev->l2ad_alloc, asize, hdr);
3333 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3337 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3339 if (HDR_HAS_L1HDR(hdr)) {
3340 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3341 hdr->b_l1hdr.b_bufcnt > 0);
3342 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3343 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3345 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3346 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3348 if (!HDR_EMPTY(hdr))
3349 buf_discard_identity(hdr);
3351 if (HDR_HAS_L2HDR(hdr)) {
3352 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3353 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3356 mutex_enter(&dev->l2ad_mtx);
3359 * Even though we checked this conditional above, we
3360 * need to check this again now that we have the
3361 * l2ad_mtx. This is because we could be racing with
3362 * another thread calling l2arc_evict() which might have
3363 * destroyed this header's L2 portion as we were waiting
3364 * to acquire the l2ad_mtx. If that happens, we don't
3365 * want to re-destroy the header's L2 portion.
3367 if (HDR_HAS_L2HDR(hdr)) {
3369 arc_hdr_l2hdr_destroy(hdr);
3373 mutex_exit(&dev->l2ad_mtx);
3376 if (HDR_HAS_L1HDR(hdr)) {
3377 arc_cksum_free(hdr);
3379 while (hdr->b_l1hdr.b_buf != NULL)
3380 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3383 if (hdr->b_l1hdr.b_thawed != NULL) {
3384 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3385 hdr->b_l1hdr.b_thawed = NULL;
3389 if (hdr->b_l1hdr.b_pdata != NULL) {
3390 arc_hdr_free_pdata(hdr);
3394 ASSERT3P(hdr->b_hash_next, ==, NULL);
3395 if (HDR_HAS_L1HDR(hdr)) {
3396 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3397 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3398 kmem_cache_free(hdr_full_cache, hdr);
3400 kmem_cache_free(hdr_l2only_cache, hdr);
3405 arc_buf_destroy(arc_buf_t *buf, void* tag)
3407 arc_buf_hdr_t *hdr = buf->b_hdr;
3408 kmutex_t *hash_lock = HDR_LOCK(hdr);
3410 if (hdr->b_l1hdr.b_state == arc_anon) {
3411 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3412 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3413 VERIFY0(remove_reference(hdr, NULL, tag));
3414 arc_hdr_destroy(hdr);
3418 mutex_enter(hash_lock);
3419 ASSERT3P(hdr, ==, buf->b_hdr);
3420 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3421 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3422 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3423 ASSERT3P(buf->b_data, !=, NULL);
3425 (void) remove_reference(hdr, hash_lock, tag);
3426 arc_buf_destroy_impl(buf);
3427 mutex_exit(hash_lock);
3431 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3432 * state of the header is dependent on its state prior to entering this
3433 * function. The following transitions are possible:
3435 * - arc_mru -> arc_mru_ghost
3436 * - arc_mfu -> arc_mfu_ghost
3437 * - arc_mru_ghost -> arc_l2c_only
3438 * - arc_mru_ghost -> deleted
3439 * - arc_mfu_ghost -> arc_l2c_only
3440 * - arc_mfu_ghost -> deleted
3443 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3445 arc_state_t *evicted_state, *state;
3446 int64_t bytes_evicted = 0;
3448 ASSERT(MUTEX_HELD(hash_lock));
3449 ASSERT(HDR_HAS_L1HDR(hdr));
3451 state = hdr->b_l1hdr.b_state;
3452 if (GHOST_STATE(state)) {
3453 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3454 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3457 * l2arc_write_buffers() relies on a header's L1 portion
3458 * (i.e. its b_pdata field) during its write phase.
3459 * Thus, we cannot push a header onto the arc_l2c_only
3460 * state (removing it's L1 piece) until the header is
3461 * done being written to the l2arc.
3463 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3464 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3465 return (bytes_evicted);
3468 ARCSTAT_BUMP(arcstat_deleted);
3469 bytes_evicted += HDR_GET_LSIZE(hdr);
3471 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3473 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3474 if (HDR_HAS_L2HDR(hdr)) {
3476 * This buffer is cached on the 2nd Level ARC;
3477 * don't destroy the header.
3479 arc_change_state(arc_l2c_only, hdr, hash_lock);
3481 * dropping from L1+L2 cached to L2-only,
3482 * realloc to remove the L1 header.
3484 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3487 arc_change_state(arc_anon, hdr, hash_lock);
3488 arc_hdr_destroy(hdr);
3490 return (bytes_evicted);
3493 ASSERT(state == arc_mru || state == arc_mfu);
3494 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3496 /* prefetch buffers have a minimum lifespan */
3497 if (HDR_IO_IN_PROGRESS(hdr) ||
3498 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3499 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3500 arc_min_prefetch_lifespan)) {
3501 ARCSTAT_BUMP(arcstat_evict_skip);
3502 return (bytes_evicted);
3505 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3506 while (hdr->b_l1hdr.b_buf) {
3507 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3508 if (!mutex_tryenter(&buf->b_evict_lock)) {
3509 ARCSTAT_BUMP(arcstat_mutex_miss);
3512 if (buf->b_data != NULL)
3513 bytes_evicted += HDR_GET_LSIZE(hdr);
3514 mutex_exit(&buf->b_evict_lock);
3515 arc_buf_destroy_impl(buf);
3518 if (HDR_HAS_L2HDR(hdr)) {
3519 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3521 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3522 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3523 HDR_GET_LSIZE(hdr));
3525 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3526 HDR_GET_LSIZE(hdr));
3530 if (hdr->b_l1hdr.b_bufcnt == 0) {
3531 arc_cksum_free(hdr);
3533 bytes_evicted += arc_hdr_size(hdr);
3536 * If this hdr is being evicted and has a compressed
3537 * buffer then we discard it here before we change states.
3538 * This ensures that the accounting is updated correctly
3539 * in arc_free_data_buf().
3541 arc_hdr_free_pdata(hdr);
3543 arc_change_state(evicted_state, hdr, hash_lock);
3544 ASSERT(HDR_IN_HASH_TABLE(hdr));
3545 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3546 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3549 return (bytes_evicted);
3553 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3554 uint64_t spa, int64_t bytes)
3556 multilist_sublist_t *mls;
3557 uint64_t bytes_evicted = 0;
3559 kmutex_t *hash_lock;
3560 int evict_count = 0;
3562 ASSERT3P(marker, !=, NULL);
3563 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3565 mls = multilist_sublist_lock(ml, idx);
3567 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3568 hdr = multilist_sublist_prev(mls, marker)) {
3569 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3570 (evict_count >= zfs_arc_evict_batch_limit))
3574 * To keep our iteration location, move the marker
3575 * forward. Since we're not holding hdr's hash lock, we
3576 * must be very careful and not remove 'hdr' from the
3577 * sublist. Otherwise, other consumers might mistake the
3578 * 'hdr' as not being on a sublist when they call the
3579 * multilist_link_active() function (they all rely on
3580 * the hash lock protecting concurrent insertions and
3581 * removals). multilist_sublist_move_forward() was
3582 * specifically implemented to ensure this is the case
3583 * (only 'marker' will be removed and re-inserted).
3585 multilist_sublist_move_forward(mls, marker);
3588 * The only case where the b_spa field should ever be
3589 * zero, is the marker headers inserted by
3590 * arc_evict_state(). It's possible for multiple threads
3591 * to be calling arc_evict_state() concurrently (e.g.
3592 * dsl_pool_close() and zio_inject_fault()), so we must
3593 * skip any markers we see from these other threads.
3595 if (hdr->b_spa == 0)
3598 /* we're only interested in evicting buffers of a certain spa */
3599 if (spa != 0 && hdr->b_spa != spa) {
3600 ARCSTAT_BUMP(arcstat_evict_skip);
3604 hash_lock = HDR_LOCK(hdr);
3607 * We aren't calling this function from any code path
3608 * that would already be holding a hash lock, so we're
3609 * asserting on this assumption to be defensive in case
3610 * this ever changes. Without this check, it would be
3611 * possible to incorrectly increment arcstat_mutex_miss
3612 * below (e.g. if the code changed such that we called
3613 * this function with a hash lock held).
3615 ASSERT(!MUTEX_HELD(hash_lock));
3617 if (mutex_tryenter(hash_lock)) {
3618 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3619 mutex_exit(hash_lock);
3621 bytes_evicted += evicted;
3624 * If evicted is zero, arc_evict_hdr() must have
3625 * decided to skip this header, don't increment
3626 * evict_count in this case.
3632 * If arc_size isn't overflowing, signal any
3633 * threads that might happen to be waiting.
3635 * For each header evicted, we wake up a single
3636 * thread. If we used cv_broadcast, we could
3637 * wake up "too many" threads causing arc_size
3638 * to significantly overflow arc_c; since
3639 * arc_get_data_buf() doesn't check for overflow
3640 * when it's woken up (it doesn't because it's
3641 * possible for the ARC to be overflowing while
3642 * full of un-evictable buffers, and the
3643 * function should proceed in this case).
3645 * If threads are left sleeping, due to not
3646 * using cv_broadcast, they will be woken up
3647 * just before arc_reclaim_thread() sleeps.
3649 mutex_enter(&arc_reclaim_lock);
3650 if (!arc_is_overflowing())
3651 cv_signal(&arc_reclaim_waiters_cv);
3652 mutex_exit(&arc_reclaim_lock);
3654 ARCSTAT_BUMP(arcstat_mutex_miss);
3658 multilist_sublist_unlock(mls);
3660 return (bytes_evicted);
3664 * Evict buffers from the given arc state, until we've removed the
3665 * specified number of bytes. Move the removed buffers to the
3666 * appropriate evict state.
3668 * This function makes a "best effort". It skips over any buffers
3669 * it can't get a hash_lock on, and so, may not catch all candidates.
3670 * It may also return without evicting as much space as requested.
3672 * If bytes is specified using the special value ARC_EVICT_ALL, this
3673 * will evict all available (i.e. unlocked and evictable) buffers from
3674 * the given arc state; which is used by arc_flush().
3677 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3678 arc_buf_contents_t type)
3680 uint64_t total_evicted = 0;
3681 multilist_t *ml = &state->arcs_list[type];
3683 arc_buf_hdr_t **markers;
3685 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3687 num_sublists = multilist_get_num_sublists(ml);
3690 * If we've tried to evict from each sublist, made some
3691 * progress, but still have not hit the target number of bytes
3692 * to evict, we want to keep trying. The markers allow us to
3693 * pick up where we left off for each individual sublist, rather
3694 * than starting from the tail each time.
3696 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3697 for (int i = 0; i < num_sublists; i++) {
3698 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3701 * A b_spa of 0 is used to indicate that this header is
3702 * a marker. This fact is used in arc_adjust_type() and
3703 * arc_evict_state_impl().
3705 markers[i]->b_spa = 0;
3707 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3708 multilist_sublist_insert_tail(mls, markers[i]);
3709 multilist_sublist_unlock(mls);
3713 * While we haven't hit our target number of bytes to evict, or
3714 * we're evicting all available buffers.
3716 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3718 * Start eviction using a randomly selected sublist,
3719 * this is to try and evenly balance eviction across all
3720 * sublists. Always starting at the same sublist
3721 * (e.g. index 0) would cause evictions to favor certain
3722 * sublists over others.
3724 int sublist_idx = multilist_get_random_index(ml);
3725 uint64_t scan_evicted = 0;
3727 for (int i = 0; i < num_sublists; i++) {
3728 uint64_t bytes_remaining;
3729 uint64_t bytes_evicted;
3731 if (bytes == ARC_EVICT_ALL)
3732 bytes_remaining = ARC_EVICT_ALL;
3733 else if (total_evicted < bytes)
3734 bytes_remaining = bytes - total_evicted;
3738 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3739 markers[sublist_idx], spa, bytes_remaining);
3741 scan_evicted += bytes_evicted;
3742 total_evicted += bytes_evicted;
3744 /* we've reached the end, wrap to the beginning */
3745 if (++sublist_idx >= num_sublists)
3750 * If we didn't evict anything during this scan, we have
3751 * no reason to believe we'll evict more during another
3752 * scan, so break the loop.
3754 if (scan_evicted == 0) {
3755 /* This isn't possible, let's make that obvious */
3756 ASSERT3S(bytes, !=, 0);
3759 * When bytes is ARC_EVICT_ALL, the only way to
3760 * break the loop is when scan_evicted is zero.
3761 * In that case, we actually have evicted enough,
3762 * so we don't want to increment the kstat.
3764 if (bytes != ARC_EVICT_ALL) {
3765 ASSERT3S(total_evicted, <, bytes);
3766 ARCSTAT_BUMP(arcstat_evict_not_enough);
3773 for (int i = 0; i < num_sublists; i++) {
3774 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3775 multilist_sublist_remove(mls, markers[i]);
3776 multilist_sublist_unlock(mls);
3778 kmem_cache_free(hdr_full_cache, markers[i]);
3780 kmem_free(markers, sizeof (*markers) * num_sublists);
3782 return (total_evicted);
3786 * Flush all "evictable" data of the given type from the arc state
3787 * specified. This will not evict any "active" buffers (i.e. referenced).
3789 * When 'retry' is set to B_FALSE, the function will make a single pass
3790 * over the state and evict any buffers that it can. Since it doesn't
3791 * continually retry the eviction, it might end up leaving some buffers
3792 * in the ARC due to lock misses.
3794 * When 'retry' is set to B_TRUE, the function will continually retry the
3795 * eviction until *all* evictable buffers have been removed from the
3796 * state. As a result, if concurrent insertions into the state are
3797 * allowed (e.g. if the ARC isn't shutting down), this function might
3798 * wind up in an infinite loop, continually trying to evict buffers.
3801 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3804 uint64_t evicted = 0;
3806 while (refcount_count(&state->arcs_esize[type]) != 0) {
3807 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3817 * Evict the specified number of bytes from the state specified,
3818 * restricting eviction to the spa and type given. This function
3819 * prevents us from trying to evict more from a state's list than
3820 * is "evictable", and to skip evicting altogether when passed a
3821 * negative value for "bytes". In contrast, arc_evict_state() will
3822 * evict everything it can, when passed a negative value for "bytes".
3825 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3826 arc_buf_contents_t type)
3830 if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3831 delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3832 return (arc_evict_state(state, spa, delta, type));
3839 * Evict metadata buffers from the cache, such that arc_meta_used is
3840 * capped by the arc_meta_limit tunable.
3843 arc_adjust_meta(void)
3845 uint64_t total_evicted = 0;
3849 * If we're over the meta limit, we want to evict enough
3850 * metadata to get back under the meta limit. We don't want to
3851 * evict so much that we drop the MRU below arc_p, though. If
3852 * we're over the meta limit more than we're over arc_p, we
3853 * evict some from the MRU here, and some from the MFU below.
3855 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3856 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3857 refcount_count(&arc_mru->arcs_size) - arc_p));
3859 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3862 * Similar to the above, we want to evict enough bytes to get us
3863 * below the meta limit, but not so much as to drop us below the
3864 * space allotted to the MFU (which is defined as arc_c - arc_p).
3866 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3867 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3869 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3871 return (total_evicted);
3875 * Return the type of the oldest buffer in the given arc state
3877 * This function will select a random sublist of type ARC_BUFC_DATA and
3878 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3879 * is compared, and the type which contains the "older" buffer will be
3882 static arc_buf_contents_t
3883 arc_adjust_type(arc_state_t *state)
3885 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3886 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3887 int data_idx = multilist_get_random_index(data_ml);
3888 int meta_idx = multilist_get_random_index(meta_ml);
3889 multilist_sublist_t *data_mls;
3890 multilist_sublist_t *meta_mls;
3891 arc_buf_contents_t type;
3892 arc_buf_hdr_t *data_hdr;
3893 arc_buf_hdr_t *meta_hdr;
3896 * We keep the sublist lock until we're finished, to prevent
3897 * the headers from being destroyed via arc_evict_state().
3899 data_mls = multilist_sublist_lock(data_ml, data_idx);
3900 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3903 * These two loops are to ensure we skip any markers that
3904 * might be at the tail of the lists due to arc_evict_state().
3907 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3908 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3909 if (data_hdr->b_spa != 0)
3913 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3914 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3915 if (meta_hdr->b_spa != 0)
3919 if (data_hdr == NULL && meta_hdr == NULL) {
3920 type = ARC_BUFC_DATA;
3921 } else if (data_hdr == NULL) {
3922 ASSERT3P(meta_hdr, !=, NULL);
3923 type = ARC_BUFC_METADATA;
3924 } else if (meta_hdr == NULL) {
3925 ASSERT3P(data_hdr, !=, NULL);
3926 type = ARC_BUFC_DATA;
3928 ASSERT3P(data_hdr, !=, NULL);
3929 ASSERT3P(meta_hdr, !=, NULL);
3931 /* The headers can't be on the sublist without an L1 header */
3932 ASSERT(HDR_HAS_L1HDR(data_hdr));
3933 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3935 if (data_hdr->b_l1hdr.b_arc_access <
3936 meta_hdr->b_l1hdr.b_arc_access) {
3937 type = ARC_BUFC_DATA;
3939 type = ARC_BUFC_METADATA;
3943 multilist_sublist_unlock(meta_mls);
3944 multilist_sublist_unlock(data_mls);
3950 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3955 uint64_t total_evicted = 0;
3960 * If we're over arc_meta_limit, we want to correct that before
3961 * potentially evicting data buffers below.
3963 total_evicted += arc_adjust_meta();
3968 * If we're over the target cache size, we want to evict enough
3969 * from the list to get back to our target size. We don't want
3970 * to evict too much from the MRU, such that it drops below
3971 * arc_p. So, if we're over our target cache size more than
3972 * the MRU is over arc_p, we'll evict enough to get back to
3973 * arc_p here, and then evict more from the MFU below.
3975 target = MIN((int64_t)(arc_size - arc_c),
3976 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3977 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3980 * If we're below arc_meta_min, always prefer to evict data.
3981 * Otherwise, try to satisfy the requested number of bytes to
3982 * evict from the type which contains older buffers; in an
3983 * effort to keep newer buffers in the cache regardless of their
3984 * type. If we cannot satisfy the number of bytes from this
3985 * type, spill over into the next type.
3987 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3988 arc_meta_used > arc_meta_min) {
3989 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3990 total_evicted += bytes;
3993 * If we couldn't evict our target number of bytes from
3994 * metadata, we try to get the rest from data.
3999 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4001 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4002 total_evicted += bytes;
4005 * If we couldn't evict our target number of bytes from
4006 * data, we try to get the rest from metadata.
4011 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4017 * Now that we've tried to evict enough from the MRU to get its
4018 * size back to arc_p, if we're still above the target cache
4019 * size, we evict the rest from the MFU.
4021 target = arc_size - arc_c;
4023 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4024 arc_meta_used > arc_meta_min) {
4025 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4026 total_evicted += bytes;
4029 * If we couldn't evict our target number of bytes from
4030 * metadata, we try to get the rest from data.
4035 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4037 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4038 total_evicted += bytes;
4041 * If we couldn't evict our target number of bytes from
4042 * data, we try to get the rest from data.
4047 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4051 * Adjust ghost lists
4053 * In addition to the above, the ARC also defines target values
4054 * for the ghost lists. The sum of the mru list and mru ghost
4055 * list should never exceed the target size of the cache, and
4056 * the sum of the mru list, mfu list, mru ghost list, and mfu
4057 * ghost list should never exceed twice the target size of the
4058 * cache. The following logic enforces these limits on the ghost
4059 * caches, and evicts from them as needed.
4061 target = refcount_count(&arc_mru->arcs_size) +
4062 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4064 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4065 total_evicted += bytes;
4070 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4073 * We assume the sum of the mru list and mfu list is less than
4074 * or equal to arc_c (we enforced this above), which means we
4075 * can use the simpler of the two equations below:
4077 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4078 * mru ghost + mfu ghost <= arc_c
4080 target = refcount_count(&arc_mru_ghost->arcs_size) +
4081 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4083 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4084 total_evicted += bytes;
4089 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4091 return (total_evicted);
4095 arc_flush(spa_t *spa, boolean_t retry)
4100 * If retry is B_TRUE, a spa must not be specified since we have
4101 * no good way to determine if all of a spa's buffers have been
4102 * evicted from an arc state.
4104 ASSERT(!retry || spa == 0);
4107 guid = spa_load_guid(spa);
4109 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4110 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4112 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4113 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4115 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4116 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4118 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4119 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4123 arc_shrink(int64_t to_free)
4125 if (arc_c > arc_c_min) {
4126 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4127 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4128 if (arc_c > arc_c_min + to_free)
4129 atomic_add_64(&arc_c, -to_free);
4133 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4134 if (arc_c > arc_size)
4135 arc_c = MAX(arc_size, arc_c_min);
4137 arc_p = (arc_c >> 1);
4139 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4142 ASSERT(arc_c >= arc_c_min);
4143 ASSERT((int64_t)arc_p >= 0);
4146 if (arc_size > arc_c) {
4147 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
4149 (void) arc_adjust();
4153 static long needfree = 0;
4155 typedef enum free_memory_reason_t {
4160 FMR_PAGES_PP_MAXIMUM,
4164 } free_memory_reason_t;
4166 int64_t last_free_memory;
4167 free_memory_reason_t last_free_reason;
4170 * Additional reserve of pages for pp_reserve.
4172 int64_t arc_pages_pp_reserve = 64;
4175 * Additional reserve of pages for swapfs.
4177 int64_t arc_swapfs_reserve = 64;
4180 * Return the amount of memory that can be consumed before reclaim will be
4181 * needed. Positive if there is sufficient free memory, negative indicates
4182 * the amount of memory that needs to be freed up.
4185 arc_available_memory(void)
4187 int64_t lowest = INT64_MAX;
4189 free_memory_reason_t r = FMR_UNKNOWN;
4193 n = PAGESIZE * (-needfree);
4201 * Cooperate with pagedaemon when it's time for it to scan
4202 * and reclaim some pages.
4204 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4212 * check that we're out of range of the pageout scanner. It starts to
4213 * schedule paging if freemem is less than lotsfree and needfree.
4214 * lotsfree is the high-water mark for pageout, and needfree is the
4215 * number of needed free pages. We add extra pages here to make sure
4216 * the scanner doesn't start up while we're freeing memory.
4218 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4225 * check to make sure that swapfs has enough space so that anon
4226 * reservations can still succeed. anon_resvmem() checks that the
4227 * availrmem is greater than swapfs_minfree, and the number of reserved
4228 * swap pages. We also add a bit of extra here just to prevent
4229 * circumstances from getting really dire.
4231 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4232 desfree - arc_swapfs_reserve);
4235 r = FMR_SWAPFS_MINFREE;
4240 * Check that we have enough availrmem that memory locking (e.g., via
4241 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
4242 * stores the number of pages that cannot be locked; when availrmem
4243 * drops below pages_pp_maximum, page locking mechanisms such as
4244 * page_pp_lock() will fail.)
4246 n = PAGESIZE * (availrmem - pages_pp_maximum -
4247 arc_pages_pp_reserve);
4250 r = FMR_PAGES_PP_MAXIMUM;
4253 #endif /* illumos */
4254 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4256 * If we're on an i386 platform, it's possible that we'll exhaust the
4257 * kernel heap space before we ever run out of available physical
4258 * memory. Most checks of the size of the heap_area compare against
4259 * tune.t_minarmem, which is the minimum available real memory that we
4260 * can have in the system. However, this is generally fixed at 25 pages
4261 * which is so low that it's useless. In this comparison, we seek to
4262 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4263 * heap is allocated. (Or, in the calculation, if less than 1/4th is
4266 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
4267 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
4272 #define zio_arena NULL
4274 #define zio_arena heap_arena
4278 * If zio data pages are being allocated out of a separate heap segment,
4279 * then enforce that the size of available vmem for this arena remains
4280 * above about 1/16th free.
4282 * Note: The 1/16th arena free requirement was put in place
4283 * to aggressively evict memory from the arc in order to avoid
4284 * memory fragmentation issues.
4286 if (zio_arena != NULL) {
4287 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4288 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
4296 * Above limits know nothing about real level of KVA fragmentation.
4297 * Start aggressive reclamation if too little sequential KVA left.
4300 n = (vmem_size(heap_arena, VMEM_MAXFREE) < SPA_MAXBLOCKSIZE) ?
4301 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
4310 /* Every 100 calls, free a small amount */
4311 if (spa_get_random(100) == 0)
4313 #endif /* _KERNEL */
4315 last_free_memory = lowest;
4316 last_free_reason = r;
4317 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4323 * Determine if the system is under memory pressure and is asking
4324 * to reclaim memory. A return value of B_TRUE indicates that the system
4325 * is under memory pressure and that the arc should adjust accordingly.
4328 arc_reclaim_needed(void)
4330 return (arc_available_memory() < 0);
4333 extern kmem_cache_t *zio_buf_cache[];
4334 extern kmem_cache_t *zio_data_buf_cache[];
4335 extern kmem_cache_t *range_seg_cache;
4337 static __noinline void
4338 arc_kmem_reap_now(void)
4341 kmem_cache_t *prev_cache = NULL;
4342 kmem_cache_t *prev_data_cache = NULL;
4344 DTRACE_PROBE(arc__kmem_reap_start);
4346 if (arc_meta_used >= arc_meta_limit) {
4348 * We are exceeding our meta-data cache limit.
4349 * Purge some DNLC entries to release holds on meta-data.
4351 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4355 * Reclaim unused memory from all kmem caches.
4361 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4362 if (zio_buf_cache[i] != prev_cache) {
4363 prev_cache = zio_buf_cache[i];
4364 kmem_cache_reap_now(zio_buf_cache[i]);
4366 if (zio_data_buf_cache[i] != prev_data_cache) {
4367 prev_data_cache = zio_data_buf_cache[i];
4368 kmem_cache_reap_now(zio_data_buf_cache[i]);
4371 kmem_cache_reap_now(buf_cache);
4372 kmem_cache_reap_now(hdr_full_cache);
4373 kmem_cache_reap_now(hdr_l2only_cache);
4374 kmem_cache_reap_now(range_seg_cache);
4377 if (zio_arena != NULL) {
4379 * Ask the vmem arena to reclaim unused memory from its
4382 vmem_qcache_reap(zio_arena);
4385 DTRACE_PROBE(arc__kmem_reap_end);
4389 * Threads can block in arc_get_data_buf() waiting for this thread to evict
4390 * enough data and signal them to proceed. When this happens, the threads in
4391 * arc_get_data_buf() are sleeping while holding the hash lock for their
4392 * particular arc header. Thus, we must be careful to never sleep on a
4393 * hash lock in this thread. This is to prevent the following deadlock:
4395 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
4396 * waiting for the reclaim thread to signal it.
4398 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4399 * fails, and goes to sleep forever.
4401 * This possible deadlock is avoided by always acquiring a hash lock
4402 * using mutex_tryenter() from arc_reclaim_thread().
4405 arc_reclaim_thread(void *dummy __unused)
4407 hrtime_t growtime = 0;
4410 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4412 mutex_enter(&arc_reclaim_lock);
4413 while (!arc_reclaim_thread_exit) {
4414 uint64_t evicted = 0;
4417 * This is necessary in order for the mdb ::arc dcmd to
4418 * show up to date information. Since the ::arc command
4419 * does not call the kstat's update function, without
4420 * this call, the command may show stale stats for the
4421 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4422 * with this change, the data might be up to 1 second
4423 * out of date; but that should suffice. The arc_state_t
4424 * structures can be queried directly if more accurate
4425 * information is needed.
4427 if (arc_ksp != NULL)
4428 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4430 mutex_exit(&arc_reclaim_lock);
4433 * We call arc_adjust() before (possibly) calling
4434 * arc_kmem_reap_now(), so that we can wake up
4435 * arc_get_data_buf() sooner.
4437 evicted = arc_adjust();
4439 int64_t free_memory = arc_available_memory();
4440 if (free_memory < 0) {
4442 arc_no_grow = B_TRUE;
4446 * Wait at least zfs_grow_retry (default 60) seconds
4447 * before considering growing.
4449 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4451 arc_kmem_reap_now();
4454 * If we are still low on memory, shrink the ARC
4455 * so that we have arc_shrink_min free space.
4457 free_memory = arc_available_memory();
4460 (arc_c >> arc_shrink_shift) - free_memory;
4463 to_free = MAX(to_free, ptob(needfree));
4465 arc_shrink(to_free);
4467 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4468 arc_no_grow = B_TRUE;
4469 } else if (gethrtime() >= growtime) {
4470 arc_no_grow = B_FALSE;
4473 mutex_enter(&arc_reclaim_lock);
4476 * If evicted is zero, we couldn't evict anything via
4477 * arc_adjust(). This could be due to hash lock
4478 * collisions, but more likely due to the majority of
4479 * arc buffers being unevictable. Therefore, even if
4480 * arc_size is above arc_c, another pass is unlikely to
4481 * be helpful and could potentially cause us to enter an
4484 if (arc_size <= arc_c || evicted == 0) {
4489 * We're either no longer overflowing, or we
4490 * can't evict anything more, so we should wake
4491 * up any threads before we go to sleep.
4493 cv_broadcast(&arc_reclaim_waiters_cv);
4496 * Block until signaled, or after one second (we
4497 * might need to perform arc_kmem_reap_now()
4498 * even if we aren't being signalled)
4500 CALLB_CPR_SAFE_BEGIN(&cpr);
4501 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4502 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4503 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4507 arc_reclaim_thread_exit = B_FALSE;
4508 cv_broadcast(&arc_reclaim_thread_cv);
4509 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
4513 static u_int arc_dnlc_evicts_arg;
4514 extern struct vfsops zfs_vfsops;
4517 arc_dnlc_evicts_thread(void *dummy __unused)
4522 CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
4524 mutex_enter(&arc_dnlc_evicts_lock);
4525 while (!arc_dnlc_evicts_thread_exit) {
4526 CALLB_CPR_SAFE_BEGIN(&cpr);
4527 (void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
4528 CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
4529 if (arc_dnlc_evicts_arg != 0) {
4530 percent = arc_dnlc_evicts_arg;
4531 mutex_exit(&arc_dnlc_evicts_lock);
4533 vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
4535 mutex_enter(&arc_dnlc_evicts_lock);
4537 * Clear our token only after vnlru_free()
4538 * pass is done, to avoid false queueing of
4541 arc_dnlc_evicts_arg = 0;
4544 arc_dnlc_evicts_thread_exit = FALSE;
4545 cv_broadcast(&arc_dnlc_evicts_cv);
4546 CALLB_CPR_EXIT(&cpr);
4551 dnlc_reduce_cache(void *arg)
4555 percent = (u_int)(uintptr_t)arg;
4556 mutex_enter(&arc_dnlc_evicts_lock);
4557 if (arc_dnlc_evicts_arg == 0) {
4558 arc_dnlc_evicts_arg = percent;
4559 cv_broadcast(&arc_dnlc_evicts_cv);
4561 mutex_exit(&arc_dnlc_evicts_lock);
4565 * Adapt arc info given the number of bytes we are trying to add and
4566 * the state that we are comming from. This function is only called
4567 * when we are adding new content to the cache.
4570 arc_adapt(int bytes, arc_state_t *state)
4573 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4574 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4575 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4577 if (state == arc_l2c_only)
4582 * Adapt the target size of the MRU list:
4583 * - if we just hit in the MRU ghost list, then increase
4584 * the target size of the MRU list.
4585 * - if we just hit in the MFU ghost list, then increase
4586 * the target size of the MFU list by decreasing the
4587 * target size of the MRU list.
4589 if (state == arc_mru_ghost) {
4590 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4591 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4593 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4594 } else if (state == arc_mfu_ghost) {
4597 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4598 mult = MIN(mult, 10);
4600 delta = MIN(bytes * mult, arc_p);
4601 arc_p = MAX(arc_p_min, arc_p - delta);
4603 ASSERT((int64_t)arc_p >= 0);
4605 if (arc_reclaim_needed()) {
4606 cv_signal(&arc_reclaim_thread_cv);
4613 if (arc_c >= arc_c_max)
4617 * If we're within (2 * maxblocksize) bytes of the target
4618 * cache size, increment the target cache size
4620 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
4621 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
4622 atomic_add_64(&arc_c, (int64_t)bytes);
4623 if (arc_c > arc_c_max)
4625 else if (state == arc_anon)
4626 atomic_add_64(&arc_p, (int64_t)bytes);
4630 ASSERT((int64_t)arc_p >= 0);
4634 * Check if arc_size has grown past our upper threshold, determined by
4635 * zfs_arc_overflow_shift.
4638 arc_is_overflowing(void)
4640 /* Always allow at least one block of overflow */
4641 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4642 arc_c >> zfs_arc_overflow_shift);
4644 return (arc_size >= arc_c + overflow);
4648 * Allocate a block and return it to the caller. If we are hitting the
4649 * hard limit for the cache size, we must sleep, waiting for the eviction
4650 * thread to catch up. If we're past the target size but below the hard
4651 * limit, we'll only signal the reclaim thread and continue on.
4654 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4657 arc_state_t *state = hdr->b_l1hdr.b_state;
4658 arc_buf_contents_t type = arc_buf_type(hdr);
4660 arc_adapt(size, state);
4663 * If arc_size is currently overflowing, and has grown past our
4664 * upper limit, we must be adding data faster than the evict
4665 * thread can evict. Thus, to ensure we don't compound the
4666 * problem by adding more data and forcing arc_size to grow even
4667 * further past it's target size, we halt and wait for the
4668 * eviction thread to catch up.
4670 * It's also possible that the reclaim thread is unable to evict
4671 * enough buffers to get arc_size below the overflow limit (e.g.
4672 * due to buffers being un-evictable, or hash lock collisions).
4673 * In this case, we want to proceed regardless if we're
4674 * overflowing; thus we don't use a while loop here.
4676 if (arc_is_overflowing()) {
4677 mutex_enter(&arc_reclaim_lock);
4680 * Now that we've acquired the lock, we may no longer be
4681 * over the overflow limit, lets check.
4683 * We're ignoring the case of spurious wake ups. If that
4684 * were to happen, it'd let this thread consume an ARC
4685 * buffer before it should have (i.e. before we're under
4686 * the overflow limit and were signalled by the reclaim
4687 * thread). As long as that is a rare occurrence, it
4688 * shouldn't cause any harm.
4690 if (arc_is_overflowing()) {
4691 cv_signal(&arc_reclaim_thread_cv);
4692 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4695 mutex_exit(&arc_reclaim_lock);
4698 VERIFY3U(hdr->b_type, ==, type);
4699 if (type == ARC_BUFC_METADATA) {
4700 datap = zio_buf_alloc(size);
4701 arc_space_consume(size, ARC_SPACE_META);
4703 ASSERT(type == ARC_BUFC_DATA);
4704 datap = zio_data_buf_alloc(size);
4705 arc_space_consume(size, ARC_SPACE_DATA);
4709 * Update the state size. Note that ghost states have a
4710 * "ghost size" and so don't need to be updated.
4712 if (!GHOST_STATE(state)) {
4714 (void) refcount_add_many(&state->arcs_size, size, tag);
4717 * If this is reached via arc_read, the link is
4718 * protected by the hash lock. If reached via
4719 * arc_buf_alloc, the header should not be accessed by
4720 * any other thread. And, if reached via arc_read_done,
4721 * the hash lock will protect it if it's found in the
4722 * hash table; otherwise no other thread should be
4723 * trying to [add|remove]_reference it.
4725 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4726 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4727 (void) refcount_add_many(&state->arcs_esize[type],
4732 * If we are growing the cache, and we are adding anonymous
4733 * data, and we have outgrown arc_p, update arc_p
4735 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
4736 (refcount_count(&arc_anon->arcs_size) +
4737 refcount_count(&arc_mru->arcs_size) > arc_p))
4738 arc_p = MIN(arc_c, arc_p + size);
4740 ARCSTAT_BUMP(arcstat_allocated);
4745 * Free the arc data buffer.
4748 arc_free_data_buf(arc_buf_hdr_t *hdr, void *data, uint64_t size, void *tag)
4750 arc_state_t *state = hdr->b_l1hdr.b_state;
4751 arc_buf_contents_t type = arc_buf_type(hdr);
4753 /* protected by hash lock, if in the hash table */
4754 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4755 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4756 ASSERT(state != arc_anon && state != arc_l2c_only);
4758 (void) refcount_remove_many(&state->arcs_esize[type],
4761 (void) refcount_remove_many(&state->arcs_size, size, tag);
4763 VERIFY3U(hdr->b_type, ==, type);
4764 if (type == ARC_BUFC_METADATA) {
4765 zio_buf_free(data, size);
4766 arc_space_return(size, ARC_SPACE_META);
4768 ASSERT(type == ARC_BUFC_DATA);
4769 zio_data_buf_free(data, size);
4770 arc_space_return(size, ARC_SPACE_DATA);
4775 * This routine is called whenever a buffer is accessed.
4776 * NOTE: the hash lock is dropped in this function.
4779 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4783 ASSERT(MUTEX_HELD(hash_lock));
4784 ASSERT(HDR_HAS_L1HDR(hdr));
4786 if (hdr->b_l1hdr.b_state == arc_anon) {
4788 * This buffer is not in the cache, and does not
4789 * appear in our "ghost" list. Add the new buffer
4793 ASSERT0(hdr->b_l1hdr.b_arc_access);
4794 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4795 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4796 arc_change_state(arc_mru, hdr, hash_lock);
4798 } else if (hdr->b_l1hdr.b_state == arc_mru) {
4799 now = ddi_get_lbolt();
4802 * If this buffer is here because of a prefetch, then either:
4803 * - clear the flag if this is a "referencing" read
4804 * (any subsequent access will bump this into the MFU state).
4806 * - move the buffer to the head of the list if this is
4807 * another prefetch (to make it less likely to be evicted).
4809 if (HDR_PREFETCH(hdr)) {
4810 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4811 /* link protected by hash lock */
4812 ASSERT(multilist_link_active(
4813 &hdr->b_l1hdr.b_arc_node));
4815 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4816 ARCSTAT_BUMP(arcstat_mru_hits);
4818 hdr->b_l1hdr.b_arc_access = now;
4823 * This buffer has been "accessed" only once so far,
4824 * but it is still in the cache. Move it to the MFU
4827 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4829 * More than 125ms have passed since we
4830 * instantiated this buffer. Move it to the
4831 * most frequently used state.
4833 hdr->b_l1hdr.b_arc_access = now;
4834 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4835 arc_change_state(arc_mfu, hdr, hash_lock);
4837 ARCSTAT_BUMP(arcstat_mru_hits);
4838 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4839 arc_state_t *new_state;
4841 * This buffer has been "accessed" recently, but
4842 * was evicted from the cache. Move it to the
4846 if (HDR_PREFETCH(hdr)) {
4847 new_state = arc_mru;
4848 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4849 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4850 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4852 new_state = arc_mfu;
4853 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4856 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4857 arc_change_state(new_state, hdr, hash_lock);
4859 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4860 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
4862 * This buffer has been accessed more than once and is
4863 * still in the cache. Keep it in the MFU state.
4865 * NOTE: an add_reference() that occurred when we did
4866 * the arc_read() will have kicked this off the list.
4867 * If it was a prefetch, we will explicitly move it to
4868 * the head of the list now.
4870 if ((HDR_PREFETCH(hdr)) != 0) {
4871 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4872 /* link protected by hash_lock */
4873 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4875 ARCSTAT_BUMP(arcstat_mfu_hits);
4876 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4877 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4878 arc_state_t *new_state = arc_mfu;
4880 * This buffer has been accessed more than once but has
4881 * been evicted from the cache. Move it back to the
4885 if (HDR_PREFETCH(hdr)) {
4887 * This is a prefetch access...
4888 * move this block back to the MRU state.
4890 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4891 new_state = arc_mru;
4894 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4895 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4896 arc_change_state(new_state, hdr, hash_lock);
4898 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4899 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4901 * This buffer is on the 2nd Level ARC.
4904 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4905 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4906 arc_change_state(arc_mfu, hdr, hash_lock);
4908 ASSERT(!"invalid arc state");
4912 /* a generic arc_done_func_t which you can use */
4915 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4917 if (zio == NULL || zio->io_error == 0)
4918 bcopy(buf->b_data, arg, arc_buf_size(buf));
4919 arc_buf_destroy(buf, arg);
4922 /* a generic arc_done_func_t */
4924 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4926 arc_buf_t **bufp = arg;
4927 if (zio && zio->io_error) {
4928 arc_buf_destroy(buf, arg);
4932 ASSERT(buf->b_data);
4937 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4939 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4940 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4941 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4943 if (HDR_COMPRESSION_ENABLED(hdr)) {
4944 ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4945 BP_GET_COMPRESS(bp));
4947 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4948 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4953 arc_read_done(zio_t *zio)
4955 arc_buf_hdr_t *hdr = zio->io_private;
4956 kmutex_t *hash_lock = NULL;
4957 arc_callback_t *callback_list;
4958 arc_callback_t *acb;
4959 boolean_t freeable = B_FALSE;
4960 boolean_t no_zio_error = (zio->io_error == 0);
4963 * The hdr was inserted into hash-table and removed from lists
4964 * prior to starting I/O. We should find this header, since
4965 * it's in the hash table, and it should be legit since it's
4966 * not possible to evict it during the I/O. The only possible
4967 * reason for it not to be found is if we were freed during the
4970 if (HDR_IN_HASH_TABLE(hdr)) {
4971 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4972 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4973 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4974 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4975 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4977 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4980 ASSERT((found == hdr &&
4981 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4982 (found == hdr && HDR_L2_READING(hdr)));
4983 ASSERT3P(hash_lock, !=, NULL);
4987 /* byteswap if necessary */
4988 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4989 if (BP_GET_LEVEL(zio->io_bp) > 0) {
4990 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4992 hdr->b_l1hdr.b_byteswap =
4993 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4996 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5000 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5001 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5002 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5004 callback_list = hdr->b_l1hdr.b_acb;
5005 ASSERT3P(callback_list, !=, NULL);
5007 if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5009 * Only call arc_access on anonymous buffers. This is because
5010 * if we've issued an I/O for an evicted buffer, we've already
5011 * called arc_access (to prevent any simultaneous readers from
5012 * getting confused).
5014 arc_access(hdr, hash_lock);
5018 * If a read request has a callback (i.e. acb_done is not NULL), then we
5019 * make a buf containing the data according to the parameters which were
5020 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5021 * aren't needlessly decompressing the data multiple times.
5023 int callback_cnt = 0;
5024 for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5028 /* This is a demand read since prefetches don't use callbacks */
5031 int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5032 acb->acb_compressed, no_zio_error, &acb->acb_buf);
5034 zio->io_error = error;
5037 hdr->b_l1hdr.b_acb = NULL;
5038 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5039 if (callback_cnt == 0) {
5040 ASSERT(HDR_PREFETCH(hdr));
5041 ASSERT0(hdr->b_l1hdr.b_bufcnt);
5042 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5045 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5046 callback_list != NULL);
5049 arc_hdr_verify(hdr, zio->io_bp);
5051 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5052 if (hdr->b_l1hdr.b_state != arc_anon)
5053 arc_change_state(arc_anon, hdr, hash_lock);
5054 if (HDR_IN_HASH_TABLE(hdr))
5055 buf_hash_remove(hdr);
5056 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5060 * Broadcast before we drop the hash_lock to avoid the possibility
5061 * that the hdr (and hence the cv) might be freed before we get to
5062 * the cv_broadcast().
5064 cv_broadcast(&hdr->b_l1hdr.b_cv);
5066 if (hash_lock != NULL) {
5067 mutex_exit(hash_lock);
5070 * This block was freed while we waited for the read to
5071 * complete. It has been removed from the hash table and
5072 * moved to the anonymous state (so that it won't show up
5075 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5076 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5079 /* execute each callback and free its structure */
5080 while ((acb = callback_list) != NULL) {
5082 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
5084 if (acb->acb_zio_dummy != NULL) {
5085 acb->acb_zio_dummy->io_error = zio->io_error;
5086 zio_nowait(acb->acb_zio_dummy);
5089 callback_list = acb->acb_next;
5090 kmem_free(acb, sizeof (arc_callback_t));
5094 arc_hdr_destroy(hdr);
5098 * "Read" the block at the specified DVA (in bp) via the
5099 * cache. If the block is found in the cache, invoke the provided
5100 * callback immediately and return. Note that the `zio' parameter
5101 * in the callback will be NULL in this case, since no IO was
5102 * required. If the block is not in the cache pass the read request
5103 * on to the spa with a substitute callback function, so that the
5104 * requested block will be added to the cache.
5106 * If a read request arrives for a block that has a read in-progress,
5107 * either wait for the in-progress read to complete (and return the
5108 * results); or, if this is a read with a "done" func, add a record
5109 * to the read to invoke the "done" func when the read completes,
5110 * and return; or just return.
5112 * arc_read_done() will invoke all the requested "done" functions
5113 * for readers of this block.
5116 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
5117 void *private, zio_priority_t priority, int zio_flags,
5118 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5120 arc_buf_hdr_t *hdr = NULL;
5121 kmutex_t *hash_lock = NULL;
5123 uint64_t guid = spa_load_guid(spa);
5124 boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5126 ASSERT(!BP_IS_EMBEDDED(bp) ||
5127 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5130 if (!BP_IS_EMBEDDED(bp)) {
5132 * Embedded BP's have no DVA and require no I/O to "read".
5133 * Create an anonymous arc buf to back it.
5135 hdr = buf_hash_find(guid, bp, &hash_lock);
5138 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pdata != NULL) {
5139 arc_buf_t *buf = NULL;
5140 *arc_flags |= ARC_FLAG_CACHED;
5142 if (HDR_IO_IN_PROGRESS(hdr)) {
5144 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5145 priority == ZIO_PRIORITY_SYNC_READ) {
5147 * This sync read must wait for an
5148 * in-progress async read (e.g. a predictive
5149 * prefetch). Async reads are queued
5150 * separately at the vdev_queue layer, so
5151 * this is a form of priority inversion.
5152 * Ideally, we would "inherit" the demand
5153 * i/o's priority by moving the i/o from
5154 * the async queue to the synchronous queue,
5155 * but there is currently no mechanism to do
5156 * so. Track this so that we can evaluate
5157 * the magnitude of this potential performance
5160 * Note that if the prefetch i/o is already
5161 * active (has been issued to the device),
5162 * the prefetch improved performance, because
5163 * we issued it sooner than we would have
5164 * without the prefetch.
5166 DTRACE_PROBE1(arc__sync__wait__for__async,
5167 arc_buf_hdr_t *, hdr);
5168 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
5170 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5171 arc_hdr_clear_flags(hdr,
5172 ARC_FLAG_PREDICTIVE_PREFETCH);
5175 if (*arc_flags & ARC_FLAG_WAIT) {
5176 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5177 mutex_exit(hash_lock);
5180 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5183 arc_callback_t *acb = NULL;
5185 acb = kmem_zalloc(sizeof (arc_callback_t),
5187 acb->acb_done = done;
5188 acb->acb_private = private;
5189 acb->acb_compressed = compressed_read;
5191 acb->acb_zio_dummy = zio_null(pio,
5192 spa, NULL, NULL, NULL, zio_flags);
5194 ASSERT3P(acb->acb_done, !=, NULL);
5195 acb->acb_next = hdr->b_l1hdr.b_acb;
5196 hdr->b_l1hdr.b_acb = acb;
5197 mutex_exit(hash_lock);
5200 mutex_exit(hash_lock);
5204 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5205 hdr->b_l1hdr.b_state == arc_mfu);
5208 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5210 * This is a demand read which does not have to
5211 * wait for i/o because we did a predictive
5212 * prefetch i/o for it, which has completed.
5215 arc__demand__hit__predictive__prefetch,
5216 arc_buf_hdr_t *, hdr);
5218 arcstat_demand_hit_predictive_prefetch);
5219 arc_hdr_clear_flags(hdr,
5220 ARC_FLAG_PREDICTIVE_PREFETCH);
5222 ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5224 /* Get a buf with the desired data in it. */
5225 VERIFY0(arc_buf_alloc_impl(hdr, private,
5226 compressed_read, B_TRUE, &buf));
5227 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
5228 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5229 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5231 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5232 arc_access(hdr, hash_lock);
5233 if (*arc_flags & ARC_FLAG_L2CACHE)
5234 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5235 mutex_exit(hash_lock);
5236 ARCSTAT_BUMP(arcstat_hits);
5237 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5238 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5239 data, metadata, hits);
5242 done(NULL, buf, private);
5244 uint64_t lsize = BP_GET_LSIZE(bp);
5245 uint64_t psize = BP_GET_PSIZE(bp);
5246 arc_callback_t *acb;
5249 boolean_t devw = B_FALSE;
5253 /* this block is not in the cache */
5254 arc_buf_hdr_t *exists = NULL;
5255 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5256 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5257 BP_GET_COMPRESS(bp), type);
5259 if (!BP_IS_EMBEDDED(bp)) {
5260 hdr->b_dva = *BP_IDENTITY(bp);
5261 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5262 exists = buf_hash_insert(hdr, &hash_lock);
5264 if (exists != NULL) {
5265 /* somebody beat us to the hash insert */
5266 mutex_exit(hash_lock);
5267 buf_discard_identity(hdr);
5268 arc_hdr_destroy(hdr);
5269 goto top; /* restart the IO request */
5273 * This block is in the ghost cache. If it was L2-only
5274 * (and thus didn't have an L1 hdr), we realloc the
5275 * header to add an L1 hdr.
5277 if (!HDR_HAS_L1HDR(hdr)) {
5278 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5281 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5282 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5283 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5284 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5285 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5286 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5289 * This is a delicate dance that we play here.
5290 * This hdr is in the ghost list so we access it
5291 * to move it out of the ghost list before we
5292 * initiate the read. If it's a prefetch then
5293 * it won't have a callback so we'll remove the
5294 * reference that arc_buf_alloc_impl() created. We
5295 * do this after we've called arc_access() to
5296 * avoid hitting an assert in remove_reference().
5298 arc_access(hdr, hash_lock);
5299 arc_hdr_alloc_pdata(hdr);
5301 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5302 size = arc_hdr_size(hdr);
5305 * If compression is enabled on the hdr, then will do
5306 * RAW I/O and will store the compressed data in the hdr's
5307 * data block. Otherwise, the hdr's data block will contain
5308 * the uncompressed data.
5310 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5311 zio_flags |= ZIO_FLAG_RAW;
5314 if (*arc_flags & ARC_FLAG_PREFETCH)
5315 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5316 if (*arc_flags & ARC_FLAG_L2CACHE)
5317 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5318 if (BP_GET_LEVEL(bp) > 0)
5319 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5320 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5321 arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5322 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5324 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5325 acb->acb_done = done;
5326 acb->acb_private = private;
5327 acb->acb_compressed = compressed_read;
5329 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5330 hdr->b_l1hdr.b_acb = acb;
5331 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5333 if (HDR_HAS_L2HDR(hdr) &&
5334 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5335 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5336 addr = hdr->b_l2hdr.b_daddr;
5338 * Lock out device removal.
5340 if (vdev_is_dead(vd) ||
5341 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5345 if (priority == ZIO_PRIORITY_ASYNC_READ)
5346 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5348 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5350 if (hash_lock != NULL)
5351 mutex_exit(hash_lock);
5354 * At this point, we have a level 1 cache miss. Try again in
5355 * L2ARC if possible.
5357 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5359 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5360 uint64_t, lsize, zbookmark_phys_t *, zb);
5361 ARCSTAT_BUMP(arcstat_misses);
5362 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5363 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5364 data, metadata, misses);
5369 racct_add_force(curproc, RACCT_READBPS, size);
5370 racct_add_force(curproc, RACCT_READIOPS, 1);
5371 PROC_UNLOCK(curproc);
5374 curthread->td_ru.ru_inblock++;
5377 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5379 * Read from the L2ARC if the following are true:
5380 * 1. The L2ARC vdev was previously cached.
5381 * 2. This buffer still has L2ARC metadata.
5382 * 3. This buffer isn't currently writing to the L2ARC.
5383 * 4. The L2ARC entry wasn't evicted, which may
5384 * also have invalidated the vdev.
5385 * 5. This isn't prefetch and l2arc_noprefetch is set.
5387 if (HDR_HAS_L2HDR(hdr) &&
5388 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5389 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5390 l2arc_read_callback_t *cb;
5393 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5394 ARCSTAT_BUMP(arcstat_l2_hits);
5396 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5398 cb->l2rcb_hdr = hdr;
5401 cb->l2rcb_flags = zio_flags;
5402 uint64_t asize = vdev_psize_to_asize(vd, size);
5403 if (asize != size) {
5404 b_data = zio_data_buf_alloc(asize);
5405 cb->l2rcb_data = b_data;
5407 b_data = hdr->b_l1hdr.b_pdata;
5410 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5411 addr + asize < vd->vdev_psize -
5412 VDEV_LABEL_END_SIZE);
5415 * l2arc read. The SCL_L2ARC lock will be
5416 * released by l2arc_read_done().
5417 * Issue a null zio if the underlying buffer
5418 * was squashed to zero size by compression.
5420 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5421 ZIO_COMPRESS_EMPTY);
5422 rzio = zio_read_phys(pio, vd, addr,
5425 l2arc_read_done, cb, priority,
5426 zio_flags | ZIO_FLAG_DONT_CACHE |
5428 ZIO_FLAG_DONT_PROPAGATE |
5429 ZIO_FLAG_DONT_RETRY, B_FALSE);
5430 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5432 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5434 if (*arc_flags & ARC_FLAG_NOWAIT) {
5439 ASSERT(*arc_flags & ARC_FLAG_WAIT);
5440 if (zio_wait(rzio) == 0)
5443 /* l2arc read error; goto zio_read() */
5445 DTRACE_PROBE1(l2arc__miss,
5446 arc_buf_hdr_t *, hdr);
5447 ARCSTAT_BUMP(arcstat_l2_misses);
5448 if (HDR_L2_WRITING(hdr))
5449 ARCSTAT_BUMP(arcstat_l2_rw_clash);
5450 spa_config_exit(spa, SCL_L2ARC, vd);
5454 spa_config_exit(spa, SCL_L2ARC, vd);
5455 if (l2arc_ndev != 0) {
5456 DTRACE_PROBE1(l2arc__miss,
5457 arc_buf_hdr_t *, hdr);
5458 ARCSTAT_BUMP(arcstat_l2_misses);
5462 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pdata, size,
5463 arc_read_done, hdr, priority, zio_flags, zb);
5465 if (*arc_flags & ARC_FLAG_WAIT)
5466 return (zio_wait(rzio));
5468 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5475 * Notify the arc that a block was freed, and thus will never be used again.
5478 arc_freed(spa_t *spa, const blkptr_t *bp)
5481 kmutex_t *hash_lock;
5482 uint64_t guid = spa_load_guid(spa);
5484 ASSERT(!BP_IS_EMBEDDED(bp));
5486 hdr = buf_hash_find(guid, bp, &hash_lock);
5491 * We might be trying to free a block that is still doing I/O
5492 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5493 * dmu_sync-ed block). If this block is being prefetched, then it
5494 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5495 * until the I/O completes. A block may also have a reference if it is
5496 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5497 * have written the new block to its final resting place on disk but
5498 * without the dedup flag set. This would have left the hdr in the MRU
5499 * state and discoverable. When the txg finally syncs it detects that
5500 * the block was overridden in open context and issues an override I/O.
5501 * Since this is a dedup block, the override I/O will determine if the
5502 * block is already in the DDT. If so, then it will replace the io_bp
5503 * with the bp from the DDT and allow the I/O to finish. When the I/O
5504 * reaches the done callback, dbuf_write_override_done, it will
5505 * check to see if the io_bp and io_bp_override are identical.
5506 * If they are not, then it indicates that the bp was replaced with
5507 * the bp in the DDT and the override bp is freed. This allows
5508 * us to arrive here with a reference on a block that is being
5509 * freed. So if we have an I/O in progress, or a reference to
5510 * this hdr, then we don't destroy the hdr.
5512 if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5513 refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5514 arc_change_state(arc_anon, hdr, hash_lock);
5515 arc_hdr_destroy(hdr);
5516 mutex_exit(hash_lock);
5518 mutex_exit(hash_lock);
5524 * Release this buffer from the cache, making it an anonymous buffer. This
5525 * must be done after a read and prior to modifying the buffer contents.
5526 * If the buffer has more than one reference, we must make
5527 * a new hdr for the buffer.
5530 arc_release(arc_buf_t *buf, void *tag)
5532 arc_buf_hdr_t *hdr = buf->b_hdr;
5535 * It would be nice to assert that if it's DMU metadata (level >
5536 * 0 || it's the dnode file), then it must be syncing context.
5537 * But we don't know that information at this level.
5540 mutex_enter(&buf->b_evict_lock);
5542 ASSERT(HDR_HAS_L1HDR(hdr));
5545 * We don't grab the hash lock prior to this check, because if
5546 * the buffer's header is in the arc_anon state, it won't be
5547 * linked into the hash table.
5549 if (hdr->b_l1hdr.b_state == arc_anon) {
5550 mutex_exit(&buf->b_evict_lock);
5551 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5552 ASSERT(!HDR_IN_HASH_TABLE(hdr));
5553 ASSERT(!HDR_HAS_L2HDR(hdr));
5554 ASSERT(HDR_EMPTY(hdr));
5555 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5556 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5557 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5559 hdr->b_l1hdr.b_arc_access = 0;
5562 * If the buf is being overridden then it may already
5563 * have a hdr that is not empty.
5565 buf_discard_identity(hdr);
5571 kmutex_t *hash_lock = HDR_LOCK(hdr);
5572 mutex_enter(hash_lock);
5575 * This assignment is only valid as long as the hash_lock is
5576 * held, we must be careful not to reference state or the
5577 * b_state field after dropping the lock.
5579 arc_state_t *state = hdr->b_l1hdr.b_state;
5580 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5581 ASSERT3P(state, !=, arc_anon);
5583 /* this buffer is not on any list */
5584 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
5586 if (HDR_HAS_L2HDR(hdr)) {
5587 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5590 * We have to recheck this conditional again now that
5591 * we're holding the l2ad_mtx to prevent a race with
5592 * another thread which might be concurrently calling
5593 * l2arc_evict(). In that case, l2arc_evict() might have
5594 * destroyed the header's L2 portion as we were waiting
5595 * to acquire the l2ad_mtx.
5597 if (HDR_HAS_L2HDR(hdr)) {
5599 arc_hdr_l2hdr_destroy(hdr);
5602 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5606 * Do we have more than one buf?
5608 if (hdr->b_l1hdr.b_bufcnt > 1) {
5609 arc_buf_hdr_t *nhdr;
5610 uint64_t spa = hdr->b_spa;
5611 uint64_t psize = HDR_GET_PSIZE(hdr);
5612 uint64_t lsize = HDR_GET_LSIZE(hdr);
5613 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5614 arc_buf_contents_t type = arc_buf_type(hdr);
5615 VERIFY3U(hdr->b_type, ==, type);
5617 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5618 (void) remove_reference(hdr, hash_lock, tag);
5620 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5621 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5622 ASSERT(ARC_BUF_LAST(buf));
5626 * Pull the data off of this hdr and attach it to
5627 * a new anonymous hdr. Also find the last buffer
5628 * in the hdr's buffer list.
5630 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5631 ASSERT3P(lastbuf, !=, NULL);
5634 * If the current arc_buf_t and the hdr are sharing their data
5635 * buffer, then we must stop sharing that block.
5637 if (arc_buf_is_shared(buf)) {
5638 VERIFY(!arc_buf_is_shared(lastbuf));
5641 * First, sever the block sharing relationship between
5642 * buf and the arc_buf_hdr_t.
5644 arc_unshare_buf(hdr, buf);
5647 * Now we need to recreate the hdr's b_pdata. Since we
5648 * have lastbuf handy, we try to share with it, but if
5649 * we can't then we allocate a new b_pdata and copy the
5650 * data from buf into it.
5652 if (arc_can_share(hdr, lastbuf)) {
5653 arc_share_buf(hdr, lastbuf);
5655 arc_hdr_alloc_pdata(hdr);
5656 bcopy(buf->b_data, hdr->b_l1hdr.b_pdata, psize);
5658 VERIFY3P(lastbuf->b_data, !=, NULL);
5659 } else if (HDR_SHARED_DATA(hdr)) {
5661 * Uncompressed shared buffers are always at the end
5662 * of the list. Compressed buffers don't have the
5663 * same requirements. This makes it hard to
5664 * simply assert that the lastbuf is shared so
5665 * we rely on the hdr's compression flags to determine
5666 * if we have a compressed, shared buffer.
5668 ASSERT(arc_buf_is_shared(lastbuf) ||
5669 HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
5670 ASSERT(!ARC_BUF_SHARED(buf));
5672 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5673 ASSERT3P(state, !=, arc_l2c_only);
5675 (void) refcount_remove_many(&state->arcs_size,
5676 arc_buf_size(buf), buf);
5678 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5679 ASSERT3P(state, !=, arc_l2c_only);
5680 (void) refcount_remove_many(&state->arcs_esize[type],
5681 arc_buf_size(buf), buf);
5684 hdr->b_l1hdr.b_bufcnt -= 1;
5685 arc_cksum_verify(buf);
5687 arc_buf_unwatch(buf);
5690 mutex_exit(hash_lock);
5693 * Allocate a new hdr. The new hdr will contain a b_pdata
5694 * buffer which will be freed in arc_write().
5696 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5697 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5698 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5699 ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5700 VERIFY3U(nhdr->b_type, ==, type);
5701 ASSERT(!HDR_SHARED_DATA(nhdr));
5703 nhdr->b_l1hdr.b_buf = buf;
5704 nhdr->b_l1hdr.b_bufcnt = 1;
5705 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5708 mutex_exit(&buf->b_evict_lock);
5709 (void) refcount_add_many(&arc_anon->arcs_size,
5710 arc_buf_size(buf), buf);
5712 mutex_exit(&buf->b_evict_lock);
5713 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5714 /* protected by hash lock, or hdr is on arc_anon */
5715 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5716 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5717 arc_change_state(arc_anon, hdr, hash_lock);
5718 hdr->b_l1hdr.b_arc_access = 0;
5719 mutex_exit(hash_lock);
5721 buf_discard_identity(hdr);
5727 arc_released(arc_buf_t *buf)
5731 mutex_enter(&buf->b_evict_lock);
5732 released = (buf->b_data != NULL &&
5733 buf->b_hdr->b_l1hdr.b_state == arc_anon);
5734 mutex_exit(&buf->b_evict_lock);
5740 arc_referenced(arc_buf_t *buf)
5744 mutex_enter(&buf->b_evict_lock);
5745 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5746 mutex_exit(&buf->b_evict_lock);
5747 return (referenced);
5752 arc_write_ready(zio_t *zio)
5754 arc_write_callback_t *callback = zio->io_private;
5755 arc_buf_t *buf = callback->awcb_buf;
5756 arc_buf_hdr_t *hdr = buf->b_hdr;
5757 uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5759 ASSERT(HDR_HAS_L1HDR(hdr));
5760 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5761 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5764 * If we're reexecuting this zio because the pool suspended, then
5765 * cleanup any state that was previously set the first time the
5766 * callback was invoked.
5768 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5769 arc_cksum_free(hdr);
5771 arc_buf_unwatch(buf);
5773 if (hdr->b_l1hdr.b_pdata != NULL) {
5774 if (arc_buf_is_shared(buf)) {
5775 arc_unshare_buf(hdr, buf);
5777 arc_hdr_free_pdata(hdr);
5781 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5782 ASSERT(!HDR_SHARED_DATA(hdr));
5783 ASSERT(!arc_buf_is_shared(buf));
5785 callback->awcb_ready(zio, buf, callback->awcb_private);
5787 if (HDR_IO_IN_PROGRESS(hdr))
5788 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5790 arc_cksum_compute(buf);
5791 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5793 enum zio_compress compress;
5794 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5795 compress = ZIO_COMPRESS_OFF;
5797 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5798 compress = BP_GET_COMPRESS(zio->io_bp);
5800 HDR_SET_PSIZE(hdr, psize);
5801 arc_hdr_set_compress(hdr, compress);
5804 * If the hdr is compressed, then copy the compressed
5805 * zio contents into arc_buf_hdr_t. Otherwise, copy the original
5806 * data buf into the hdr. Ideally, we would like to always copy the
5807 * io_data into b_pdata but the user may have disabled compressed
5808 * arc thus the on-disk block may or may not match what we maintain
5809 * in the hdr's b_pdata field.
5811 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
5812 !ARC_BUF_COMPRESSED(buf)) {
5813 ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=, ZIO_COMPRESS_OFF);
5814 ASSERT3U(psize, >, 0);
5815 arc_hdr_alloc_pdata(hdr);
5816 bcopy(zio->io_data, hdr->b_l1hdr.b_pdata, psize);
5818 ASSERT3P(buf->b_data, ==, zio->io_orig_data);
5819 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5820 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5823 * This hdr is not compressed so we're able to share
5824 * the arc_buf_t data buffer with the hdr.
5826 arc_share_buf(hdr, buf);
5827 ASSERT0(bcmp(zio->io_orig_data, hdr->b_l1hdr.b_pdata,
5828 arc_buf_size(buf)));
5830 arc_hdr_verify(hdr, zio->io_bp);
5834 arc_write_children_ready(zio_t *zio)
5836 arc_write_callback_t *callback = zio->io_private;
5837 arc_buf_t *buf = callback->awcb_buf;
5839 callback->awcb_children_ready(zio, buf, callback->awcb_private);
5843 * The SPA calls this callback for each physical write that happens on behalf
5844 * of a logical write. See the comment in dbuf_write_physdone() for details.
5847 arc_write_physdone(zio_t *zio)
5849 arc_write_callback_t *cb = zio->io_private;
5850 if (cb->awcb_physdone != NULL)
5851 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
5855 arc_write_done(zio_t *zio)
5857 arc_write_callback_t *callback = zio->io_private;
5858 arc_buf_t *buf = callback->awcb_buf;
5859 arc_buf_hdr_t *hdr = buf->b_hdr;
5861 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5863 if (zio->io_error == 0) {
5864 arc_hdr_verify(hdr, zio->io_bp);
5866 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5867 buf_discard_identity(hdr);
5869 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5870 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5873 ASSERT(HDR_EMPTY(hdr));
5877 * If the block to be written was all-zero or compressed enough to be
5878 * embedded in the BP, no write was performed so there will be no
5879 * dva/birth/checksum. The buffer must therefore remain anonymous
5882 if (!HDR_EMPTY(hdr)) {
5883 arc_buf_hdr_t *exists;
5884 kmutex_t *hash_lock;
5886 ASSERT3U(zio->io_error, ==, 0);
5888 arc_cksum_verify(buf);
5890 exists = buf_hash_insert(hdr, &hash_lock);
5891 if (exists != NULL) {
5893 * This can only happen if we overwrite for
5894 * sync-to-convergence, because we remove
5895 * buffers from the hash table when we arc_free().
5897 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5898 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5899 panic("bad overwrite, hdr=%p exists=%p",
5900 (void *)hdr, (void *)exists);
5901 ASSERT(refcount_is_zero(
5902 &exists->b_l1hdr.b_refcnt));
5903 arc_change_state(arc_anon, exists, hash_lock);
5904 mutex_exit(hash_lock);
5905 arc_hdr_destroy(exists);
5906 exists = buf_hash_insert(hdr, &hash_lock);
5907 ASSERT3P(exists, ==, NULL);
5908 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5910 ASSERT(zio->io_prop.zp_nopwrite);
5911 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5912 panic("bad nopwrite, hdr=%p exists=%p",
5913 (void *)hdr, (void *)exists);
5916 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
5917 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5918 ASSERT(BP_GET_DEDUP(zio->io_bp));
5919 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5922 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5923 /* if it's not anon, we are doing a scrub */
5924 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5925 arc_access(hdr, hash_lock);
5926 mutex_exit(hash_lock);
5928 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5931 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5932 callback->awcb_done(zio, buf, callback->awcb_private);
5934 kmem_free(callback, sizeof (arc_write_callback_t));
5938 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5939 boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
5940 arc_done_func_t *children_ready, arc_done_func_t *physdone,
5941 arc_done_func_t *done, void *private, zio_priority_t priority,
5942 int zio_flags, const zbookmark_phys_t *zb)
5944 arc_buf_hdr_t *hdr = buf->b_hdr;
5945 arc_write_callback_t *callback;
5948 ASSERT3P(ready, !=, NULL);
5949 ASSERT3P(done, !=, NULL);
5950 ASSERT(!HDR_IO_ERROR(hdr));
5951 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5952 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5953 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
5955 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5956 if (ARC_BUF_COMPRESSED(buf)) {
5957 ASSERT3U(zp->zp_compress, !=, ZIO_COMPRESS_OFF);
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), zp, 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 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
6220 sizeof (arc_buf_hdr_t),
6221 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6222 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6223 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
6224 sizeof (arc_buf_hdr_t),
6225 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6226 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6227 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
6228 sizeof (arc_buf_hdr_t),
6229 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6230 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6231 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
6232 sizeof (arc_buf_hdr_t),
6233 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6234 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6235 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
6236 sizeof (arc_buf_hdr_t),
6237 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6238 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6239 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
6240 sizeof (arc_buf_hdr_t),
6241 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6242 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6243 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
6244 sizeof (arc_buf_hdr_t),
6245 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6246 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6247 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
6248 sizeof (arc_buf_hdr_t),
6249 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6250 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6251 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
6252 sizeof (arc_buf_hdr_t),
6253 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6254 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
6255 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
6256 sizeof (arc_buf_hdr_t),
6257 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6258 zfs_arc_num_sublists_per_state, 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;
6325 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
6326 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
6327 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
6329 mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
6330 cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
6332 /* Convert seconds to clock ticks */
6333 arc_min_prefetch_lifespan = 1 * hz;
6335 /* Start out with 1/8 of all memory */
6336 arc_c = kmem_size() / 8;
6341 * On architectures where the physical memory can be larger
6342 * than the addressable space (intel in 32-bit mode), we may
6343 * need to limit the cache to 1/8 of VM size.
6345 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
6347 #endif /* illumos */
6348 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
6349 arc_c_min = MAX(arc_c / 4, arc_abs_min);
6350 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
6351 if (arc_c * 8 >= 1 << 30)
6352 arc_c_max = (arc_c * 8) - (1 << 30);
6354 arc_c_max = arc_c_min;
6355 arc_c_max = MAX(arc_c * 5, arc_c_max);
6358 * In userland, there's only the memory pressure that we artificially
6359 * create (see arc_available_memory()). Don't let arc_c get too
6360 * small, because it can cause transactions to be larger than
6361 * arc_c, causing arc_tempreserve_space() to fail.
6364 arc_c_min = arc_c_max / 2;
6369 * Allow the tunables to override our calculations if they are
6372 if (zfs_arc_max > arc_abs_min && zfs_arc_max < kmem_size()) {
6373 arc_c_max = zfs_arc_max;
6374 arc_c_min = MIN(arc_c_min, arc_c_max);
6376 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
6377 arc_c_min = zfs_arc_min;
6381 arc_p = (arc_c >> 1);
6384 /* limit meta-data to 1/4 of the arc capacity */
6385 arc_meta_limit = arc_c_max / 4;
6387 /* Allow the tunable to override if it is reasonable */
6388 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6389 arc_meta_limit = zfs_arc_meta_limit;
6391 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6392 arc_c_min = arc_meta_limit / 2;
6394 if (zfs_arc_meta_min > 0) {
6395 arc_meta_min = zfs_arc_meta_min;
6397 arc_meta_min = arc_c_min / 2;
6400 if (zfs_arc_grow_retry > 0)
6401 arc_grow_retry = zfs_arc_grow_retry;
6403 if (zfs_arc_shrink_shift > 0)
6404 arc_shrink_shift = zfs_arc_shrink_shift;
6407 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6409 if (arc_no_grow_shift >= arc_shrink_shift)
6410 arc_no_grow_shift = arc_shrink_shift - 1;
6412 if (zfs_arc_p_min_shift > 0)
6413 arc_p_min_shift = zfs_arc_p_min_shift;
6415 if (zfs_arc_num_sublists_per_state < 1)
6416 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
6418 /* if kmem_flags are set, lets try to use less memory */
6419 if (kmem_debugging())
6421 if (arc_c < arc_c_min)
6424 zfs_arc_min = arc_c_min;
6425 zfs_arc_max = arc_c_max;
6430 arc_reclaim_thread_exit = B_FALSE;
6431 arc_dnlc_evicts_thread_exit = FALSE;
6433 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6434 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6436 if (arc_ksp != NULL) {
6437 arc_ksp->ks_data = &arc_stats;
6438 arc_ksp->ks_update = arc_kstat_update;
6439 kstat_install(arc_ksp);
6442 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6443 TS_RUN, minclsyspri);
6446 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
6447 EVENTHANDLER_PRI_FIRST);
6450 (void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
6451 TS_RUN, minclsyspri);
6457 * Calculate maximum amount of dirty data per pool.
6459 * If it has been set by /etc/system, take that.
6460 * Otherwise, use a percentage of physical memory defined by
6461 * zfs_dirty_data_max_percent (default 10%) with a cap at
6462 * zfs_dirty_data_max_max (default 4GB).
6464 if (zfs_dirty_data_max == 0) {
6465 zfs_dirty_data_max = ptob(physmem) *
6466 zfs_dirty_data_max_percent / 100;
6467 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6468 zfs_dirty_data_max_max);
6472 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
6473 prefetch_tunable_set = 1;
6476 if (prefetch_tunable_set == 0) {
6477 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
6479 printf(" add \"vfs.zfs.prefetch_disable=0\" "
6480 "to /boot/loader.conf.\n");
6481 zfs_prefetch_disable = 1;
6484 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
6485 prefetch_tunable_set == 0) {
6486 printf("ZFS NOTICE: Prefetch is disabled by default if less "
6487 "than 4GB of RAM is present;\n"
6488 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
6489 "to /boot/loader.conf.\n");
6490 zfs_prefetch_disable = 1;
6493 /* Warn about ZFS memory and address space requirements. */
6494 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
6495 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
6496 "expect unstable behavior.\n");
6498 if (kmem_size() < 512 * (1 << 20)) {
6499 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
6500 "expect unstable behavior.\n");
6501 printf(" Consider tuning vm.kmem_size and "
6502 "vm.kmem_size_max\n");
6503 printf(" in /boot/loader.conf.\n");
6511 mutex_enter(&arc_reclaim_lock);
6512 arc_reclaim_thread_exit = B_TRUE;
6514 * The reclaim thread will set arc_reclaim_thread_exit back to
6515 * B_FALSE when it is finished exiting; we're waiting for that.
6517 while (arc_reclaim_thread_exit) {
6518 cv_signal(&arc_reclaim_thread_cv);
6519 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6521 mutex_exit(&arc_reclaim_lock);
6523 /* Use B_TRUE to ensure *all* buffers are evicted */
6524 arc_flush(NULL, B_TRUE);
6526 mutex_enter(&arc_dnlc_evicts_lock);
6527 arc_dnlc_evicts_thread_exit = TRUE;
6529 * The user evicts thread will set arc_user_evicts_thread_exit
6530 * to FALSE when it is finished exiting; we're waiting for that.
6532 while (arc_dnlc_evicts_thread_exit) {
6533 cv_signal(&arc_dnlc_evicts_cv);
6534 cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
6536 mutex_exit(&arc_dnlc_evicts_lock);
6540 if (arc_ksp != NULL) {
6541 kstat_delete(arc_ksp);
6545 mutex_destroy(&arc_reclaim_lock);
6546 cv_destroy(&arc_reclaim_thread_cv);
6547 cv_destroy(&arc_reclaim_waiters_cv);
6549 mutex_destroy(&arc_dnlc_evicts_lock);
6550 cv_destroy(&arc_dnlc_evicts_cv);
6555 ASSERT0(arc_loaned_bytes);
6558 if (arc_event_lowmem != NULL)
6559 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
6566 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6567 * It uses dedicated storage devices to hold cached data, which are populated
6568 * using large infrequent writes. The main role of this cache is to boost
6569 * the performance of random read workloads. The intended L2ARC devices
6570 * include short-stroked disks, solid state disks, and other media with
6571 * substantially faster read latency than disk.
6573 * +-----------------------+
6575 * +-----------------------+
6578 * l2arc_feed_thread() arc_read()
6582 * +---------------+ |
6584 * +---------------+ |
6589 * +-------+ +-------+
6591 * | cache | | cache |
6592 * +-------+ +-------+
6593 * +=========+ .-----.
6594 * : L2ARC : |-_____-|
6595 * : devices : | Disks |
6596 * +=========+ `-_____-'
6598 * Read requests are satisfied from the following sources, in order:
6601 * 2) vdev cache of L2ARC devices
6603 * 4) vdev cache of disks
6606 * Some L2ARC device types exhibit extremely slow write performance.
6607 * To accommodate for this there are some significant differences between
6608 * the L2ARC and traditional cache design:
6610 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
6611 * the ARC behave as usual, freeing buffers and placing headers on ghost
6612 * lists. The ARC does not send buffers to the L2ARC during eviction as
6613 * this would add inflated write latencies for all ARC memory pressure.
6615 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6616 * It does this by periodically scanning buffers from the eviction-end of
6617 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6618 * not already there. It scans until a headroom of buffers is satisfied,
6619 * which itself is a buffer for ARC eviction. If a compressible buffer is
6620 * found during scanning and selected for writing to an L2ARC device, we
6621 * temporarily boost scanning headroom during the next scan cycle to make
6622 * sure we adapt to compression effects (which might significantly reduce
6623 * the data volume we write to L2ARC). The thread that does this is
6624 * l2arc_feed_thread(), illustrated below; example sizes are included to
6625 * provide a better sense of ratio than this diagram:
6628 * +---------------------+----------+
6629 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
6630 * +---------------------+----------+ | o L2ARC eligible
6631 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
6632 * +---------------------+----------+ |
6633 * 15.9 Gbytes ^ 32 Mbytes |
6635 * l2arc_feed_thread()
6637 * l2arc write hand <--[oooo]--'
6641 * +==============================+
6642 * L2ARC dev |####|#|###|###| |####| ... |
6643 * +==============================+
6646 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6647 * evicted, then the L2ARC has cached a buffer much sooner than it probably
6648 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
6649 * safe to say that this is an uncommon case, since buffers at the end of
6650 * the ARC lists have moved there due to inactivity.
6652 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6653 * then the L2ARC simply misses copying some buffers. This serves as a
6654 * pressure valve to prevent heavy read workloads from both stalling the ARC
6655 * with waits and clogging the L2ARC with writes. This also helps prevent
6656 * the potential for the L2ARC to churn if it attempts to cache content too
6657 * quickly, such as during backups of the entire pool.
6659 * 5. After system boot and before the ARC has filled main memory, there are
6660 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
6661 * lists can remain mostly static. Instead of searching from tail of these
6662 * lists as pictured, the l2arc_feed_thread() will search from the list heads
6663 * for eligible buffers, greatly increasing its chance of finding them.
6665 * The L2ARC device write speed is also boosted during this time so that
6666 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
6667 * there are no L2ARC reads, and no fear of degrading read performance
6668 * through increased writes.
6670 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6671 * the vdev queue can aggregate them into larger and fewer writes. Each
6672 * device is written to in a rotor fashion, sweeping writes through
6673 * available space then repeating.
6675 * 7. The L2ARC does not store dirty content. It never needs to flush
6676 * write buffers back to disk based storage.
6678 * 8. If an ARC buffer is written (and dirtied) which also exists in the
6679 * L2ARC, the now stale L2ARC buffer is immediately dropped.
6681 * The performance of the L2ARC can be tweaked by a number of tunables, which
6682 * may be necessary for different workloads:
6684 * l2arc_write_max max write bytes per interval
6685 * l2arc_write_boost extra write bytes during device warmup
6686 * l2arc_noprefetch skip caching prefetched buffers
6687 * l2arc_headroom number of max device writes to precache
6688 * l2arc_headroom_boost when we find compressed buffers during ARC
6689 * scanning, we multiply headroom by this
6690 * percentage factor for the next scan cycle,
6691 * since more compressed buffers are likely to
6693 * l2arc_feed_secs seconds between L2ARC writing
6695 * Tunables may be removed or added as future performance improvements are
6696 * integrated, and also may become zpool properties.
6698 * There are three key functions that control how the L2ARC warms up:
6700 * l2arc_write_eligible() check if a buffer is eligible to cache
6701 * l2arc_write_size() calculate how much to write
6702 * l2arc_write_interval() calculate sleep delay between writes
6704 * These three functions determine what to write, how much, and how quickly
6709 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
6712 * A buffer is *not* eligible for the L2ARC if it:
6713 * 1. belongs to a different spa.
6714 * 2. is already cached on the L2ARC.
6715 * 3. has an I/O in progress (it may be an incomplete read).
6716 * 4. is flagged not eligible (zfs property).
6718 if (hdr->b_spa != spa_guid) {
6719 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
6722 if (HDR_HAS_L2HDR(hdr)) {
6723 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
6726 if (HDR_IO_IN_PROGRESS(hdr)) {
6727 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
6730 if (!HDR_L2CACHE(hdr)) {
6731 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
6739 l2arc_write_size(void)
6744 * Make sure our globals have meaningful values in case the user
6747 size = l2arc_write_max;
6749 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6750 "be greater than zero, resetting it to the default (%d)",
6752 size = l2arc_write_max = L2ARC_WRITE_SIZE;
6755 if (arc_warm == B_FALSE)
6756 size += l2arc_write_boost;
6763 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
6765 clock_t interval, next, now;
6768 * If the ARC lists are busy, increase our write rate; if the
6769 * lists are stale, idle back. This is achieved by checking
6770 * how much we previously wrote - if it was more than half of
6771 * what we wanted, schedule the next write much sooner.
6773 if (l2arc_feed_again && wrote > (wanted / 2))
6774 interval = (hz * l2arc_feed_min_ms) / 1000;
6776 interval = hz * l2arc_feed_secs;
6778 now = ddi_get_lbolt();
6779 next = MAX(now, MIN(now + interval, began + interval));
6785 * Cycle through L2ARC devices. This is how L2ARC load balances.
6786 * If a device is returned, this also returns holding the spa config lock.
6788 static l2arc_dev_t *
6789 l2arc_dev_get_next(void)
6791 l2arc_dev_t *first, *next = NULL;
6794 * Lock out the removal of spas (spa_namespace_lock), then removal
6795 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
6796 * both locks will be dropped and a spa config lock held instead.
6798 mutex_enter(&spa_namespace_lock);
6799 mutex_enter(&l2arc_dev_mtx);
6801 /* if there are no vdevs, there is nothing to do */
6802 if (l2arc_ndev == 0)
6806 next = l2arc_dev_last;
6808 /* loop around the list looking for a non-faulted vdev */
6810 next = list_head(l2arc_dev_list);
6812 next = list_next(l2arc_dev_list, next);
6814 next = list_head(l2arc_dev_list);
6817 /* if we have come back to the start, bail out */
6820 else if (next == first)
6823 } while (vdev_is_dead(next->l2ad_vdev));
6825 /* if we were unable to find any usable vdevs, return NULL */
6826 if (vdev_is_dead(next->l2ad_vdev))
6829 l2arc_dev_last = next;
6832 mutex_exit(&l2arc_dev_mtx);
6835 * Grab the config lock to prevent the 'next' device from being
6836 * removed while we are writing to it.
6839 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
6840 mutex_exit(&spa_namespace_lock);
6846 * Free buffers that were tagged for destruction.
6849 l2arc_do_free_on_write()
6852 l2arc_data_free_t *df, *df_prev;
6854 mutex_enter(&l2arc_free_on_write_mtx);
6855 buflist = l2arc_free_on_write;
6857 for (df = list_tail(buflist); df; df = df_prev) {
6858 df_prev = list_prev(buflist, df);
6859 ASSERT3P(df->l2df_data, !=, NULL);
6860 if (df->l2df_type == ARC_BUFC_METADATA) {
6861 zio_buf_free(df->l2df_data, df->l2df_size);
6863 ASSERT(df->l2df_type == ARC_BUFC_DATA);
6864 zio_data_buf_free(df->l2df_data, df->l2df_size);
6866 list_remove(buflist, df);
6867 kmem_free(df, sizeof (l2arc_data_free_t));
6870 mutex_exit(&l2arc_free_on_write_mtx);
6874 * A write to a cache device has completed. Update all headers to allow
6875 * reads from these buffers to begin.
6878 l2arc_write_done(zio_t *zio)
6880 l2arc_write_callback_t *cb;
6883 arc_buf_hdr_t *head, *hdr, *hdr_prev;
6884 kmutex_t *hash_lock;
6885 int64_t bytes_dropped = 0;
6887 cb = zio->io_private;
6888 ASSERT3P(cb, !=, NULL);
6889 dev = cb->l2wcb_dev;
6890 ASSERT3P(dev, !=, NULL);
6891 head = cb->l2wcb_head;
6892 ASSERT3P(head, !=, NULL);
6893 buflist = &dev->l2ad_buflist;
6894 ASSERT3P(buflist, !=, NULL);
6895 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6896 l2arc_write_callback_t *, cb);
6898 if (zio->io_error != 0)
6899 ARCSTAT_BUMP(arcstat_l2_writes_error);
6902 * All writes completed, or an error was hit.
6905 mutex_enter(&dev->l2ad_mtx);
6906 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
6907 hdr_prev = list_prev(buflist, hdr);
6909 hash_lock = HDR_LOCK(hdr);
6912 * We cannot use mutex_enter or else we can deadlock
6913 * with l2arc_write_buffers (due to swapping the order
6914 * the hash lock and l2ad_mtx are taken).
6916 if (!mutex_tryenter(hash_lock)) {
6918 * Missed the hash lock. We must retry so we
6919 * don't leave the ARC_FLAG_L2_WRITING bit set.
6921 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6924 * We don't want to rescan the headers we've
6925 * already marked as having been written out, so
6926 * we reinsert the head node so we can pick up
6927 * where we left off.
6929 list_remove(buflist, head);
6930 list_insert_after(buflist, hdr, head);
6932 mutex_exit(&dev->l2ad_mtx);
6935 * We wait for the hash lock to become available
6936 * to try and prevent busy waiting, and increase
6937 * the chance we'll be able to acquire the lock
6938 * the next time around.
6940 mutex_enter(hash_lock);
6941 mutex_exit(hash_lock);
6946 * We could not have been moved into the arc_l2c_only
6947 * state while in-flight due to our ARC_FLAG_L2_WRITING
6948 * bit being set. Let's just ensure that's being enforced.
6950 ASSERT(HDR_HAS_L1HDR(hdr));
6952 if (zio->io_error != 0) {
6954 * Error - drop L2ARC entry.
6956 list_remove(buflist, hdr);
6958 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
6960 ARCSTAT_INCR(arcstat_l2_asize, -arc_hdr_size(hdr));
6961 ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
6963 bytes_dropped += arc_hdr_size(hdr);
6964 (void) refcount_remove_many(&dev->l2ad_alloc,
6965 arc_hdr_size(hdr), hdr);
6969 * Allow ARC to begin reads and ghost list evictions to
6972 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6974 mutex_exit(hash_lock);
6977 atomic_inc_64(&l2arc_writes_done);
6978 list_remove(buflist, head);
6979 ASSERT(!HDR_HAS_L1HDR(head));
6980 kmem_cache_free(hdr_l2only_cache, head);
6981 mutex_exit(&dev->l2ad_mtx);
6983 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6985 l2arc_do_free_on_write();
6987 kmem_free(cb, sizeof (l2arc_write_callback_t));
6991 * A read to a cache device completed. Validate buffer contents before
6992 * handing over to the regular ARC routines.
6995 l2arc_read_done(zio_t *zio)
6997 l2arc_read_callback_t *cb;
6999 kmutex_t *hash_lock;
7000 boolean_t valid_cksum;
7002 ASSERT3P(zio->io_vd, !=, NULL);
7003 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7005 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7007 cb = zio->io_private;
7008 ASSERT3P(cb, !=, NULL);
7009 hdr = cb->l2rcb_hdr;
7010 ASSERT3P(hdr, !=, NULL);
7012 hash_lock = HDR_LOCK(hdr);
7013 mutex_enter(hash_lock);
7014 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7017 * If the data was read into a temporary buffer,
7018 * move it and free the buffer.
7020 if (cb->l2rcb_data != NULL) {
7021 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7022 if (zio->io_error == 0) {
7023 bcopy(cb->l2rcb_data, hdr->b_l1hdr.b_pdata,
7028 * The following must be done regardless of whether
7029 * there was an error:
7030 * - free the temporary buffer
7031 * - point zio to the real ARC buffer
7032 * - set zio size accordingly
7033 * These are required because zio is either re-used for
7034 * an I/O of the block in the case of the error
7035 * or the zio is passed to arc_read_done() and it
7038 zio_data_buf_free(cb->l2rcb_data, zio->io_size);
7039 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7040 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_pdata;
7043 ASSERT3P(zio->io_data, !=, NULL);
7046 * Check this survived the L2ARC journey.
7048 ASSERT3P(zio->io_data, ==, hdr->b_l1hdr.b_pdata);
7049 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
7050 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
7052 valid_cksum = arc_cksum_is_equal(hdr, zio);
7053 if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7054 mutex_exit(hash_lock);
7055 zio->io_private = hdr;
7058 mutex_exit(hash_lock);
7060 * Buffer didn't survive caching. Increment stats and
7061 * reissue to the original storage device.
7063 if (zio->io_error != 0) {
7064 ARCSTAT_BUMP(arcstat_l2_io_error);
7066 zio->io_error = SET_ERROR(EIO);
7069 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7072 * If there's no waiter, issue an async i/o to the primary
7073 * storage now. If there *is* a waiter, the caller must
7074 * issue the i/o in a context where it's OK to block.
7076 if (zio->io_waiter == NULL) {
7077 zio_t *pio = zio_unique_parent(zio);
7079 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7081 zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7082 hdr->b_l1hdr.b_pdata, zio->io_size, arc_read_done,
7083 hdr, zio->io_priority, cb->l2rcb_flags,
7088 kmem_free(cb, sizeof (l2arc_read_callback_t));
7092 * This is the list priority from which the L2ARC will search for pages to
7093 * cache. This is used within loops (0..3) to cycle through lists in the
7094 * desired order. This order can have a significant effect on cache
7097 * Currently the metadata lists are hit first, MFU then MRU, followed by
7098 * the data lists. This function returns a locked list, and also returns
7101 static multilist_sublist_t *
7102 l2arc_sublist_lock(int list_num)
7104 multilist_t *ml = NULL;
7107 ASSERT(list_num >= 0 && list_num <= 3);
7111 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
7114 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
7117 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
7120 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
7125 * Return a randomly-selected sublist. This is acceptable
7126 * because the caller feeds only a little bit of data for each
7127 * call (8MB). Subsequent calls will result in different
7128 * sublists being selected.
7130 idx = multilist_get_random_index(ml);
7131 return (multilist_sublist_lock(ml, idx));
7135 * Evict buffers from the device write hand to the distance specified in
7136 * bytes. This distance may span populated buffers, it may span nothing.
7137 * This is clearing a region on the L2ARC device ready for writing.
7138 * If the 'all' boolean is set, every buffer is evicted.
7141 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7144 arc_buf_hdr_t *hdr, *hdr_prev;
7145 kmutex_t *hash_lock;
7148 buflist = &dev->l2ad_buflist;
7150 if (!all && dev->l2ad_first) {
7152 * This is the first sweep through the device. There is
7158 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7160 * When nearing the end of the device, evict to the end
7161 * before the device write hand jumps to the start.
7163 taddr = dev->l2ad_end;
7165 taddr = dev->l2ad_hand + distance;
7167 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7168 uint64_t, taddr, boolean_t, all);
7171 mutex_enter(&dev->l2ad_mtx);
7172 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
7173 hdr_prev = list_prev(buflist, hdr);
7175 hash_lock = HDR_LOCK(hdr);
7178 * We cannot use mutex_enter or else we can deadlock
7179 * with l2arc_write_buffers (due to swapping the order
7180 * the hash lock and l2ad_mtx are taken).
7182 if (!mutex_tryenter(hash_lock)) {
7184 * Missed the hash lock. Retry.
7186 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
7187 mutex_exit(&dev->l2ad_mtx);
7188 mutex_enter(hash_lock);
7189 mutex_exit(hash_lock);
7193 if (HDR_L2_WRITE_HEAD(hdr)) {
7195 * We hit a write head node. Leave it for
7196 * l2arc_write_done().
7198 list_remove(buflist, hdr);
7199 mutex_exit(hash_lock);
7203 if (!all && HDR_HAS_L2HDR(hdr) &&
7204 (hdr->b_l2hdr.b_daddr >= taddr ||
7205 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
7207 * We've evicted to the target address,
7208 * or the end of the device.
7210 mutex_exit(hash_lock);
7214 ASSERT(HDR_HAS_L2HDR(hdr));
7215 if (!HDR_HAS_L1HDR(hdr)) {
7216 ASSERT(!HDR_L2_READING(hdr));
7218 * This doesn't exist in the ARC. Destroy.
7219 * arc_hdr_destroy() will call list_remove()
7220 * and decrement arcstat_l2_size.
7222 arc_change_state(arc_anon, hdr, hash_lock);
7223 arc_hdr_destroy(hdr);
7225 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
7226 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
7228 * Invalidate issued or about to be issued
7229 * reads, since we may be about to write
7230 * over this location.
7232 if (HDR_L2_READING(hdr)) {
7233 ARCSTAT_BUMP(arcstat_l2_evict_reading);
7234 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7237 /* Ensure this header has finished being written */
7238 ASSERT(!HDR_L2_WRITING(hdr));
7240 arc_hdr_l2hdr_destroy(hdr);
7242 mutex_exit(hash_lock);
7244 mutex_exit(&dev->l2ad_mtx);
7248 * Find and write ARC buffers to the L2ARC device.
7250 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7251 * for reading until they have completed writing.
7252 * The headroom_boost is an in-out parameter used to maintain headroom boost
7253 * state between calls to this function.
7255 * Returns the number of bytes actually written (which may be smaller than
7256 * the delta by which the device hand has changed due to alignment).
7259 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7261 arc_buf_hdr_t *hdr, *hdr_prev, *head;
7262 uint64_t write_asize, write_psize, write_sz, headroom;
7264 l2arc_write_callback_t *cb;
7266 uint64_t guid = spa_load_guid(spa);
7269 ASSERT3P(dev->l2ad_vdev, !=, NULL);
7272 write_sz = write_asize = write_psize = 0;
7274 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7275 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7277 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
7279 * Copy buffers for L2ARC writing.
7281 for (try = 0; try <= 3; try++) {
7282 multilist_sublist_t *mls = l2arc_sublist_lock(try);
7283 uint64_t passed_sz = 0;
7285 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
7288 * L2ARC fast warmup.
7290 * Until the ARC is warm and starts to evict, read from the
7291 * head of the ARC lists rather than the tail.
7293 if (arc_warm == B_FALSE)
7294 hdr = multilist_sublist_head(mls);
7296 hdr = multilist_sublist_tail(mls);
7298 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
7300 headroom = target_sz * l2arc_headroom;
7301 if (zfs_compressed_arc_enabled)
7302 headroom = (headroom * l2arc_headroom_boost) / 100;
7304 for (; hdr; hdr = hdr_prev) {
7305 kmutex_t *hash_lock;
7307 if (arc_warm == B_FALSE)
7308 hdr_prev = multilist_sublist_next(mls, hdr);
7310 hdr_prev = multilist_sublist_prev(mls, hdr);
7311 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
7312 HDR_GET_LSIZE(hdr));
7314 hash_lock = HDR_LOCK(hdr);
7315 if (!mutex_tryenter(hash_lock)) {
7316 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
7318 * Skip this buffer rather than waiting.
7323 passed_sz += HDR_GET_LSIZE(hdr);
7324 if (passed_sz > headroom) {
7328 mutex_exit(hash_lock);
7329 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
7333 if (!l2arc_write_eligible(guid, hdr)) {
7334 mutex_exit(hash_lock);
7339 * We rely on the L1 portion of the header below, so
7340 * it's invalid for this header to have been evicted out
7341 * of the ghost cache, prior to being written out. The
7342 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7344 ASSERT(HDR_HAS_L1HDR(hdr));
7346 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7347 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
7348 ASSERT3U(arc_hdr_size(hdr), >, 0);
7349 uint64_t size = arc_hdr_size(hdr);
7350 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7353 if ((write_psize + asize) > target_sz) {
7355 mutex_exit(hash_lock);
7356 ARCSTAT_BUMP(arcstat_l2_write_full);
7362 * Insert a dummy header on the buflist so
7363 * l2arc_write_done() can find where the
7364 * write buffers begin without searching.
7366 mutex_enter(&dev->l2ad_mtx);
7367 list_insert_head(&dev->l2ad_buflist, head);
7368 mutex_exit(&dev->l2ad_mtx);
7371 sizeof (l2arc_write_callback_t), KM_SLEEP);
7372 cb->l2wcb_dev = dev;
7373 cb->l2wcb_head = head;
7374 pio = zio_root(spa, l2arc_write_done, cb,
7376 ARCSTAT_BUMP(arcstat_l2_write_pios);
7379 hdr->b_l2hdr.b_dev = dev;
7380 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7381 arc_hdr_set_flags(hdr,
7382 ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7384 mutex_enter(&dev->l2ad_mtx);
7385 list_insert_head(&dev->l2ad_buflist, hdr);
7386 mutex_exit(&dev->l2ad_mtx);
7388 (void) refcount_add_many(&dev->l2ad_alloc, size, hdr);
7391 * Normally the L2ARC can use the hdr's data, but if
7392 * we're sharing data between the hdr and one of its
7393 * bufs, L2ARC needs its own copy of the data so that
7394 * the ZIO below can't race with the buf consumer. To
7395 * ensure that this copy will be available for the
7396 * lifetime of the ZIO and be cleaned up afterwards, we
7397 * add it to the l2arc_free_on_write queue.
7400 if (!HDR_SHARED_DATA(hdr) && size == asize) {
7401 to_write = hdr->b_l1hdr.b_pdata;
7403 arc_buf_contents_t type = arc_buf_type(hdr);
7404 if (type == ARC_BUFC_METADATA) {
7405 to_write = zio_buf_alloc(asize);
7407 ASSERT3U(type, ==, ARC_BUFC_DATA);
7408 to_write = zio_data_buf_alloc(asize);
7411 bcopy(hdr->b_l1hdr.b_pdata, to_write, size);
7413 bzero(to_write + size, asize - size);
7414 l2arc_free_data_on_write(to_write, asize, type);
7416 wzio = zio_write_phys(pio, dev->l2ad_vdev,
7417 hdr->b_l2hdr.b_daddr, asize, to_write,
7418 ZIO_CHECKSUM_OFF, NULL, hdr,
7419 ZIO_PRIORITY_ASYNC_WRITE,
7420 ZIO_FLAG_CANFAIL, B_FALSE);
7422 write_sz += HDR_GET_LSIZE(hdr);
7423 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7426 write_asize += size;
7427 write_psize += asize;
7428 dev->l2ad_hand += asize;
7430 mutex_exit(hash_lock);
7432 (void) zio_nowait(wzio);
7435 multilist_sublist_unlock(mls);
7441 /* No buffers selected for writing? */
7444 ASSERT(!HDR_HAS_L1HDR(head));
7445 kmem_cache_free(hdr_l2only_cache, head);
7449 ASSERT3U(write_psize, <=, target_sz);
7450 ARCSTAT_BUMP(arcstat_l2_writes_sent);
7451 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
7452 ARCSTAT_INCR(arcstat_l2_size, write_sz);
7453 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
7454 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
7457 * Bump device hand to the device start if it is approaching the end.
7458 * l2arc_evict() will already have evicted ahead for this case.
7460 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7461 dev->l2ad_hand = dev->l2ad_start;
7462 dev->l2ad_first = B_FALSE;
7465 dev->l2ad_writing = B_TRUE;
7466 (void) zio_wait(pio);
7467 dev->l2ad_writing = B_FALSE;
7469 return (write_asize);
7473 * This thread feeds the L2ARC at regular intervals. This is the beating
7474 * heart of the L2ARC.
7477 l2arc_feed_thread(void *dummy __unused)
7482 uint64_t size, wrote;
7483 clock_t begin, next = ddi_get_lbolt();
7485 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7487 mutex_enter(&l2arc_feed_thr_lock);
7489 while (l2arc_thread_exit == 0) {
7490 CALLB_CPR_SAFE_BEGIN(&cpr);
7491 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7492 next - ddi_get_lbolt());
7493 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7494 next = ddi_get_lbolt() + hz;
7497 * Quick check for L2ARC devices.
7499 mutex_enter(&l2arc_dev_mtx);
7500 if (l2arc_ndev == 0) {
7501 mutex_exit(&l2arc_dev_mtx);
7504 mutex_exit(&l2arc_dev_mtx);
7505 begin = ddi_get_lbolt();
7508 * This selects the next l2arc device to write to, and in
7509 * doing so the next spa to feed from: dev->l2ad_spa. This
7510 * will return NULL if there are now no l2arc devices or if
7511 * they are all faulted.
7513 * If a device is returned, its spa's config lock is also
7514 * held to prevent device removal. l2arc_dev_get_next()
7515 * will grab and release l2arc_dev_mtx.
7517 if ((dev = l2arc_dev_get_next()) == NULL)
7520 spa = dev->l2ad_spa;
7521 ASSERT3P(spa, !=, NULL);
7524 * If the pool is read-only then force the feed thread to
7525 * sleep a little longer.
7527 if (!spa_writeable(spa)) {
7528 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7529 spa_config_exit(spa, SCL_L2ARC, dev);
7534 * Avoid contributing to memory pressure.
7536 if (arc_reclaim_needed()) {
7537 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7538 spa_config_exit(spa, SCL_L2ARC, dev);
7542 ARCSTAT_BUMP(arcstat_l2_feeds);
7544 size = l2arc_write_size();
7547 * Evict L2ARC buffers that will be overwritten.
7549 l2arc_evict(dev, size, B_FALSE);
7552 * Write ARC buffers.
7554 wrote = l2arc_write_buffers(spa, dev, size);
7557 * Calculate interval between writes.
7559 next = l2arc_write_interval(begin, size, wrote);
7560 spa_config_exit(spa, SCL_L2ARC, dev);
7563 l2arc_thread_exit = 0;
7564 cv_broadcast(&l2arc_feed_thr_cv);
7565 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
7570 l2arc_vdev_present(vdev_t *vd)
7574 mutex_enter(&l2arc_dev_mtx);
7575 for (dev = list_head(l2arc_dev_list); dev != NULL;
7576 dev = list_next(l2arc_dev_list, dev)) {
7577 if (dev->l2ad_vdev == vd)
7580 mutex_exit(&l2arc_dev_mtx);
7582 return (dev != NULL);
7586 * Add a vdev for use by the L2ARC. By this point the spa has already
7587 * validated the vdev and opened it.
7590 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7592 l2arc_dev_t *adddev;
7594 ASSERT(!l2arc_vdev_present(vd));
7596 vdev_ashift_optimize(vd);
7599 * Create a new l2arc device entry.
7601 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7602 adddev->l2ad_spa = spa;
7603 adddev->l2ad_vdev = vd;
7604 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7605 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7606 adddev->l2ad_hand = adddev->l2ad_start;
7607 adddev->l2ad_first = B_TRUE;
7608 adddev->l2ad_writing = B_FALSE;
7610 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7612 * This is a list of all ARC buffers that are still valid on the
7615 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7616 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7618 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7619 refcount_create(&adddev->l2ad_alloc);
7622 * Add device to global list
7624 mutex_enter(&l2arc_dev_mtx);
7625 list_insert_head(l2arc_dev_list, adddev);
7626 atomic_inc_64(&l2arc_ndev);
7627 mutex_exit(&l2arc_dev_mtx);
7631 * Remove a vdev from the L2ARC.
7634 l2arc_remove_vdev(vdev_t *vd)
7636 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7639 * Find the device by vdev
7641 mutex_enter(&l2arc_dev_mtx);
7642 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7643 nextdev = list_next(l2arc_dev_list, dev);
7644 if (vd == dev->l2ad_vdev) {
7649 ASSERT3P(remdev, !=, NULL);
7652 * Remove device from global list
7654 list_remove(l2arc_dev_list, remdev);
7655 l2arc_dev_last = NULL; /* may have been invalidated */
7656 atomic_dec_64(&l2arc_ndev);
7657 mutex_exit(&l2arc_dev_mtx);
7660 * Clear all buflists and ARC references. L2ARC device flush.
7662 l2arc_evict(remdev, 0, B_TRUE);
7663 list_destroy(&remdev->l2ad_buflist);
7664 mutex_destroy(&remdev->l2ad_mtx);
7665 refcount_destroy(&remdev->l2ad_alloc);
7666 kmem_free(remdev, sizeof (l2arc_dev_t));
7672 l2arc_thread_exit = 0;
7674 l2arc_writes_sent = 0;
7675 l2arc_writes_done = 0;
7677 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7678 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7679 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7680 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7682 l2arc_dev_list = &L2ARC_dev_list;
7683 l2arc_free_on_write = &L2ARC_free_on_write;
7684 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7685 offsetof(l2arc_dev_t, l2ad_node));
7686 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7687 offsetof(l2arc_data_free_t, l2df_list_node));
7694 * This is called from dmu_fini(), which is called from spa_fini();
7695 * Because of this, we can assume that all l2arc devices have
7696 * already been removed when the pools themselves were removed.
7699 l2arc_do_free_on_write();
7701 mutex_destroy(&l2arc_feed_thr_lock);
7702 cv_destroy(&l2arc_feed_thr_cv);
7703 mutex_destroy(&l2arc_dev_mtx);
7704 mutex_destroy(&l2arc_free_on_write_mtx);
7706 list_destroy(l2arc_dev_list);
7707 list_destroy(l2arc_free_on_write);
7713 if (!(spa_mode_global & FWRITE))
7716 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7717 TS_RUN, minclsyspri);
7723 if (!(spa_mode_global & FWRITE))
7726 mutex_enter(&l2arc_feed_thr_lock);
7727 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7728 l2arc_thread_exit = 1;
7729 while (l2arc_thread_exit != 0)
7730 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7731 mutex_exit(&l2arc_feed_thr_lock);