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 * Arc buffers may have an associated eviction callback function.
103 * This function will be invoked prior to removing the buffer (e.g.
104 * in arc_do_user_evicts()). Note however that the data associated
105 * with the buffer may be evicted prior to the callback. The callback
106 * must be made with *no locks held* (to prevent deadlock). Additionally,
107 * the users of callbacks must ensure that their private data is
108 * protected from simultaneous callbacks from arc_clear_callback()
109 * and arc_do_user_evicts().
111 * Note that the majority of the performance stats are manipulated
112 * with atomic operations.
114 * The L2ARC uses the l2ad_mtx on each vdev for the following:
116 * - L2ARC buflist creation
117 * - L2ARC buflist eviction
118 * - L2ARC write completion, which walks L2ARC buflists
119 * - ARC header destruction, as it removes from L2ARC buflists
120 * - ARC header release, as it removes from L2ARC buflists
126 * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
127 * This structure can point either to a block that is still in the cache or to
128 * one that is only accessible in an L2 ARC device, or it can provide
129 * information about a block that was recently evicted. If a block is
130 * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
131 * information to retrieve it from the L2ARC device. This information is
132 * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
133 * that is in this state cannot access the data directly.
135 * Blocks that are actively being referenced or have not been evicted
136 * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
137 * the arc_buf_hdr_t that will point to the data block in memory. A block can
138 * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
139 * caches data in two ways -- in a list of arc buffers (arc_buf_t) and
140 * also in the arc_buf_hdr_t's private physical data block pointer (b_pdata).
141 * Each arc buffer (arc_buf_t) is being actively accessed by a specific ARC
142 * consumer, and always contains uncompressed data. The ARC will provide
143 * references to this data and will keep it cached until it is no longer in
144 * use. Typically, the arc will try to cache only the L1ARC's physical data
145 * block and will aggressively evict any arc_buf_t that is no longer referenced.
146 * The amount of memory consumed by the arc_buf_t's can be seen via the
147 * "overhead_size" kstat.
161 * | b_buf +------------>+---------+ arc_buf_t
162 * | | |b_next +---->+---------+
163 * | b_pdata +-+ |---------| |b_next +-->NULL
164 * +-----------+ | | | +---------+
166 * | +---------+ | |b_data +-+
167 * +->+------+ | +---------+ |
168 * (potentially) | | | |
171 * +->+------+ +------+
172 * uncompressed | | | |
176 * The L1ARC's data pointer, however, may or may not be uncompressed. The
177 * ARC has the ability to store the physical data (b_pdata) associated with
178 * the DVA of the arc_buf_hdr_t. Since the b_pdata is a copy of the on-disk
179 * physical block, it will match its on-disk compression characteristics.
180 * If the block on-disk is compressed, then the physical data block
181 * in the cache will also be compressed and vice-versa. This behavior
182 * can be disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
183 * compressed ARC functionality is disabled, the b_pdata will point to an
184 * uncompressed version of the on-disk data.
186 * When a consumer reads a block, the ARC must first look to see if the
187 * arc_buf_hdr_t is cached. If the hdr is cached and already has an arc_buf_t,
188 * then an additional arc_buf_t is allocated and the uncompressed data is
189 * bcopied from the existing arc_buf_t. If the hdr is cached but does not
190 * have an arc_buf_t, then the ARC allocates a new arc_buf_t and decompresses
191 * the b_pdata contents into the arc_buf_t's b_data. If the arc_buf_hdr_t's
192 * b_pdata is not compressed, then the block is shared with the newly
193 * allocated arc_buf_t. This block sharing only occurs with one arc_buf_t
194 * in the arc buffer chain. Sharing the block reduces the memory overhead
195 * required when the hdr is caching uncompressed blocks or the compressed
196 * arc functionality has been disabled via 'zfs_compressed_arc_enabled'.
198 * The diagram below shows an example of an uncompressed ARC hdr that is
199 * sharing its data with an arc_buf_t:
211 * | | arc_buf_t (shared)
212 * | b_buf +------------>+---------+ arc_buf_t
213 * | | |b_next +---->+---------+
214 * | b_pdata +-+ |---------| |b_next +-->NULL
215 * +-----------+ | | | +---------+
217 * | +---------+ | |b_data +-+
218 * +->+------+ | +---------+ |
220 * uncompressed | | | |
223 * | uncompressed | | |
226 * +---------------------------------+
228 * Writing to the arc requires that the ARC first discard the b_pdata
229 * since the physical block is about to be rewritten. The new data contents
230 * will be contained in the arc_buf_t (uncompressed). As the I/O pipeline
231 * performs the write, it may compress the data before writing it to disk.
232 * The ARC will be called with the transformed data and will bcopy the
233 * transformed on-disk block into a newly allocated b_pdata.
235 * When the L2ARC is in use, it will also take advantage of the b_pdata. The
236 * L2ARC will always write the contents of b_pdata to the L2ARC. This means
237 * that when compressed arc is enabled that the L2ARC blocks are identical
238 * to the on-disk block in the main data pool. This provides a significant
239 * advantage since the ARC can leverage the bp's checksum when reading from the
240 * L2ARC to determine if the contents are valid. However, if the compressed
241 * arc is disabled, then the L2ARC's block must be transformed to look
242 * like the physical block in the main data pool before comparing the
243 * checksum and determining its validity.
248 #include <sys/spa_impl.h>
249 #include <sys/zio_compress.h>
250 #include <sys/zio_checksum.h>
251 #include <sys/zfs_context.h>
253 #include <sys/refcount.h>
254 #include <sys/vdev.h>
255 #include <sys/vdev_impl.h>
256 #include <sys/dsl_pool.h>
257 #include <sys/multilist.h>
259 #include <sys/dnlc.h>
261 #include <sys/callb.h>
262 #include <sys/kstat.h>
263 #include <sys/trim_map.h>
264 #include <zfs_fletcher.h>
267 #include <machine/vmparam.h>
271 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
272 boolean_t arc_watch = B_FALSE;
277 static kmutex_t arc_reclaim_lock;
278 static kcondvar_t arc_reclaim_thread_cv;
279 static boolean_t arc_reclaim_thread_exit;
280 static kcondvar_t arc_reclaim_waiters_cv;
282 uint_t arc_reduce_dnlc_percent = 3;
285 * The number of headers to evict in arc_evict_state_impl() before
286 * dropping the sublist lock and evicting from another sublist. A lower
287 * value means we're more likely to evict the "correct" header (i.e. the
288 * oldest header in the arc state), but comes with higher overhead
289 * (i.e. more invocations of arc_evict_state_impl()).
291 int zfs_arc_evict_batch_limit = 10;
294 * The number of sublists used for each of the arc state lists. If this
295 * is not set to a suitable value by the user, it will be configured to
296 * the number of CPUs on the system in arc_init().
298 int zfs_arc_num_sublists_per_state = 0;
300 /* number of seconds before growing cache again */
301 static int arc_grow_retry = 60;
303 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
304 int zfs_arc_overflow_shift = 8;
306 /* shift of arc_c for calculating both min and max arc_p */
307 static int arc_p_min_shift = 4;
309 /* log2(fraction of arc to reclaim) */
310 static int arc_shrink_shift = 7;
313 * log2(fraction of ARC which must be free to allow growing).
314 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
315 * when reading a new block into the ARC, we will evict an equal-sized block
318 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
319 * we will still not allow it to grow.
321 int arc_no_grow_shift = 5;
325 * minimum lifespan of a prefetch block in clock ticks
326 * (initialized in arc_init())
328 static int arc_min_prefetch_lifespan;
331 * If this percent of memory is free, don't throttle.
333 int arc_lotsfree_percent = 10;
336 extern boolean_t zfs_prefetch_disable;
339 * The arc has filled available memory and has now warmed up.
341 static boolean_t arc_warm;
344 * These tunables are for performance analysis.
346 uint64_t zfs_arc_max;
347 uint64_t zfs_arc_min;
348 uint64_t zfs_arc_meta_limit = 0;
349 uint64_t zfs_arc_meta_min = 0;
350 int zfs_arc_grow_retry = 0;
351 int zfs_arc_shrink_shift = 0;
352 int zfs_arc_p_min_shift = 0;
353 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
354 u_int zfs_arc_free_target = 0;
356 /* Absolute min for arc min / max is 16MB. */
357 static uint64_t arc_abs_min = 16 << 20;
359 boolean_t zfs_compressed_arc_enabled = B_TRUE;
361 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
362 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
363 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
364 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
366 #if defined(__FreeBSD__) && defined(_KERNEL)
368 arc_free_target_init(void *unused __unused)
371 zfs_arc_free_target = vm_pageout_wakeup_thresh;
373 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
374 arc_free_target_init, NULL);
376 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
377 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
378 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
379 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
380 TUNABLE_QUAD("vfs.zfs.arc_average_blocksize", &zfs_arc_average_blocksize);
381 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
382 SYSCTL_DECL(_vfs_zfs);
383 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
384 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
385 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
386 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
387 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
388 &zfs_arc_average_blocksize, 0,
389 "ARC average blocksize");
390 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
391 &arc_shrink_shift, 0,
392 "log2(fraction of arc to reclaim)");
393 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
394 &zfs_compressed_arc_enabled, 0, "Enable compressed ARC");
397 * We don't have a tunable for arc_free_target due to the dependency on
398 * pagedaemon initialisation.
400 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
401 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
402 sysctl_vfs_zfs_arc_free_target, "IU",
403 "Desired number of free pages below which ARC triggers reclaim");
406 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
411 val = zfs_arc_free_target;
412 err = sysctl_handle_int(oidp, &val, 0, req);
413 if (err != 0 || req->newptr == NULL)
418 if (val > cnt.v_page_count)
421 zfs_arc_free_target = val;
427 * Must be declared here, before the definition of corresponding kstat
428 * macro which uses the same names will confuse the compiler.
430 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
431 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
432 sysctl_vfs_zfs_arc_meta_limit, "QU",
433 "ARC metadata limit");
437 * Note that buffers can be in one of 6 states:
438 * ARC_anon - anonymous (discussed below)
439 * ARC_mru - recently used, currently cached
440 * ARC_mru_ghost - recentely used, no longer in cache
441 * ARC_mfu - frequently used, currently cached
442 * ARC_mfu_ghost - frequently used, no longer in cache
443 * ARC_l2c_only - exists in L2ARC but not other states
444 * When there are no active references to the buffer, they are
445 * are linked onto a list in one of these arc states. These are
446 * the only buffers that can be evicted or deleted. Within each
447 * state there are multiple lists, one for meta-data and one for
448 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
449 * etc.) is tracked separately so that it can be managed more
450 * explicitly: favored over data, limited explicitly.
452 * Anonymous buffers are buffers that are not associated with
453 * a DVA. These are buffers that hold dirty block copies
454 * before they are written to stable storage. By definition,
455 * they are "ref'd" and are considered part of arc_mru
456 * that cannot be freed. Generally, they will aquire a DVA
457 * as they are written and migrate onto the arc_mru list.
459 * The ARC_l2c_only state is for buffers that are in the second
460 * level ARC but no longer in any of the ARC_m* lists. The second
461 * level ARC itself may also contain buffers that are in any of
462 * the ARC_m* states - meaning that a buffer can exist in two
463 * places. The reason for the ARC_l2c_only state is to keep the
464 * buffer header in the hash table, so that reads that hit the
465 * second level ARC benefit from these fast lookups.
468 typedef struct arc_state {
470 * list of evictable buffers
472 multilist_t arcs_list[ARC_BUFC_NUMTYPES];
474 * total amount of evictable data in this state
476 refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
478 * total amount of data in this state; this includes: evictable,
479 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
481 refcount_t arcs_size;
485 static arc_state_t ARC_anon;
486 static arc_state_t ARC_mru;
487 static arc_state_t ARC_mru_ghost;
488 static arc_state_t ARC_mfu;
489 static arc_state_t ARC_mfu_ghost;
490 static arc_state_t ARC_l2c_only;
492 typedef struct arc_stats {
493 kstat_named_t arcstat_hits;
494 kstat_named_t arcstat_misses;
495 kstat_named_t arcstat_demand_data_hits;
496 kstat_named_t arcstat_demand_data_misses;
497 kstat_named_t arcstat_demand_metadata_hits;
498 kstat_named_t arcstat_demand_metadata_misses;
499 kstat_named_t arcstat_prefetch_data_hits;
500 kstat_named_t arcstat_prefetch_data_misses;
501 kstat_named_t arcstat_prefetch_metadata_hits;
502 kstat_named_t arcstat_prefetch_metadata_misses;
503 kstat_named_t arcstat_mru_hits;
504 kstat_named_t arcstat_mru_ghost_hits;
505 kstat_named_t arcstat_mfu_hits;
506 kstat_named_t arcstat_mfu_ghost_hits;
507 kstat_named_t arcstat_allocated;
508 kstat_named_t arcstat_deleted;
510 * Number of buffers that could not be evicted because the hash lock
511 * was held by another thread. The lock may not necessarily be held
512 * by something using the same buffer, since hash locks are shared
513 * by multiple buffers.
515 kstat_named_t arcstat_mutex_miss;
517 * Number of buffers skipped because they have I/O in progress, are
518 * indrect prefetch buffers that have not lived long enough, or are
519 * not from the spa we're trying to evict from.
521 kstat_named_t arcstat_evict_skip;
523 * Number of times arc_evict_state() was unable to evict enough
524 * buffers to reach it's target amount.
526 kstat_named_t arcstat_evict_not_enough;
527 kstat_named_t arcstat_evict_l2_cached;
528 kstat_named_t arcstat_evict_l2_eligible;
529 kstat_named_t arcstat_evict_l2_ineligible;
530 kstat_named_t arcstat_evict_l2_skip;
531 kstat_named_t arcstat_hash_elements;
532 kstat_named_t arcstat_hash_elements_max;
533 kstat_named_t arcstat_hash_collisions;
534 kstat_named_t arcstat_hash_chains;
535 kstat_named_t arcstat_hash_chain_max;
536 kstat_named_t arcstat_p;
537 kstat_named_t arcstat_c;
538 kstat_named_t arcstat_c_min;
539 kstat_named_t arcstat_c_max;
540 kstat_named_t arcstat_size;
542 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pdata.
543 * Note that the compressed bytes may match the uncompressed bytes
544 * if the block is either not compressed or compressed arc is disabled.
546 kstat_named_t arcstat_compressed_size;
548 * Uncompressed size of the data stored in b_pdata. If compressed
549 * arc is disabled then this value will be identical to the stat
552 kstat_named_t arcstat_uncompressed_size;
554 * Number of bytes stored in all the arc_buf_t's. This is classified
555 * as "overhead" since this data is typically short-lived and will
556 * be evicted from the arc when it becomes unreferenced unless the
557 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
558 * values have been set (see comment in dbuf.c for more information).
560 kstat_named_t arcstat_overhead_size;
562 * Number of bytes consumed by internal ARC structures necessary
563 * for tracking purposes; these structures are not actually
564 * backed by ARC buffers. This includes arc_buf_hdr_t structures
565 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
566 * caches), and arc_buf_t structures (allocated via arc_buf_t
569 kstat_named_t arcstat_hdr_size;
571 * Number of bytes consumed by ARC buffers of type equal to
572 * ARC_BUFC_DATA. This is generally consumed by buffers backing
573 * on disk user data (e.g. plain file contents).
575 kstat_named_t arcstat_data_size;
577 * Number of bytes consumed by ARC buffers of type equal to
578 * ARC_BUFC_METADATA. This is generally consumed by buffers
579 * backing on disk data that is used for internal ZFS
580 * structures (e.g. ZAP, dnode, indirect blocks, etc).
582 kstat_named_t arcstat_metadata_size;
584 * Number of bytes consumed by various buffers and structures
585 * not actually backed with ARC buffers. This includes bonus
586 * buffers (allocated directly via zio_buf_* functions),
587 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
588 * cache), and dnode_t structures (allocated via dnode_t cache).
590 kstat_named_t arcstat_other_size;
592 * Total number of bytes consumed by ARC buffers residing in the
593 * arc_anon state. This includes *all* buffers in the arc_anon
594 * state; e.g. data, metadata, evictable, and unevictable buffers
595 * are all included in this value.
597 kstat_named_t arcstat_anon_size;
599 * Number of bytes consumed by ARC buffers that meet the
600 * following criteria: backing buffers of type ARC_BUFC_DATA,
601 * residing in the arc_anon state, and are eligible for eviction
602 * (e.g. have no outstanding holds on the buffer).
604 kstat_named_t arcstat_anon_evictable_data;
606 * Number of bytes consumed by ARC buffers that meet the
607 * following criteria: backing buffers of type ARC_BUFC_METADATA,
608 * residing in the arc_anon state, and are eligible for eviction
609 * (e.g. have no outstanding holds on the buffer).
611 kstat_named_t arcstat_anon_evictable_metadata;
613 * Total number of bytes consumed by ARC buffers residing in the
614 * arc_mru state. This includes *all* buffers in the arc_mru
615 * state; e.g. data, metadata, evictable, and unevictable buffers
616 * are all included in this value.
618 kstat_named_t arcstat_mru_size;
620 * Number of bytes consumed by ARC buffers that meet the
621 * following criteria: backing buffers of type ARC_BUFC_DATA,
622 * residing in the arc_mru state, and are eligible for eviction
623 * (e.g. have no outstanding holds on the buffer).
625 kstat_named_t arcstat_mru_evictable_data;
627 * Number of bytes consumed by ARC buffers that meet the
628 * following criteria: backing buffers of type ARC_BUFC_METADATA,
629 * residing in the arc_mru state, and are eligible for eviction
630 * (e.g. have no outstanding holds on the buffer).
632 kstat_named_t arcstat_mru_evictable_metadata;
634 * Total number of bytes that *would have been* consumed by ARC
635 * buffers in the arc_mru_ghost state. The key thing to note
636 * here, is the fact that this size doesn't actually indicate
637 * RAM consumption. The ghost lists only consist of headers and
638 * don't actually have ARC buffers linked off of these headers.
639 * Thus, *if* the headers had associated ARC buffers, these
640 * buffers *would have* consumed this number of bytes.
642 kstat_named_t arcstat_mru_ghost_size;
644 * Number of bytes that *would have been* consumed by ARC
645 * buffers that are eligible for eviction, of type
646 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
648 kstat_named_t arcstat_mru_ghost_evictable_data;
650 * Number of bytes that *would have been* consumed by ARC
651 * buffers that are eligible for eviction, of type
652 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
654 kstat_named_t arcstat_mru_ghost_evictable_metadata;
656 * Total number of bytes consumed by ARC buffers residing in the
657 * arc_mfu state. This includes *all* buffers in the arc_mfu
658 * state; e.g. data, metadata, evictable, and unevictable buffers
659 * are all included in this value.
661 kstat_named_t arcstat_mfu_size;
663 * Number of bytes consumed by ARC buffers that are eligible for
664 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
667 kstat_named_t arcstat_mfu_evictable_data;
669 * Number of bytes consumed by ARC buffers that are eligible for
670 * eviction, of type ARC_BUFC_METADATA, and reside in the
673 kstat_named_t arcstat_mfu_evictable_metadata;
675 * Total number of bytes that *would have been* consumed by ARC
676 * buffers in the arc_mfu_ghost state. See the comment above
677 * arcstat_mru_ghost_size for more details.
679 kstat_named_t arcstat_mfu_ghost_size;
681 * Number of bytes that *would have been* consumed by ARC
682 * buffers that are eligible for eviction, of type
683 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
685 kstat_named_t arcstat_mfu_ghost_evictable_data;
687 * Number of bytes that *would have been* consumed by ARC
688 * buffers that are eligible for eviction, of type
689 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
691 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
692 kstat_named_t arcstat_l2_hits;
693 kstat_named_t arcstat_l2_misses;
694 kstat_named_t arcstat_l2_feeds;
695 kstat_named_t arcstat_l2_rw_clash;
696 kstat_named_t arcstat_l2_read_bytes;
697 kstat_named_t arcstat_l2_write_bytes;
698 kstat_named_t arcstat_l2_writes_sent;
699 kstat_named_t arcstat_l2_writes_done;
700 kstat_named_t arcstat_l2_writes_error;
701 kstat_named_t arcstat_l2_writes_lock_retry;
702 kstat_named_t arcstat_l2_evict_lock_retry;
703 kstat_named_t arcstat_l2_evict_reading;
704 kstat_named_t arcstat_l2_evict_l1cached;
705 kstat_named_t arcstat_l2_free_on_write;
706 kstat_named_t arcstat_l2_abort_lowmem;
707 kstat_named_t arcstat_l2_cksum_bad;
708 kstat_named_t arcstat_l2_io_error;
709 kstat_named_t arcstat_l2_size;
710 kstat_named_t arcstat_l2_asize;
711 kstat_named_t arcstat_l2_hdr_size;
712 kstat_named_t arcstat_l2_padding_needed;
713 kstat_named_t arcstat_l2_write_trylock_fail;
714 kstat_named_t arcstat_l2_write_passed_headroom;
715 kstat_named_t arcstat_l2_write_spa_mismatch;
716 kstat_named_t arcstat_l2_write_in_l2;
717 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
718 kstat_named_t arcstat_l2_write_not_cacheable;
719 kstat_named_t arcstat_l2_write_full;
720 kstat_named_t arcstat_l2_write_buffer_iter;
721 kstat_named_t arcstat_l2_write_pios;
722 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
723 kstat_named_t arcstat_l2_write_buffer_list_iter;
724 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
725 kstat_named_t arcstat_memory_throttle_count;
726 kstat_named_t arcstat_meta_used;
727 kstat_named_t arcstat_meta_limit;
728 kstat_named_t arcstat_meta_max;
729 kstat_named_t arcstat_meta_min;
730 kstat_named_t arcstat_sync_wait_for_async;
731 kstat_named_t arcstat_demand_hit_predictive_prefetch;
734 static arc_stats_t arc_stats = {
735 { "hits", KSTAT_DATA_UINT64 },
736 { "misses", KSTAT_DATA_UINT64 },
737 { "demand_data_hits", KSTAT_DATA_UINT64 },
738 { "demand_data_misses", KSTAT_DATA_UINT64 },
739 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
740 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
741 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
742 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
743 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
744 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
745 { "mru_hits", KSTAT_DATA_UINT64 },
746 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
747 { "mfu_hits", KSTAT_DATA_UINT64 },
748 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
749 { "allocated", KSTAT_DATA_UINT64 },
750 { "deleted", KSTAT_DATA_UINT64 },
751 { "mutex_miss", KSTAT_DATA_UINT64 },
752 { "evict_skip", KSTAT_DATA_UINT64 },
753 { "evict_not_enough", KSTAT_DATA_UINT64 },
754 { "evict_l2_cached", KSTAT_DATA_UINT64 },
755 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
756 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
757 { "evict_l2_skip", KSTAT_DATA_UINT64 },
758 { "hash_elements", KSTAT_DATA_UINT64 },
759 { "hash_elements_max", KSTAT_DATA_UINT64 },
760 { "hash_collisions", KSTAT_DATA_UINT64 },
761 { "hash_chains", KSTAT_DATA_UINT64 },
762 { "hash_chain_max", KSTAT_DATA_UINT64 },
763 { "p", KSTAT_DATA_UINT64 },
764 { "c", KSTAT_DATA_UINT64 },
765 { "c_min", KSTAT_DATA_UINT64 },
766 { "c_max", KSTAT_DATA_UINT64 },
767 { "size", KSTAT_DATA_UINT64 },
768 { "compressed_size", KSTAT_DATA_UINT64 },
769 { "uncompressed_size", KSTAT_DATA_UINT64 },
770 { "overhead_size", KSTAT_DATA_UINT64 },
771 { "hdr_size", KSTAT_DATA_UINT64 },
772 { "data_size", KSTAT_DATA_UINT64 },
773 { "metadata_size", KSTAT_DATA_UINT64 },
774 { "other_size", KSTAT_DATA_UINT64 },
775 { "anon_size", KSTAT_DATA_UINT64 },
776 { "anon_evictable_data", KSTAT_DATA_UINT64 },
777 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
778 { "mru_size", KSTAT_DATA_UINT64 },
779 { "mru_evictable_data", KSTAT_DATA_UINT64 },
780 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
781 { "mru_ghost_size", KSTAT_DATA_UINT64 },
782 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
783 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
784 { "mfu_size", KSTAT_DATA_UINT64 },
785 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
786 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
787 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
788 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
789 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
790 { "l2_hits", KSTAT_DATA_UINT64 },
791 { "l2_misses", KSTAT_DATA_UINT64 },
792 { "l2_feeds", KSTAT_DATA_UINT64 },
793 { "l2_rw_clash", KSTAT_DATA_UINT64 },
794 { "l2_read_bytes", KSTAT_DATA_UINT64 },
795 { "l2_write_bytes", KSTAT_DATA_UINT64 },
796 { "l2_writes_sent", KSTAT_DATA_UINT64 },
797 { "l2_writes_done", KSTAT_DATA_UINT64 },
798 { "l2_writes_error", KSTAT_DATA_UINT64 },
799 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
800 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
801 { "l2_evict_reading", KSTAT_DATA_UINT64 },
802 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
803 { "l2_free_on_write", KSTAT_DATA_UINT64 },
804 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
805 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
806 { "l2_io_error", KSTAT_DATA_UINT64 },
807 { "l2_size", KSTAT_DATA_UINT64 },
808 { "l2_asize", KSTAT_DATA_UINT64 },
809 { "l2_hdr_size", KSTAT_DATA_UINT64 },
810 { "l2_padding_needed", KSTAT_DATA_UINT64 },
811 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
812 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
813 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
814 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
815 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
816 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
817 { "l2_write_full", KSTAT_DATA_UINT64 },
818 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
819 { "l2_write_pios", KSTAT_DATA_UINT64 },
820 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
821 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
822 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
823 { "memory_throttle_count", KSTAT_DATA_UINT64 },
824 { "arc_meta_used", KSTAT_DATA_UINT64 },
825 { "arc_meta_limit", KSTAT_DATA_UINT64 },
826 { "arc_meta_max", KSTAT_DATA_UINT64 },
827 { "arc_meta_min", KSTAT_DATA_UINT64 },
828 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
829 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
832 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
834 #define ARCSTAT_INCR(stat, val) \
835 atomic_add_64(&arc_stats.stat.value.ui64, (val))
837 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
838 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
840 #define ARCSTAT_MAX(stat, val) { \
842 while ((val) > (m = arc_stats.stat.value.ui64) && \
843 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
847 #define ARCSTAT_MAXSTAT(stat) \
848 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
851 * We define a macro to allow ARC hits/misses to be easily broken down by
852 * two separate conditions, giving a total of four different subtypes for
853 * each of hits and misses (so eight statistics total).
855 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
858 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
860 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
864 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
866 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
871 static arc_state_t *arc_anon;
872 static arc_state_t *arc_mru;
873 static arc_state_t *arc_mru_ghost;
874 static arc_state_t *arc_mfu;
875 static arc_state_t *arc_mfu_ghost;
876 static arc_state_t *arc_l2c_only;
879 * There are several ARC variables that are critical to export as kstats --
880 * but we don't want to have to grovel around in the kstat whenever we wish to
881 * manipulate them. For these variables, we therefore define them to be in
882 * terms of the statistic variable. This assures that we are not introducing
883 * the possibility of inconsistency by having shadow copies of the variables,
884 * while still allowing the code to be readable.
886 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
887 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
888 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
889 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
890 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
891 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
892 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
893 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
894 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
896 /* compressed size of entire arc */
897 #define arc_compressed_size ARCSTAT(arcstat_compressed_size)
898 /* uncompressed size of entire arc */
899 #define arc_uncompressed_size ARCSTAT(arcstat_uncompressed_size)
900 /* number of bytes in the arc from arc_buf_t's */
901 #define arc_overhead_size ARCSTAT(arcstat_overhead_size)
903 static int arc_no_grow; /* Don't try to grow cache size */
904 static uint64_t arc_tempreserve;
905 static uint64_t arc_loaned_bytes;
907 typedef struct arc_callback arc_callback_t;
909 struct arc_callback {
911 arc_done_func_t *acb_done;
913 zio_t *acb_zio_dummy;
914 arc_callback_t *acb_next;
917 typedef struct arc_write_callback arc_write_callback_t;
919 struct arc_write_callback {
921 arc_done_func_t *awcb_ready;
922 arc_done_func_t *awcb_children_ready;
923 arc_done_func_t *awcb_physdone;
924 arc_done_func_t *awcb_done;
929 * ARC buffers are separated into multiple structs as a memory saving measure:
930 * - Common fields struct, always defined, and embedded within it:
931 * - L2-only fields, always allocated but undefined when not in L2ARC
932 * - L1-only fields, only allocated when in L1ARC
934 * Buffer in L1 Buffer only in L2
935 * +------------------------+ +------------------------+
936 * | arc_buf_hdr_t | | arc_buf_hdr_t |
940 * +------------------------+ +------------------------+
941 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
942 * | (undefined if L1-only) | | |
943 * +------------------------+ +------------------------+
944 * | l1arc_buf_hdr_t |
949 * +------------------------+
951 * Because it's possible for the L2ARC to become extremely large, we can wind
952 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
953 * is minimized by only allocating the fields necessary for an L1-cached buffer
954 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
955 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
956 * words in pointers. arc_hdr_realloc() is used to switch a header between
957 * these two allocation states.
959 typedef struct l1arc_buf_hdr {
960 kmutex_t b_freeze_lock;
961 zio_cksum_t *b_freeze_cksum;
964 * used for debugging wtih kmem_flags - by allocating and freeing
965 * b_thawed when the buffer is thawed, we get a record of the stack
966 * trace that thawed it.
973 /* for waiting on writes to complete */
977 /* protected by arc state mutex */
978 arc_state_t *b_state;
979 multilist_node_t b_arc_node;
981 /* updated atomically */
982 clock_t b_arc_access;
984 /* self protecting */
987 arc_callback_t *b_acb;
991 typedef struct l2arc_dev l2arc_dev_t;
993 typedef struct l2arc_buf_hdr {
994 /* protected by arc_buf_hdr mutex */
995 l2arc_dev_t *b_dev; /* L2ARC device */
996 uint64_t b_daddr; /* disk address, offset byte */
998 list_node_t b_l2node;
1001 struct arc_buf_hdr {
1002 /* protected by hash lock */
1006 arc_buf_contents_t b_type;
1007 arc_buf_hdr_t *b_hash_next;
1008 arc_flags_t b_flags;
1011 * This field stores the size of the data buffer after
1012 * compression, and is set in the arc's zio completion handlers.
1013 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1015 * While the block pointers can store up to 32MB in their psize
1016 * field, we can only store up to 32MB minus 512B. This is due
1017 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1018 * a field of zeros represents 512B in the bp). We can't use a
1019 * bias of 1 since we need to reserve a psize of zero, here, to
1020 * represent holes and embedded blocks.
1022 * This isn't a problem in practice, since the maximum size of a
1023 * buffer is limited to 16MB, so we never need to store 32MB in
1024 * this field. Even in the upstream illumos code base, the
1025 * maximum size of a buffer is limited to 16MB.
1030 * This field stores the size of the data buffer before
1031 * compression, and cannot change once set. It is in units
1032 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1034 uint16_t b_lsize; /* immutable */
1035 uint64_t b_spa; /* immutable */
1037 /* L2ARC fields. Undefined when not in L2ARC. */
1038 l2arc_buf_hdr_t b_l2hdr;
1039 /* L1ARC fields. Undefined when in l2arc_only state */
1040 l1arc_buf_hdr_t b_l1hdr;
1043 #if defined(__FreeBSD__) && defined(_KERNEL)
1045 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1050 val = arc_meta_limit;
1051 err = sysctl_handle_64(oidp, &val, 0, req);
1052 if (err != 0 || req->newptr == NULL)
1055 if (val <= 0 || val > arc_c_max)
1058 arc_meta_limit = val;
1063 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1069 err = sysctl_handle_64(oidp, &val, 0, req);
1070 if (err != 0 || req->newptr == NULL)
1073 if (zfs_arc_max == 0) {
1074 /* Loader tunable so blindly set */
1079 if (val < arc_abs_min || val > kmem_size())
1081 if (val < arc_c_min)
1083 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1089 arc_p = (arc_c >> 1);
1091 if (zfs_arc_meta_limit == 0) {
1092 /* limit meta-data to 1/4 of the arc capacity */
1093 arc_meta_limit = arc_c_max / 4;
1096 /* if kmem_flags are set, lets try to use less memory */
1097 if (kmem_debugging())
1100 zfs_arc_max = arc_c;
1106 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1112 err = sysctl_handle_64(oidp, &val, 0, req);
1113 if (err != 0 || req->newptr == NULL)
1116 if (zfs_arc_min == 0) {
1117 /* Loader tunable so blindly set */
1122 if (val < arc_abs_min || val > arc_c_max)
1127 if (zfs_arc_meta_min == 0)
1128 arc_meta_min = arc_c_min / 2;
1130 if (arc_c < arc_c_min)
1133 zfs_arc_min = arc_c_min;
1139 #define GHOST_STATE(state) \
1140 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
1141 (state) == arc_l2c_only)
1143 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1144 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1145 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1146 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1147 #define HDR_COMPRESSION_ENABLED(hdr) \
1148 ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1150 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1151 #define HDR_L2_READING(hdr) \
1152 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1153 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1154 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1155 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1156 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1157 #define HDR_SHARED_DATA(hdr) ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1159 #define HDR_ISTYPE_METADATA(hdr) \
1160 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1161 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1163 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1164 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1166 /* For storing compression mode in b_flags */
1167 #define HDR_COMPRESS_OFFSET (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1169 #define HDR_GET_COMPRESS(hdr) ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1170 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1171 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1172 HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1174 #define ARC_BUF_LAST(buf) ((buf)->b_next == NULL)
1180 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1181 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1184 * Hash table routines
1187 #define HT_LOCK_PAD CACHE_LINE_SIZE
1192 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1196 #define BUF_LOCKS 256
1197 typedef struct buf_hash_table {
1199 arc_buf_hdr_t **ht_table;
1200 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1203 static buf_hash_table_t buf_hash_table;
1205 #define BUF_HASH_INDEX(spa, dva, birth) \
1206 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1207 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1208 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1209 #define HDR_LOCK(hdr) \
1210 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1212 uint64_t zfs_crc64_table[256];
1218 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1219 #define L2ARC_HEADROOM 2 /* num of writes */
1221 * If we discover during ARC scan any buffers to be compressed, we boost
1222 * our headroom for the next scanning cycle by this percentage multiple.
1224 #define L2ARC_HEADROOM_BOOST 200
1225 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1226 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1228 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1229 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1231 /* L2ARC Performance Tunables */
1232 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1233 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1234 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1235 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1236 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1237 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1238 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1239 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1240 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1242 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1243 &l2arc_write_max, 0, "max write size");
1244 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1245 &l2arc_write_boost, 0, "extra write during warmup");
1246 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1247 &l2arc_headroom, 0, "number of dev writes");
1248 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1249 &l2arc_feed_secs, 0, "interval seconds");
1250 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1251 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1253 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1254 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1255 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1256 &l2arc_feed_again, 0, "turbo warmup");
1257 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1258 &l2arc_norw, 0, "no reads during writes");
1260 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1261 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1262 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1263 &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1264 "size of anonymous state");
1265 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1266 &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1267 "size of anonymous state");
1269 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1270 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1271 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1272 &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1273 "size of metadata in mru state");
1274 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1275 &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1276 "size of data in mru state");
1278 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1279 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1280 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1281 &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1282 "size of metadata in mru ghost state");
1283 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1284 &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1285 "size of data in mru ghost state");
1287 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1288 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1289 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1290 &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1291 "size of metadata in mfu state");
1292 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1293 &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1294 "size of data in mfu state");
1296 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1297 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1298 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1299 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1300 "size of metadata in mfu ghost state");
1301 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1302 &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1303 "size of data in mfu ghost state");
1305 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1306 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1312 vdev_t *l2ad_vdev; /* vdev */
1313 spa_t *l2ad_spa; /* spa */
1314 uint64_t l2ad_hand; /* next write location */
1315 uint64_t l2ad_start; /* first addr on device */
1316 uint64_t l2ad_end; /* last addr on device */
1317 boolean_t l2ad_first; /* first sweep through */
1318 boolean_t l2ad_writing; /* currently writing */
1319 kmutex_t l2ad_mtx; /* lock for buffer list */
1320 list_t l2ad_buflist; /* buffer list */
1321 list_node_t l2ad_node; /* device list node */
1322 refcount_t l2ad_alloc; /* allocated bytes */
1325 static list_t L2ARC_dev_list; /* device list */
1326 static list_t *l2arc_dev_list; /* device list pointer */
1327 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1328 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1329 static list_t L2ARC_free_on_write; /* free after write buf list */
1330 static list_t *l2arc_free_on_write; /* free after write list ptr */
1331 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1332 static uint64_t l2arc_ndev; /* number of devices */
1334 typedef struct l2arc_read_callback {
1335 arc_buf_hdr_t *l2rcb_hdr; /* read buffer */
1336 blkptr_t l2rcb_bp; /* original blkptr */
1337 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1338 int l2rcb_flags; /* original flags */
1339 void *l2rcb_data; /* temporary buffer */
1340 } l2arc_read_callback_t;
1342 typedef struct l2arc_write_callback {
1343 l2arc_dev_t *l2wcb_dev; /* device info */
1344 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1345 } l2arc_write_callback_t;
1347 typedef struct l2arc_data_free {
1348 /* protected by l2arc_free_on_write_mtx */
1351 arc_buf_contents_t l2df_type;
1352 list_node_t l2df_list_node;
1353 } l2arc_data_free_t;
1355 static kmutex_t l2arc_feed_thr_lock;
1356 static kcondvar_t l2arc_feed_thr_cv;
1357 static uint8_t l2arc_thread_exit;
1359 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1360 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1361 static void arc_hdr_free_pdata(arc_buf_hdr_t *hdr);
1362 static void arc_hdr_alloc_pdata(arc_buf_hdr_t *);
1363 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1364 static boolean_t arc_is_overflowing();
1365 static void arc_buf_watch(arc_buf_t *);
1367 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1368 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1369 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1370 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1372 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1373 static void l2arc_read_done(zio_t *);
1376 l2arc_trim(const arc_buf_hdr_t *hdr)
1378 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1380 ASSERT(HDR_HAS_L2HDR(hdr));
1381 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1383 if (HDR_GET_PSIZE(hdr) != 0) {
1384 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1385 HDR_GET_PSIZE(hdr), 0);
1390 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1392 uint8_t *vdva = (uint8_t *)dva;
1393 uint64_t crc = -1ULL;
1396 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1398 for (i = 0; i < sizeof (dva_t); i++)
1399 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1401 crc ^= (spa>>8) ^ birth;
1406 #define HDR_EMPTY(hdr) \
1407 ((hdr)->b_dva.dva_word[0] == 0 && \
1408 (hdr)->b_dva.dva_word[1] == 0)
1410 #define HDR_EQUAL(spa, dva, birth, hdr) \
1411 ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1412 ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1413 ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1416 buf_discard_identity(arc_buf_hdr_t *hdr)
1418 hdr->b_dva.dva_word[0] = 0;
1419 hdr->b_dva.dva_word[1] = 0;
1423 static arc_buf_hdr_t *
1424 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1426 const dva_t *dva = BP_IDENTITY(bp);
1427 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1428 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1429 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1432 mutex_enter(hash_lock);
1433 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1434 hdr = hdr->b_hash_next) {
1435 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1440 mutex_exit(hash_lock);
1446 * Insert an entry into the hash table. If there is already an element
1447 * equal to elem in the hash table, then the already existing element
1448 * will be returned and the new element will not be inserted.
1449 * Otherwise returns NULL.
1450 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1452 static arc_buf_hdr_t *
1453 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1455 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1456 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1457 arc_buf_hdr_t *fhdr;
1460 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1461 ASSERT(hdr->b_birth != 0);
1462 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1464 if (lockp != NULL) {
1466 mutex_enter(hash_lock);
1468 ASSERT(MUTEX_HELD(hash_lock));
1471 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1472 fhdr = fhdr->b_hash_next, i++) {
1473 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1477 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1478 buf_hash_table.ht_table[idx] = hdr;
1479 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1481 /* collect some hash table performance data */
1483 ARCSTAT_BUMP(arcstat_hash_collisions);
1485 ARCSTAT_BUMP(arcstat_hash_chains);
1487 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1490 ARCSTAT_BUMP(arcstat_hash_elements);
1491 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1497 buf_hash_remove(arc_buf_hdr_t *hdr)
1499 arc_buf_hdr_t *fhdr, **hdrp;
1500 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1502 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1503 ASSERT(HDR_IN_HASH_TABLE(hdr));
1505 hdrp = &buf_hash_table.ht_table[idx];
1506 while ((fhdr = *hdrp) != hdr) {
1507 ASSERT3P(fhdr, !=, NULL);
1508 hdrp = &fhdr->b_hash_next;
1510 *hdrp = hdr->b_hash_next;
1511 hdr->b_hash_next = NULL;
1512 arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1514 /* collect some hash table performance data */
1515 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1517 if (buf_hash_table.ht_table[idx] &&
1518 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1519 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1523 * Global data structures and functions for the buf kmem cache.
1525 static kmem_cache_t *hdr_full_cache;
1526 static kmem_cache_t *hdr_l2only_cache;
1527 static kmem_cache_t *buf_cache;
1534 kmem_free(buf_hash_table.ht_table,
1535 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1536 for (i = 0; i < BUF_LOCKS; i++)
1537 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1538 kmem_cache_destroy(hdr_full_cache);
1539 kmem_cache_destroy(hdr_l2only_cache);
1540 kmem_cache_destroy(buf_cache);
1544 * Constructor callback - called when the cache is empty
1545 * and a new buf is requested.
1549 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1551 arc_buf_hdr_t *hdr = vbuf;
1553 bzero(hdr, HDR_FULL_SIZE);
1554 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1555 refcount_create(&hdr->b_l1hdr.b_refcnt);
1556 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1557 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1558 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1565 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1567 arc_buf_hdr_t *hdr = vbuf;
1569 bzero(hdr, HDR_L2ONLY_SIZE);
1570 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1577 buf_cons(void *vbuf, void *unused, int kmflag)
1579 arc_buf_t *buf = vbuf;
1581 bzero(buf, sizeof (arc_buf_t));
1582 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1583 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1589 * Destructor callback - called when a cached buf is
1590 * no longer required.
1594 hdr_full_dest(void *vbuf, void *unused)
1596 arc_buf_hdr_t *hdr = vbuf;
1598 ASSERT(HDR_EMPTY(hdr));
1599 cv_destroy(&hdr->b_l1hdr.b_cv);
1600 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1601 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1602 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1603 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1608 hdr_l2only_dest(void *vbuf, void *unused)
1610 arc_buf_hdr_t *hdr = vbuf;
1612 ASSERT(HDR_EMPTY(hdr));
1613 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1618 buf_dest(void *vbuf, void *unused)
1620 arc_buf_t *buf = vbuf;
1622 mutex_destroy(&buf->b_evict_lock);
1623 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1627 * Reclaim callback -- invoked when memory is low.
1631 hdr_recl(void *unused)
1633 dprintf("hdr_recl called\n");
1635 * umem calls the reclaim func when we destroy the buf cache,
1636 * which is after we do arc_fini().
1639 cv_signal(&arc_reclaim_thread_cv);
1646 uint64_t hsize = 1ULL << 12;
1650 * The hash table is big enough to fill all of physical memory
1651 * with an average block size of zfs_arc_average_blocksize (default 8K).
1652 * By default, the table will take up
1653 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1655 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1658 buf_hash_table.ht_mask = hsize - 1;
1659 buf_hash_table.ht_table =
1660 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1661 if (buf_hash_table.ht_table == NULL) {
1662 ASSERT(hsize > (1ULL << 8));
1667 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1668 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1669 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1670 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1672 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1673 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1675 for (i = 0; i < 256; i++)
1676 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1677 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1679 for (i = 0; i < BUF_LOCKS; i++) {
1680 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1681 NULL, MUTEX_DEFAULT, NULL);
1685 #define ARC_MINTIME (hz>>4) /* 62 ms */
1687 static inline boolean_t
1688 arc_buf_is_shared(arc_buf_t *buf)
1690 boolean_t shared = (buf->b_data != NULL &&
1691 buf->b_data == buf->b_hdr->b_l1hdr.b_pdata);
1692 IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1697 arc_cksum_free(arc_buf_hdr_t *hdr)
1699 ASSERT(HDR_HAS_L1HDR(hdr));
1700 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1701 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1702 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1703 hdr->b_l1hdr.b_freeze_cksum = NULL;
1705 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1709 arc_cksum_verify(arc_buf_t *buf)
1711 arc_buf_hdr_t *hdr = buf->b_hdr;
1714 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1717 ASSERT(HDR_HAS_L1HDR(hdr));
1719 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1720 if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1721 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1724 fletcher_2_native(buf->b_data, HDR_GET_LSIZE(hdr), NULL, &zc);
1725 if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1726 panic("buffer modified while frozen!");
1727 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1731 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1733 enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1734 boolean_t valid_cksum;
1736 ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1737 VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1740 * We rely on the blkptr's checksum to determine if the block
1741 * is valid or not. When compressed arc is enabled, the l2arc
1742 * writes the block to the l2arc just as it appears in the pool.
1743 * This allows us to use the blkptr's checksum to validate the
1744 * data that we just read off of the l2arc without having to store
1745 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1746 * arc is disabled, then the data written to the l2arc is always
1747 * uncompressed and won't match the block as it exists in the main
1748 * pool. When this is the case, we must first compress it if it is
1749 * compressed on the main pool before we can validate the checksum.
1751 if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1752 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1753 uint64_t lsize = HDR_GET_LSIZE(hdr);
1756 void *cbuf = zio_buf_alloc(HDR_GET_PSIZE(hdr));
1757 csize = zio_compress_data(compress, zio->io_data, cbuf, lsize);
1758 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1759 if (csize < HDR_GET_PSIZE(hdr)) {
1761 * Compressed blocks are always a multiple of the
1762 * smallest ashift in the pool. Ideally, we would
1763 * like to round up the csize to the next
1764 * spa_min_ashift but that value may have changed
1765 * since the block was last written. Instead,
1766 * we rely on the fact that the hdr's psize
1767 * was set to the psize of the block when it was
1768 * last written. We set the csize to that value
1769 * and zero out any part that should not contain
1772 bzero((char *)cbuf + csize, HDR_GET_PSIZE(hdr) - csize);
1773 csize = HDR_GET_PSIZE(hdr);
1775 zio_push_transform(zio, cbuf, csize, HDR_GET_PSIZE(hdr), NULL);
1779 * Block pointers always store the checksum for the logical data.
1780 * If the block pointer has the gang bit set, then the checksum
1781 * it represents is for the reconstituted data and not for an
1782 * individual gang member. The zio pipeline, however, must be able to
1783 * determine the checksum of each of the gang constituents so it
1784 * treats the checksum comparison differently than what we need
1785 * for l2arc blocks. This prevents us from using the
1786 * zio_checksum_error() interface directly. Instead we must call the
1787 * zio_checksum_error_impl() so that we can ensure the checksum is
1788 * generated using the correct checksum algorithm and accounts for the
1789 * logical I/O size and not just a gang fragment.
1791 valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1792 BP_GET_CHECKSUM(zio->io_bp), zio->io_data, zio->io_size,
1793 zio->io_offset, NULL) == 0);
1794 zio_pop_transforms(zio);
1795 return (valid_cksum);
1799 arc_cksum_compute(arc_buf_t *buf)
1801 arc_buf_hdr_t *hdr = buf->b_hdr;
1803 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1806 ASSERT(HDR_HAS_L1HDR(hdr));
1807 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1808 if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1809 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1812 hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1814 fletcher_2_native(buf->b_data, HDR_GET_LSIZE(hdr), NULL,
1815 hdr->b_l1hdr.b_freeze_cksum);
1816 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1824 typedef struct procctl {
1832 arc_buf_unwatch(arc_buf_t *buf)
1839 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1840 ctl.prwatch.pr_size = 0;
1841 ctl.prwatch.pr_wflags = 0;
1842 result = write(arc_procfd, &ctl, sizeof (ctl));
1843 ASSERT3U(result, ==, sizeof (ctl));
1850 arc_buf_watch(arc_buf_t *buf)
1857 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1858 ctl.prwatch.pr_size = HDR_GET_LSIZE(buf->b_hdr);
1859 ctl.prwatch.pr_wflags = WA_WRITE;
1860 result = write(arc_procfd, &ctl, sizeof (ctl));
1861 ASSERT3U(result, ==, sizeof (ctl));
1865 #endif /* illumos */
1867 static arc_buf_contents_t
1868 arc_buf_type(arc_buf_hdr_t *hdr)
1870 arc_buf_contents_t type;
1871 if (HDR_ISTYPE_METADATA(hdr)) {
1872 type = ARC_BUFC_METADATA;
1874 type = ARC_BUFC_DATA;
1876 VERIFY3U(hdr->b_type, ==, type);
1881 arc_bufc_to_flags(arc_buf_contents_t type)
1885 /* metadata field is 0 if buffer contains normal data */
1887 case ARC_BUFC_METADATA:
1888 return (ARC_FLAG_BUFC_METADATA);
1892 panic("undefined ARC buffer type!");
1893 return ((uint32_t)-1);
1897 arc_buf_thaw(arc_buf_t *buf)
1899 arc_buf_hdr_t *hdr = buf->b_hdr;
1901 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1902 if (hdr->b_l1hdr.b_state != arc_anon)
1903 panic("modifying non-anon buffer!");
1904 if (HDR_IO_IN_PROGRESS(hdr))
1905 panic("modifying buffer while i/o in progress!");
1906 arc_cksum_verify(buf);
1909 ASSERT(HDR_HAS_L1HDR(hdr));
1910 arc_cksum_free(hdr);
1912 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1914 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1915 if (hdr->b_l1hdr.b_thawed != NULL)
1916 kmem_free(hdr->b_l1hdr.b_thawed, 1);
1917 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1921 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1924 arc_buf_unwatch(buf);
1929 arc_buf_freeze(arc_buf_t *buf)
1931 arc_buf_hdr_t *hdr = buf->b_hdr;
1932 kmutex_t *hash_lock;
1934 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1937 hash_lock = HDR_LOCK(hdr);
1938 mutex_enter(hash_lock);
1940 ASSERT(HDR_HAS_L1HDR(hdr));
1941 ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1942 hdr->b_l1hdr.b_state == arc_anon);
1943 arc_cksum_compute(buf);
1944 mutex_exit(hash_lock);
1949 * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1950 * the following functions should be used to ensure that the flags are
1951 * updated in a thread-safe way. When manipulating the flags either
1952 * the hash_lock must be held or the hdr must be undiscoverable. This
1953 * ensures that we're not racing with any other threads when updating
1957 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1959 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1960 hdr->b_flags |= flags;
1964 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1966 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1967 hdr->b_flags &= ~flags;
1971 * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1972 * done in a special way since we have to clear and set bits
1973 * at the same time. Consumers that wish to set the compression bits
1974 * must use this function to ensure that the flags are updated in
1975 * thread-safe manner.
1978 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1980 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1983 * Holes and embedded blocks will always have a psize = 0 so
1984 * we ignore the compression of the blkptr and set the
1985 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1986 * Holes and embedded blocks remain anonymous so we don't
1987 * want to uncompress them. Mark them as uncompressed.
1989 if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1990 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1991 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1992 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1993 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1995 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1996 HDR_SET_COMPRESS(hdr, cmp);
1997 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1998 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2003 arc_decompress(arc_buf_t *buf)
2005 arc_buf_hdr_t *hdr = buf->b_hdr;
2006 dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2009 if (arc_buf_is_shared(buf)) {
2010 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2011 } else if (HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) {
2013 * The arc_buf_hdr_t is either not compressed or is
2014 * associated with an embedded block or a hole in which
2015 * case they remain anonymous.
2017 IMPLY(HDR_COMPRESSION_ENABLED(hdr), HDR_GET_PSIZE(hdr) == 0 ||
2018 HDR_GET_PSIZE(hdr) == HDR_GET_LSIZE(hdr));
2019 ASSERT(!HDR_SHARED_DATA(hdr));
2020 bcopy(hdr->b_l1hdr.b_pdata, buf->b_data, HDR_GET_LSIZE(hdr));
2022 ASSERT(!HDR_SHARED_DATA(hdr));
2023 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2024 error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2025 hdr->b_l1hdr.b_pdata, buf->b_data, HDR_GET_PSIZE(hdr),
2026 HDR_GET_LSIZE(hdr));
2028 zfs_dbgmsg("hdr %p, compress %d, psize %d, lsize %d",
2029 hdr, HDR_GET_COMPRESS(hdr), HDR_GET_PSIZE(hdr),
2030 HDR_GET_LSIZE(hdr));
2031 return (SET_ERROR(EIO));
2034 if (bswap != DMU_BSWAP_NUMFUNCS) {
2035 ASSERT(!HDR_SHARED_DATA(hdr));
2036 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2037 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2039 arc_cksum_compute(buf);
2044 * Return the size of the block, b_pdata, that is stored in the arc_buf_hdr_t.
2047 arc_hdr_size(arc_buf_hdr_t *hdr)
2051 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2052 HDR_GET_PSIZE(hdr) > 0) {
2053 size = HDR_GET_PSIZE(hdr);
2055 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2056 size = HDR_GET_LSIZE(hdr);
2062 * Increment the amount of evictable space in the arc_state_t's refcount.
2063 * We account for the space used by the hdr and the arc buf individually
2064 * so that we can add and remove them from the refcount individually.
2067 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2069 arc_buf_contents_t type = arc_buf_type(hdr);
2070 uint64_t lsize = HDR_GET_LSIZE(hdr);
2072 ASSERT(HDR_HAS_L1HDR(hdr));
2074 if (GHOST_STATE(state)) {
2075 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2076 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2077 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2078 (void) refcount_add_many(&state->arcs_esize[type], lsize, hdr);
2082 ASSERT(!GHOST_STATE(state));
2083 if (hdr->b_l1hdr.b_pdata != NULL) {
2084 (void) refcount_add_many(&state->arcs_esize[type],
2085 arc_hdr_size(hdr), hdr);
2087 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2088 buf = buf->b_next) {
2089 if (arc_buf_is_shared(buf)) {
2090 ASSERT(ARC_BUF_LAST(buf));
2093 (void) refcount_add_many(&state->arcs_esize[type], lsize, buf);
2098 * Decrement the amount of evictable space in the arc_state_t's refcount.
2099 * We account for the space used by the hdr and the arc buf individually
2100 * so that we can add and remove them from the refcount individually.
2103 arc_evitable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2105 arc_buf_contents_t type = arc_buf_type(hdr);
2106 uint64_t lsize = HDR_GET_LSIZE(hdr);
2108 ASSERT(HDR_HAS_L1HDR(hdr));
2110 if (GHOST_STATE(state)) {
2111 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2112 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2113 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2114 (void) refcount_remove_many(&state->arcs_esize[type],
2119 ASSERT(!GHOST_STATE(state));
2120 if (hdr->b_l1hdr.b_pdata != NULL) {
2121 (void) refcount_remove_many(&state->arcs_esize[type],
2122 arc_hdr_size(hdr), hdr);
2124 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2125 buf = buf->b_next) {
2126 if (arc_buf_is_shared(buf)) {
2127 ASSERT(ARC_BUF_LAST(buf));
2130 (void) refcount_remove_many(&state->arcs_esize[type],
2136 * Add a reference to this hdr indicating that someone is actively
2137 * referencing that memory. When the refcount transitions from 0 to 1,
2138 * we remove it from the respective arc_state_t list to indicate that
2139 * it is not evictable.
2142 add_reference(arc_buf_hdr_t *hdr, void *tag)
2144 ASSERT(HDR_HAS_L1HDR(hdr));
2145 if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2146 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2147 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2148 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2151 arc_state_t *state = hdr->b_l1hdr.b_state;
2153 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2154 (state != arc_anon)) {
2155 /* We don't use the L2-only state list. */
2156 if (state != arc_l2c_only) {
2157 multilist_remove(&state->arcs_list[arc_buf_type(hdr)],
2159 arc_evitable_space_decrement(hdr, state);
2161 /* remove the prefetch flag if we get a reference */
2162 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2167 * Remove a reference from this hdr. When the reference transitions from
2168 * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2169 * list making it eligible for eviction.
2172 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2175 arc_state_t *state = hdr->b_l1hdr.b_state;
2177 ASSERT(HDR_HAS_L1HDR(hdr));
2178 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2179 ASSERT(!GHOST_STATE(state));
2182 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2183 * check to prevent usage of the arc_l2c_only list.
2185 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2186 (state != arc_anon)) {
2187 multilist_insert(&state->arcs_list[arc_buf_type(hdr)], hdr);
2188 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2189 arc_evictable_space_increment(hdr, state);
2195 * Move the supplied buffer to the indicated state. The hash lock
2196 * for the buffer must be held by the caller.
2199 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2200 kmutex_t *hash_lock)
2202 arc_state_t *old_state;
2205 boolean_t update_old, update_new;
2206 arc_buf_contents_t buftype = arc_buf_type(hdr);
2209 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2210 * in arc_read() when bringing a buffer out of the L2ARC. However, the
2211 * L1 hdr doesn't always exist when we change state to arc_anon before
2212 * destroying a header, in which case reallocating to add the L1 hdr is
2215 if (HDR_HAS_L1HDR(hdr)) {
2216 old_state = hdr->b_l1hdr.b_state;
2217 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2218 bufcnt = hdr->b_l1hdr.b_bufcnt;
2219 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pdata != NULL);
2221 old_state = arc_l2c_only;
2224 update_old = B_FALSE;
2226 update_new = update_old;
2228 ASSERT(MUTEX_HELD(hash_lock));
2229 ASSERT3P(new_state, !=, old_state);
2230 ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2231 ASSERT(old_state != arc_anon || bufcnt <= 1);
2234 * If this buffer is evictable, transfer it from the
2235 * old state list to the new state list.
2238 if (old_state != arc_anon && old_state != arc_l2c_only) {
2239 ASSERT(HDR_HAS_L1HDR(hdr));
2240 multilist_remove(&old_state->arcs_list[buftype], hdr);
2242 if (GHOST_STATE(old_state)) {
2244 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2245 update_old = B_TRUE;
2247 arc_evitable_space_decrement(hdr, old_state);
2249 if (new_state != arc_anon && new_state != arc_l2c_only) {
2252 * An L1 header always exists here, since if we're
2253 * moving to some L1-cached state (i.e. not l2c_only or
2254 * anonymous), we realloc the header to add an L1hdr
2257 ASSERT(HDR_HAS_L1HDR(hdr));
2258 multilist_insert(&new_state->arcs_list[buftype], hdr);
2260 if (GHOST_STATE(new_state)) {
2262 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2263 update_new = B_TRUE;
2265 arc_evictable_space_increment(hdr, new_state);
2269 ASSERT(!HDR_EMPTY(hdr));
2270 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2271 buf_hash_remove(hdr);
2273 /* adjust state sizes (ignore arc_l2c_only) */
2275 if (update_new && new_state != arc_l2c_only) {
2276 ASSERT(HDR_HAS_L1HDR(hdr));
2277 if (GHOST_STATE(new_state)) {
2281 * When moving a header to a ghost state, we first
2282 * remove all arc buffers. Thus, we'll have a
2283 * bufcnt of zero, and no arc buffer to use for
2284 * the reference. As a result, we use the arc
2285 * header pointer for the reference.
2287 (void) refcount_add_many(&new_state->arcs_size,
2288 HDR_GET_LSIZE(hdr), hdr);
2289 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2291 uint32_t buffers = 0;
2294 * Each individual buffer holds a unique reference,
2295 * thus we must remove each of these references one
2298 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2299 buf = buf->b_next) {
2300 ASSERT3U(bufcnt, !=, 0);
2304 * When the arc_buf_t is sharing the data
2305 * block with the hdr, the owner of the
2306 * reference belongs to the hdr. Only
2307 * add to the refcount if the arc_buf_t is
2310 if (arc_buf_is_shared(buf)) {
2311 ASSERT(ARC_BUF_LAST(buf));
2315 (void) refcount_add_many(&new_state->arcs_size,
2316 HDR_GET_LSIZE(hdr), buf);
2318 ASSERT3U(bufcnt, ==, buffers);
2320 if (hdr->b_l1hdr.b_pdata != NULL) {
2321 (void) refcount_add_many(&new_state->arcs_size,
2322 arc_hdr_size(hdr), hdr);
2324 ASSERT(GHOST_STATE(old_state));
2329 if (update_old && old_state != arc_l2c_only) {
2330 ASSERT(HDR_HAS_L1HDR(hdr));
2331 if (GHOST_STATE(old_state)) {
2335 * When moving a header off of a ghost state,
2336 * the header will not contain any arc buffers.
2337 * We use the arc header pointer for the reference
2338 * which is exactly what we did when we put the
2339 * header on the ghost state.
2342 (void) refcount_remove_many(&old_state->arcs_size,
2343 HDR_GET_LSIZE(hdr), hdr);
2344 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2346 uint32_t buffers = 0;
2349 * Each individual buffer holds a unique reference,
2350 * thus we must remove each of these references one
2353 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2354 buf = buf->b_next) {
2355 ASSERT3P(bufcnt, !=, 0);
2359 * When the arc_buf_t is sharing the data
2360 * block with the hdr, the owner of the
2361 * reference belongs to the hdr. Only
2362 * add to the refcount if the arc_buf_t is
2365 if (arc_buf_is_shared(buf)) {
2366 ASSERT(ARC_BUF_LAST(buf));
2370 (void) refcount_remove_many(
2371 &old_state->arcs_size, HDR_GET_LSIZE(hdr),
2374 ASSERT3U(bufcnt, ==, buffers);
2375 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2376 (void) refcount_remove_many(
2377 &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2381 if (HDR_HAS_L1HDR(hdr))
2382 hdr->b_l1hdr.b_state = new_state;
2385 * L2 headers should never be on the L2 state list since they don't
2386 * have L1 headers allocated.
2388 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2389 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2393 arc_space_consume(uint64_t space, arc_space_type_t type)
2395 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2398 case ARC_SPACE_DATA:
2399 ARCSTAT_INCR(arcstat_data_size, space);
2401 case ARC_SPACE_META:
2402 ARCSTAT_INCR(arcstat_metadata_size, space);
2404 case ARC_SPACE_OTHER:
2405 ARCSTAT_INCR(arcstat_other_size, space);
2407 case ARC_SPACE_HDRS:
2408 ARCSTAT_INCR(arcstat_hdr_size, space);
2410 case ARC_SPACE_L2HDRS:
2411 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
2415 if (type != ARC_SPACE_DATA)
2416 ARCSTAT_INCR(arcstat_meta_used, space);
2418 atomic_add_64(&arc_size, space);
2422 arc_space_return(uint64_t space, arc_space_type_t type)
2424 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2427 case ARC_SPACE_DATA:
2428 ARCSTAT_INCR(arcstat_data_size, -space);
2430 case ARC_SPACE_META:
2431 ARCSTAT_INCR(arcstat_metadata_size, -space);
2433 case ARC_SPACE_OTHER:
2434 ARCSTAT_INCR(arcstat_other_size, -space);
2436 case ARC_SPACE_HDRS:
2437 ARCSTAT_INCR(arcstat_hdr_size, -space);
2439 case ARC_SPACE_L2HDRS:
2440 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2444 if (type != ARC_SPACE_DATA) {
2445 ASSERT(arc_meta_used >= space);
2446 if (arc_meta_max < arc_meta_used)
2447 arc_meta_max = arc_meta_used;
2448 ARCSTAT_INCR(arcstat_meta_used, -space);
2451 ASSERT(arc_size >= space);
2452 atomic_add_64(&arc_size, -space);
2456 * Allocate an initial buffer for this hdr, subsequent buffers will
2457 * use arc_buf_clone().
2460 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag)
2464 ASSERT(HDR_HAS_L1HDR(hdr));
2465 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2466 VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2467 hdr->b_type == ARC_BUFC_METADATA);
2469 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2470 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2471 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2473 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2478 add_reference(hdr, tag);
2481 * We're about to change the hdr's b_flags. We must either
2482 * hold the hash_lock or be undiscoverable.
2484 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2487 * If the hdr's data can be shared (no byteswapping, hdr is
2488 * uncompressed, hdr's data is not currently being written to the
2489 * L2ARC write) then we share the data buffer and set the appropriate
2490 * bit in the hdr's b_flags to indicate the hdr is sharing it's
2491 * b_pdata with the arc_buf_t. Otherwise, we allocate a new buffer to
2492 * store the buf's data.
2494 if (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2495 HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF && !HDR_L2_WRITING(hdr)) {
2496 buf->b_data = hdr->b_l1hdr.b_pdata;
2497 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2499 buf->b_data = arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2500 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2501 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2503 VERIFY3P(buf->b_data, !=, NULL);
2505 hdr->b_l1hdr.b_buf = buf;
2506 hdr->b_l1hdr.b_bufcnt += 1;
2512 * Used when allocating additional buffers.
2515 arc_buf_clone(arc_buf_t *from)
2518 arc_buf_hdr_t *hdr = from->b_hdr;
2519 uint64_t size = HDR_GET_LSIZE(hdr);
2521 ASSERT(HDR_HAS_L1HDR(hdr));
2522 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2524 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2527 buf->b_next = hdr->b_l1hdr.b_buf;
2528 hdr->b_l1hdr.b_buf = buf;
2529 buf->b_data = arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2530 bcopy(from->b_data, buf->b_data, size);
2531 hdr->b_l1hdr.b_bufcnt += 1;
2533 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2537 static char *arc_onloan_tag = "onloan";
2540 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2541 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2542 * buffers must be returned to the arc before they can be used by the DMU or
2546 arc_loan_buf(spa_t *spa, int size)
2550 buf = arc_alloc_buf(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2552 atomic_add_64(&arc_loaned_bytes, size);
2557 * Return a loaned arc buffer to the arc.
2560 arc_return_buf(arc_buf_t *buf, void *tag)
2562 arc_buf_hdr_t *hdr = buf->b_hdr;
2564 ASSERT3P(buf->b_data, !=, NULL);
2565 ASSERT(HDR_HAS_L1HDR(hdr));
2566 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2567 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2569 atomic_add_64(&arc_loaned_bytes, -HDR_GET_LSIZE(hdr));
2572 /* Detach an arc_buf from a dbuf (tag) */
2574 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2576 arc_buf_hdr_t *hdr = buf->b_hdr;
2578 ASSERT3P(buf->b_data, !=, NULL);
2579 ASSERT(HDR_HAS_L1HDR(hdr));
2580 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2581 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2583 atomic_add_64(&arc_loaned_bytes, HDR_GET_LSIZE(hdr));
2587 l2arc_free_data_on_write(void *data, size_t size, arc_buf_contents_t type)
2589 l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2591 df->l2df_data = data;
2592 df->l2df_size = size;
2593 df->l2df_type = type;
2594 mutex_enter(&l2arc_free_on_write_mtx);
2595 list_insert_head(l2arc_free_on_write, df);
2596 mutex_exit(&l2arc_free_on_write_mtx);
2600 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2602 arc_state_t *state = hdr->b_l1hdr.b_state;
2603 arc_buf_contents_t type = arc_buf_type(hdr);
2604 uint64_t size = arc_hdr_size(hdr);
2606 /* protected by hash lock, if in the hash table */
2607 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2608 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2609 ASSERT(state != arc_anon && state != arc_l2c_only);
2611 (void) refcount_remove_many(&state->arcs_esize[type],
2614 (void) refcount_remove_many(&state->arcs_size, size, hdr);
2616 l2arc_free_data_on_write(hdr->b_l1hdr.b_pdata, size, type);
2620 * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2621 * data buffer, we transfer the refcount ownership to the hdr and update
2622 * the appropriate kstats.
2625 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2627 arc_state_t *state = hdr->b_l1hdr.b_state;
2629 ASSERT(!HDR_SHARED_DATA(hdr));
2630 ASSERT(!arc_buf_is_shared(buf));
2631 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2632 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2635 * Start sharing the data buffer. We transfer the
2636 * refcount ownership to the hdr since it always owns
2637 * the refcount whenever an arc_buf_t is shared.
2639 refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2640 hdr->b_l1hdr.b_pdata = buf->b_data;
2641 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2644 * Since we've transferred ownership to the hdr we need
2645 * to increment its compressed and uncompressed kstats and
2646 * decrement the overhead size.
2648 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2649 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2650 ARCSTAT_INCR(arcstat_overhead_size, -HDR_GET_LSIZE(hdr));
2654 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2656 arc_state_t *state = hdr->b_l1hdr.b_state;
2658 ASSERT(HDR_SHARED_DATA(hdr));
2659 ASSERT(arc_buf_is_shared(buf));
2660 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2661 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2664 * We are no longer sharing this buffer so we need
2665 * to transfer its ownership to the rightful owner.
2667 refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2668 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2669 hdr->b_l1hdr.b_pdata = NULL;
2672 * Since the buffer is no longer shared between
2673 * the arc buf and the hdr, count it as overhead.
2675 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2676 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2677 ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2681 * Free up buf->b_data and if 'remove' is set, then pull the
2682 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2685 arc_buf_destroy_impl(arc_buf_t *buf, boolean_t remove)
2688 arc_buf_hdr_t *hdr = buf->b_hdr;
2689 uint64_t size = HDR_GET_LSIZE(hdr);
2690 boolean_t destroyed_buf_is_shared = arc_buf_is_shared(buf);
2693 * Free up the data associated with the buf but only
2694 * if we're not sharing this with the hdr. If we are sharing
2695 * it with the hdr, then hdr will have performed the allocation
2696 * so allow it to do the free.
2698 if (buf->b_data != NULL) {
2700 * We're about to change the hdr's b_flags. We must either
2701 * hold the hash_lock or be undiscoverable.
2703 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2705 arc_cksum_verify(buf);
2707 arc_buf_unwatch(buf);
2710 if (destroyed_buf_is_shared) {
2711 ASSERT(ARC_BUF_LAST(buf));
2712 ASSERT(HDR_SHARED_DATA(hdr));
2713 arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2715 arc_free_data_buf(hdr, buf->b_data, size, buf);
2716 ARCSTAT_INCR(arcstat_overhead_size, -size);
2720 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2721 hdr->b_l1hdr.b_bufcnt -= 1;
2724 /* only remove the buf if requested */
2728 /* remove the buf from the hdr list */
2729 arc_buf_t *lastbuf = NULL;
2730 bufp = &hdr->b_l1hdr.b_buf;
2731 while (*bufp != NULL) {
2733 *bufp = buf->b_next;
2736 * If we've removed a buffer in the middle of
2737 * the list then update the lastbuf and update
2740 if (*bufp != NULL) {
2742 bufp = &(*bufp)->b_next;
2746 ASSERT3P(lastbuf, !=, buf);
2749 * If the current arc_buf_t is sharing its data
2750 * buffer with the hdr, then reassign the hdr's
2751 * b_pdata to share it with the new buffer at the end
2752 * of the list. The shared buffer is always the last one
2753 * on the hdr's buffer list.
2755 if (destroyed_buf_is_shared && lastbuf != NULL) {
2756 ASSERT(ARC_BUF_LAST(buf));
2757 ASSERT(ARC_BUF_LAST(lastbuf));
2758 VERIFY(!arc_buf_is_shared(lastbuf));
2760 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2761 arc_hdr_free_pdata(hdr);
2764 * We must setup a new shared block between the
2765 * last buffer and the hdr. The data would have
2766 * been allocated by the arc buf so we need to transfer
2767 * ownership to the hdr since it's now being shared.
2769 arc_share_buf(hdr, lastbuf);
2770 } else if (HDR_SHARED_DATA(hdr)) {
2771 ASSERT(arc_buf_is_shared(lastbuf));
2774 if (hdr->b_l1hdr.b_bufcnt == 0)
2775 arc_cksum_free(hdr);
2777 /* clean up the buf */
2779 kmem_cache_free(buf_cache, buf);
2783 arc_hdr_alloc_pdata(arc_buf_hdr_t *hdr)
2785 ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2786 ASSERT(HDR_HAS_L1HDR(hdr));
2787 ASSERT(!HDR_SHARED_DATA(hdr));
2789 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2790 hdr->b_l1hdr.b_pdata = arc_get_data_buf(hdr, arc_hdr_size(hdr), hdr);
2791 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2792 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2794 ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2795 ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2799 arc_hdr_free_pdata(arc_buf_hdr_t *hdr)
2801 ASSERT(HDR_HAS_L1HDR(hdr));
2802 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
2805 * If the hdr is currently being written to the l2arc then
2806 * we defer freeing the data by adding it to the l2arc_free_on_write
2807 * list. The l2arc will free the data once it's finished
2808 * writing it to the l2arc device.
2810 if (HDR_L2_WRITING(hdr)) {
2811 arc_hdr_free_on_write(hdr);
2812 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2814 arc_free_data_buf(hdr, hdr->b_l1hdr.b_pdata,
2815 arc_hdr_size(hdr), hdr);
2817 hdr->b_l1hdr.b_pdata = NULL;
2818 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2820 ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2821 ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2824 static arc_buf_hdr_t *
2825 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
2826 enum zio_compress compress, arc_buf_contents_t type)
2830 ASSERT3U(lsize, >, 0);
2831 VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2833 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2834 ASSERT(HDR_EMPTY(hdr));
2835 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2836 ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2837 HDR_SET_PSIZE(hdr, psize);
2838 HDR_SET_LSIZE(hdr, lsize);
2842 arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
2843 arc_hdr_set_compress(hdr, compress);
2845 hdr->b_l1hdr.b_state = arc_anon;
2846 hdr->b_l1hdr.b_arc_access = 0;
2847 hdr->b_l1hdr.b_bufcnt = 0;
2848 hdr->b_l1hdr.b_buf = NULL;
2851 * Allocate the hdr's buffer. This will contain either
2852 * the compressed or uncompressed data depending on the block
2853 * it references and compressed arc enablement.
2855 arc_hdr_alloc_pdata(hdr);
2856 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2862 * Transition between the two allocation states for the arc_buf_hdr struct.
2863 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2864 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2865 * version is used when a cache buffer is only in the L2ARC in order to reduce
2868 static arc_buf_hdr_t *
2869 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2871 ASSERT(HDR_HAS_L2HDR(hdr));
2873 arc_buf_hdr_t *nhdr;
2874 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2876 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2877 (old == hdr_l2only_cache && new == hdr_full_cache));
2879 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2881 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2882 buf_hash_remove(hdr);
2884 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2886 if (new == hdr_full_cache) {
2887 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2889 * arc_access and arc_change_state need to be aware that a
2890 * header has just come out of L2ARC, so we set its state to
2891 * l2c_only even though it's about to change.
2893 nhdr->b_l1hdr.b_state = arc_l2c_only;
2895 /* Verify previous threads set to NULL before freeing */
2896 ASSERT3P(nhdr->b_l1hdr.b_pdata, ==, NULL);
2898 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2899 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2900 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2903 * If we've reached here, We must have been called from
2904 * arc_evict_hdr(), as such we should have already been
2905 * removed from any ghost list we were previously on
2906 * (which protects us from racing with arc_evict_state),
2907 * thus no locking is needed during this check.
2909 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2912 * A buffer must not be moved into the arc_l2c_only
2913 * state if it's not finished being written out to the
2914 * l2arc device. Otherwise, the b_l1hdr.b_pdata field
2915 * might try to be accessed, even though it was removed.
2917 VERIFY(!HDR_L2_WRITING(hdr));
2918 VERIFY3P(hdr->b_l1hdr.b_pdata, ==, NULL);
2921 if (hdr->b_l1hdr.b_thawed != NULL) {
2922 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2923 hdr->b_l1hdr.b_thawed = NULL;
2927 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2930 * The header has been reallocated so we need to re-insert it into any
2933 (void) buf_hash_insert(nhdr, NULL);
2935 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
2937 mutex_enter(&dev->l2ad_mtx);
2940 * We must place the realloc'ed header back into the list at
2941 * the same spot. Otherwise, if it's placed earlier in the list,
2942 * l2arc_write_buffers() could find it during the function's
2943 * write phase, and try to write it out to the l2arc.
2945 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
2946 list_remove(&dev->l2ad_buflist, hdr);
2948 mutex_exit(&dev->l2ad_mtx);
2951 * Since we're using the pointer address as the tag when
2952 * incrementing and decrementing the l2ad_alloc refcount, we
2953 * must remove the old pointer (that we're about to destroy) and
2954 * add the new pointer to the refcount. Otherwise we'd remove
2955 * the wrong pointer address when calling arc_hdr_destroy() later.
2958 (void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
2959 (void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
2961 buf_discard_identity(hdr);
2962 kmem_cache_free(old, hdr);
2968 * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
2969 * The buf is returned thawed since we expect the consumer to modify it.
2972 arc_alloc_buf(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2974 arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
2975 ZIO_COMPRESS_OFF, type);
2976 ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
2977 arc_buf_t *buf = arc_buf_alloc_impl(hdr, tag);
2983 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2985 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2986 l2arc_dev_t *dev = l2hdr->b_dev;
2987 uint64_t asize = arc_hdr_size(hdr);
2989 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2990 ASSERT(HDR_HAS_L2HDR(hdr));
2992 list_remove(&dev->l2ad_buflist, hdr);
2994 ARCSTAT_INCR(arcstat_l2_asize, -asize);
2995 ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
2997 vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
2999 (void) refcount_remove_many(&dev->l2ad_alloc, asize, hdr);
3000 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3004 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3006 if (HDR_HAS_L1HDR(hdr)) {
3007 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3008 hdr->b_l1hdr.b_bufcnt > 0);
3009 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3010 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3012 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3013 ASSERT(!HDR_IN_HASH_TABLE(hdr));
3015 if (!HDR_EMPTY(hdr))
3016 buf_discard_identity(hdr);
3018 if (HDR_HAS_L2HDR(hdr)) {
3019 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3020 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3023 mutex_enter(&dev->l2ad_mtx);
3026 * Even though we checked this conditional above, we
3027 * need to check this again now that we have the
3028 * l2ad_mtx. This is because we could be racing with
3029 * another thread calling l2arc_evict() which might have
3030 * destroyed this header's L2 portion as we were waiting
3031 * to acquire the l2ad_mtx. If that happens, we don't
3032 * want to re-destroy the header's L2 portion.
3034 if (HDR_HAS_L2HDR(hdr)) {
3036 arc_hdr_l2hdr_destroy(hdr);
3040 mutex_exit(&dev->l2ad_mtx);
3043 if (HDR_HAS_L1HDR(hdr)) {
3044 arc_cksum_free(hdr);
3046 while (hdr->b_l1hdr.b_buf != NULL)
3047 arc_buf_destroy_impl(hdr->b_l1hdr.b_buf, B_TRUE);
3050 if (hdr->b_l1hdr.b_thawed != NULL) {
3051 kmem_free(hdr->b_l1hdr.b_thawed, 1);
3052 hdr->b_l1hdr.b_thawed = NULL;
3056 if (hdr->b_l1hdr.b_pdata != NULL) {
3057 arc_hdr_free_pdata(hdr);
3061 ASSERT3P(hdr->b_hash_next, ==, NULL);
3062 if (HDR_HAS_L1HDR(hdr)) {
3063 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3064 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3065 kmem_cache_free(hdr_full_cache, hdr);
3067 kmem_cache_free(hdr_l2only_cache, hdr);
3072 arc_buf_destroy(arc_buf_t *buf, void* tag)
3074 arc_buf_hdr_t *hdr = buf->b_hdr;
3075 kmutex_t *hash_lock = HDR_LOCK(hdr);
3077 if (hdr->b_l1hdr.b_state == arc_anon) {
3078 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3079 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3080 VERIFY0(remove_reference(hdr, NULL, tag));
3081 arc_hdr_destroy(hdr);
3085 mutex_enter(hash_lock);
3086 ASSERT3P(hdr, ==, buf->b_hdr);
3087 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3088 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3089 ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3090 ASSERT3P(buf->b_data, !=, NULL);
3092 (void) remove_reference(hdr, hash_lock, tag);
3093 arc_buf_destroy_impl(buf, B_TRUE);
3094 mutex_exit(hash_lock);
3098 arc_buf_size(arc_buf_t *buf)
3100 return (HDR_GET_LSIZE(buf->b_hdr));
3104 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3105 * state of the header is dependent on it's state prior to entering this
3106 * function. The following transitions are possible:
3108 * - arc_mru -> arc_mru_ghost
3109 * - arc_mfu -> arc_mfu_ghost
3110 * - arc_mru_ghost -> arc_l2c_only
3111 * - arc_mru_ghost -> deleted
3112 * - arc_mfu_ghost -> arc_l2c_only
3113 * - arc_mfu_ghost -> deleted
3116 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3118 arc_state_t *evicted_state, *state;
3119 int64_t bytes_evicted = 0;
3121 ASSERT(MUTEX_HELD(hash_lock));
3122 ASSERT(HDR_HAS_L1HDR(hdr));
3124 state = hdr->b_l1hdr.b_state;
3125 if (GHOST_STATE(state)) {
3126 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3127 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3130 * l2arc_write_buffers() relies on a header's L1 portion
3131 * (i.e. its b_pdata field) during its write phase.
3132 * Thus, we cannot push a header onto the arc_l2c_only
3133 * state (removing it's L1 piece) until the header is
3134 * done being written to the l2arc.
3136 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3137 ARCSTAT_BUMP(arcstat_evict_l2_skip);
3138 return (bytes_evicted);
3141 ARCSTAT_BUMP(arcstat_deleted);
3142 bytes_evicted += HDR_GET_LSIZE(hdr);
3144 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3146 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
3147 if (HDR_HAS_L2HDR(hdr)) {
3148 ASSERT(hdr->b_l1hdr.b_pdata == NULL);
3150 * This buffer is cached on the 2nd Level ARC;
3151 * don't destroy the header.
3153 arc_change_state(arc_l2c_only, hdr, hash_lock);
3155 * dropping from L1+L2 cached to L2-only,
3156 * realloc to remove the L1 header.
3158 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3161 ASSERT(hdr->b_l1hdr.b_pdata == NULL);
3162 arc_change_state(arc_anon, hdr, hash_lock);
3163 arc_hdr_destroy(hdr);
3165 return (bytes_evicted);
3168 ASSERT(state == arc_mru || state == arc_mfu);
3169 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3171 /* prefetch buffers have a minimum lifespan */
3172 if (HDR_IO_IN_PROGRESS(hdr) ||
3173 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3174 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3175 arc_min_prefetch_lifespan)) {
3176 ARCSTAT_BUMP(arcstat_evict_skip);
3177 return (bytes_evicted);
3180 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3181 while (hdr->b_l1hdr.b_buf) {
3182 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3183 if (!mutex_tryenter(&buf->b_evict_lock)) {
3184 ARCSTAT_BUMP(arcstat_mutex_miss);
3187 if (buf->b_data != NULL)
3188 bytes_evicted += HDR_GET_LSIZE(hdr);
3189 mutex_exit(&buf->b_evict_lock);
3190 arc_buf_destroy_impl(buf, B_TRUE);
3193 if (HDR_HAS_L2HDR(hdr)) {
3194 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3196 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3197 ARCSTAT_INCR(arcstat_evict_l2_eligible,
3198 HDR_GET_LSIZE(hdr));
3200 ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3201 HDR_GET_LSIZE(hdr));
3205 if (hdr->b_l1hdr.b_bufcnt == 0) {
3206 arc_cksum_free(hdr);
3208 bytes_evicted += arc_hdr_size(hdr);
3211 * If this hdr is being evicted and has a compressed
3212 * buffer then we discard it here before we change states.
3213 * This ensures that the accounting is updated correctly
3214 * in arc_free_data_buf().
3216 arc_hdr_free_pdata(hdr);
3218 arc_change_state(evicted_state, hdr, hash_lock);
3219 ASSERT(HDR_IN_HASH_TABLE(hdr));
3220 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3221 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3224 return (bytes_evicted);
3228 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3229 uint64_t spa, int64_t bytes)
3231 multilist_sublist_t *mls;
3232 uint64_t bytes_evicted = 0;
3234 kmutex_t *hash_lock;
3235 int evict_count = 0;
3237 ASSERT3P(marker, !=, NULL);
3238 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3240 mls = multilist_sublist_lock(ml, idx);
3242 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3243 hdr = multilist_sublist_prev(mls, marker)) {
3244 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3245 (evict_count >= zfs_arc_evict_batch_limit))
3249 * To keep our iteration location, move the marker
3250 * forward. Since we're not holding hdr's hash lock, we
3251 * must be very careful and not remove 'hdr' from the
3252 * sublist. Otherwise, other consumers might mistake the
3253 * 'hdr' as not being on a sublist when they call the
3254 * multilist_link_active() function (they all rely on
3255 * the hash lock protecting concurrent insertions and
3256 * removals). multilist_sublist_move_forward() was
3257 * specifically implemented to ensure this is the case
3258 * (only 'marker' will be removed and re-inserted).
3260 multilist_sublist_move_forward(mls, marker);
3263 * The only case where the b_spa field should ever be
3264 * zero, is the marker headers inserted by
3265 * arc_evict_state(). It's possible for multiple threads
3266 * to be calling arc_evict_state() concurrently (e.g.
3267 * dsl_pool_close() and zio_inject_fault()), so we must
3268 * skip any markers we see from these other threads.
3270 if (hdr->b_spa == 0)
3273 /* we're only interested in evicting buffers of a certain spa */
3274 if (spa != 0 && hdr->b_spa != spa) {
3275 ARCSTAT_BUMP(arcstat_evict_skip);
3279 hash_lock = HDR_LOCK(hdr);
3282 * We aren't calling this function from any code path
3283 * that would already be holding a hash lock, so we're
3284 * asserting on this assumption to be defensive in case
3285 * this ever changes. Without this check, it would be
3286 * possible to incorrectly increment arcstat_mutex_miss
3287 * below (e.g. if the code changed such that we called
3288 * this function with a hash lock held).
3290 ASSERT(!MUTEX_HELD(hash_lock));
3292 if (mutex_tryenter(hash_lock)) {
3293 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3294 mutex_exit(hash_lock);
3296 bytes_evicted += evicted;
3299 * If evicted is zero, arc_evict_hdr() must have
3300 * decided to skip this header, don't increment
3301 * evict_count in this case.
3307 * If arc_size isn't overflowing, signal any
3308 * threads that might happen to be waiting.
3310 * For each header evicted, we wake up a single
3311 * thread. If we used cv_broadcast, we could
3312 * wake up "too many" threads causing arc_size
3313 * to significantly overflow arc_c; since
3314 * arc_get_data_buf() doesn't check for overflow
3315 * when it's woken up (it doesn't because it's
3316 * possible for the ARC to be overflowing while
3317 * full of un-evictable buffers, and the
3318 * function should proceed in this case).
3320 * If threads are left sleeping, due to not
3321 * using cv_broadcast, they will be woken up
3322 * just before arc_reclaim_thread() sleeps.
3324 mutex_enter(&arc_reclaim_lock);
3325 if (!arc_is_overflowing())
3326 cv_signal(&arc_reclaim_waiters_cv);
3327 mutex_exit(&arc_reclaim_lock);
3329 ARCSTAT_BUMP(arcstat_mutex_miss);
3333 multilist_sublist_unlock(mls);
3335 return (bytes_evicted);
3339 * Evict buffers from the given arc state, until we've removed the
3340 * specified number of bytes. Move the removed buffers to the
3341 * appropriate evict state.
3343 * This function makes a "best effort". It skips over any buffers
3344 * it can't get a hash_lock on, and so, may not catch all candidates.
3345 * It may also return without evicting as much space as requested.
3347 * If bytes is specified using the special value ARC_EVICT_ALL, this
3348 * will evict all available (i.e. unlocked and evictable) buffers from
3349 * the given arc state; which is used by arc_flush().
3352 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3353 arc_buf_contents_t type)
3355 uint64_t total_evicted = 0;
3356 multilist_t *ml = &state->arcs_list[type];
3358 arc_buf_hdr_t **markers;
3360 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3362 num_sublists = multilist_get_num_sublists(ml);
3365 * If we've tried to evict from each sublist, made some
3366 * progress, but still have not hit the target number of bytes
3367 * to evict, we want to keep trying. The markers allow us to
3368 * pick up where we left off for each individual sublist, rather
3369 * than starting from the tail each time.
3371 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3372 for (int i = 0; i < num_sublists; i++) {
3373 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3376 * A b_spa of 0 is used to indicate that this header is
3377 * a marker. This fact is used in arc_adjust_type() and
3378 * arc_evict_state_impl().
3380 markers[i]->b_spa = 0;
3382 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3383 multilist_sublist_insert_tail(mls, markers[i]);
3384 multilist_sublist_unlock(mls);
3388 * While we haven't hit our target number of bytes to evict, or
3389 * we're evicting all available buffers.
3391 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3393 * Start eviction using a randomly selected sublist,
3394 * this is to try and evenly balance eviction across all
3395 * sublists. Always starting at the same sublist
3396 * (e.g. index 0) would cause evictions to favor certain
3397 * sublists over others.
3399 int sublist_idx = multilist_get_random_index(ml);
3400 uint64_t scan_evicted = 0;
3402 for (int i = 0; i < num_sublists; i++) {
3403 uint64_t bytes_remaining;
3404 uint64_t bytes_evicted;
3406 if (bytes == ARC_EVICT_ALL)
3407 bytes_remaining = ARC_EVICT_ALL;
3408 else if (total_evicted < bytes)
3409 bytes_remaining = bytes - total_evicted;
3413 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3414 markers[sublist_idx], spa, bytes_remaining);
3416 scan_evicted += bytes_evicted;
3417 total_evicted += bytes_evicted;
3419 /* we've reached the end, wrap to the beginning */
3420 if (++sublist_idx >= num_sublists)
3425 * If we didn't evict anything during this scan, we have
3426 * no reason to believe we'll evict more during another
3427 * scan, so break the loop.
3429 if (scan_evicted == 0) {
3430 /* This isn't possible, let's make that obvious */
3431 ASSERT3S(bytes, !=, 0);
3434 * When bytes is ARC_EVICT_ALL, the only way to
3435 * break the loop is when scan_evicted is zero.
3436 * In that case, we actually have evicted enough,
3437 * so we don't want to increment the kstat.
3439 if (bytes != ARC_EVICT_ALL) {
3440 ASSERT3S(total_evicted, <, bytes);
3441 ARCSTAT_BUMP(arcstat_evict_not_enough);
3448 for (int i = 0; i < num_sublists; i++) {
3449 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3450 multilist_sublist_remove(mls, markers[i]);
3451 multilist_sublist_unlock(mls);
3453 kmem_cache_free(hdr_full_cache, markers[i]);
3455 kmem_free(markers, sizeof (*markers) * num_sublists);
3457 return (total_evicted);
3461 * Flush all "evictable" data of the given type from the arc state
3462 * specified. This will not evict any "active" buffers (i.e. referenced).
3464 * When 'retry' is set to B_FALSE, the function will make a single pass
3465 * over the state and evict any buffers that it can. Since it doesn't
3466 * continually retry the eviction, it might end up leaving some buffers
3467 * in the ARC due to lock misses.
3469 * When 'retry' is set to B_TRUE, the function will continually retry the
3470 * eviction until *all* evictable buffers have been removed from the
3471 * state. As a result, if concurrent insertions into the state are
3472 * allowed (e.g. if the ARC isn't shutting down), this function might
3473 * wind up in an infinite loop, continually trying to evict buffers.
3476 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3479 uint64_t evicted = 0;
3481 while (refcount_count(&state->arcs_esize[type]) != 0) {
3482 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3492 * Evict the specified number of bytes from the state specified,
3493 * restricting eviction to the spa and type given. This function
3494 * prevents us from trying to evict more from a state's list than
3495 * is "evictable", and to skip evicting altogether when passed a
3496 * negative value for "bytes". In contrast, arc_evict_state() will
3497 * evict everything it can, when passed a negative value for "bytes".
3500 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3501 arc_buf_contents_t type)
3505 if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
3506 delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
3507 return (arc_evict_state(state, spa, delta, type));
3514 * Evict metadata buffers from the cache, such that arc_meta_used is
3515 * capped by the arc_meta_limit tunable.
3518 arc_adjust_meta(void)
3520 uint64_t total_evicted = 0;
3524 * If we're over the meta limit, we want to evict enough
3525 * metadata to get back under the meta limit. We don't want to
3526 * evict so much that we drop the MRU below arc_p, though. If
3527 * we're over the meta limit more than we're over arc_p, we
3528 * evict some from the MRU here, and some from the MFU below.
3530 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3531 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3532 refcount_count(&arc_mru->arcs_size) - arc_p));
3534 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3537 * Similar to the above, we want to evict enough bytes to get us
3538 * below the meta limit, but not so much as to drop us below the
3539 * space alloted to the MFU (which is defined as arc_c - arc_p).
3541 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3542 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3544 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3546 return (total_evicted);
3550 * Return the type of the oldest buffer in the given arc state
3552 * This function will select a random sublist of type ARC_BUFC_DATA and
3553 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3554 * is compared, and the type which contains the "older" buffer will be
3557 static arc_buf_contents_t
3558 arc_adjust_type(arc_state_t *state)
3560 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3561 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3562 int data_idx = multilist_get_random_index(data_ml);
3563 int meta_idx = multilist_get_random_index(meta_ml);
3564 multilist_sublist_t *data_mls;
3565 multilist_sublist_t *meta_mls;
3566 arc_buf_contents_t type;
3567 arc_buf_hdr_t *data_hdr;
3568 arc_buf_hdr_t *meta_hdr;
3571 * We keep the sublist lock until we're finished, to prevent
3572 * the headers from being destroyed via arc_evict_state().
3574 data_mls = multilist_sublist_lock(data_ml, data_idx);
3575 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3578 * These two loops are to ensure we skip any markers that
3579 * might be at the tail of the lists due to arc_evict_state().
3582 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3583 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3584 if (data_hdr->b_spa != 0)
3588 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3589 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3590 if (meta_hdr->b_spa != 0)
3594 if (data_hdr == NULL && meta_hdr == NULL) {
3595 type = ARC_BUFC_DATA;
3596 } else if (data_hdr == NULL) {
3597 ASSERT3P(meta_hdr, !=, NULL);
3598 type = ARC_BUFC_METADATA;
3599 } else if (meta_hdr == NULL) {
3600 ASSERT3P(data_hdr, !=, NULL);
3601 type = ARC_BUFC_DATA;
3603 ASSERT3P(data_hdr, !=, NULL);
3604 ASSERT3P(meta_hdr, !=, NULL);
3606 /* The headers can't be on the sublist without an L1 header */
3607 ASSERT(HDR_HAS_L1HDR(data_hdr));
3608 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3610 if (data_hdr->b_l1hdr.b_arc_access <
3611 meta_hdr->b_l1hdr.b_arc_access) {
3612 type = ARC_BUFC_DATA;
3614 type = ARC_BUFC_METADATA;
3618 multilist_sublist_unlock(meta_mls);
3619 multilist_sublist_unlock(data_mls);
3625 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3630 uint64_t total_evicted = 0;
3635 * If we're over arc_meta_limit, we want to correct that before
3636 * potentially evicting data buffers below.
3638 total_evicted += arc_adjust_meta();
3643 * If we're over the target cache size, we want to evict enough
3644 * from the list to get back to our target size. We don't want
3645 * to evict too much from the MRU, such that it drops below
3646 * arc_p. So, if we're over our target cache size more than
3647 * the MRU is over arc_p, we'll evict enough to get back to
3648 * arc_p here, and then evict more from the MFU below.
3650 target = MIN((int64_t)(arc_size - arc_c),
3651 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3652 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3655 * If we're below arc_meta_min, always prefer to evict data.
3656 * Otherwise, try to satisfy the requested number of bytes to
3657 * evict from the type which contains older buffers; in an
3658 * effort to keep newer buffers in the cache regardless of their
3659 * type. If we cannot satisfy the number of bytes from this
3660 * type, spill over into the next type.
3662 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3663 arc_meta_used > arc_meta_min) {
3664 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3665 total_evicted += bytes;
3668 * If we couldn't evict our target number of bytes from
3669 * metadata, we try to get the rest from data.
3674 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3676 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3677 total_evicted += bytes;
3680 * If we couldn't evict our target number of bytes from
3681 * data, we try to get the rest from metadata.
3686 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3692 * Now that we've tried to evict enough from the MRU to get its
3693 * size back to arc_p, if we're still above the target cache
3694 * size, we evict the rest from the MFU.
3696 target = arc_size - arc_c;
3698 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3699 arc_meta_used > arc_meta_min) {
3700 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3701 total_evicted += bytes;
3704 * If we couldn't evict our target number of bytes from
3705 * metadata, we try to get the rest from data.
3710 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3712 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3713 total_evicted += bytes;
3716 * If we couldn't evict our target number of bytes from
3717 * data, we try to get the rest from data.
3722 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3726 * Adjust ghost lists
3728 * In addition to the above, the ARC also defines target values
3729 * for the ghost lists. The sum of the mru list and mru ghost
3730 * list should never exceed the target size of the cache, and
3731 * the sum of the mru list, mfu list, mru ghost list, and mfu
3732 * ghost list should never exceed twice the target size of the
3733 * cache. The following logic enforces these limits on the ghost
3734 * caches, and evicts from them as needed.
3736 target = refcount_count(&arc_mru->arcs_size) +
3737 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3739 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3740 total_evicted += bytes;
3745 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3748 * We assume the sum of the mru list and mfu list is less than
3749 * or equal to arc_c (we enforced this above), which means we
3750 * can use the simpler of the two equations below:
3752 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3753 * mru ghost + mfu ghost <= arc_c
3755 target = refcount_count(&arc_mru_ghost->arcs_size) +
3756 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3758 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3759 total_evicted += bytes;
3764 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3766 return (total_evicted);
3770 arc_flush(spa_t *spa, boolean_t retry)
3775 * If retry is B_TRUE, a spa must not be specified since we have
3776 * no good way to determine if all of a spa's buffers have been
3777 * evicted from an arc state.
3779 ASSERT(!retry || spa == 0);
3782 guid = spa_load_guid(spa);
3784 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3785 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3787 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3788 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3790 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3791 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3793 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3794 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3798 arc_shrink(int64_t to_free)
3800 if (arc_c > arc_c_min) {
3801 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3802 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3803 if (arc_c > arc_c_min + to_free)
3804 atomic_add_64(&arc_c, -to_free);
3808 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3809 if (arc_c > arc_size)
3810 arc_c = MAX(arc_size, arc_c_min);
3812 arc_p = (arc_c >> 1);
3814 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3817 ASSERT(arc_c >= arc_c_min);
3818 ASSERT((int64_t)arc_p >= 0);
3821 if (arc_size > arc_c) {
3822 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3824 (void) arc_adjust();
3828 static long needfree = 0;
3830 typedef enum free_memory_reason_t {
3835 FMR_PAGES_PP_MAXIMUM,
3839 } free_memory_reason_t;
3841 int64_t last_free_memory;
3842 free_memory_reason_t last_free_reason;
3845 * Additional reserve of pages for pp_reserve.
3847 int64_t arc_pages_pp_reserve = 64;
3850 * Additional reserve of pages for swapfs.
3852 int64_t arc_swapfs_reserve = 64;
3855 * Return the amount of memory that can be consumed before reclaim will be
3856 * needed. Positive if there is sufficient free memory, negative indicates
3857 * the amount of memory that needs to be freed up.
3860 arc_available_memory(void)
3862 int64_t lowest = INT64_MAX;
3864 free_memory_reason_t r = FMR_UNKNOWN;
3868 n = PAGESIZE * (-needfree);
3876 * Cooperate with pagedaemon when it's time for it to scan
3877 * and reclaim some pages.
3879 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3887 * check that we're out of range of the pageout scanner. It starts to
3888 * schedule paging if freemem is less than lotsfree and needfree.
3889 * lotsfree is the high-water mark for pageout, and needfree is the
3890 * number of needed free pages. We add extra pages here to make sure
3891 * the scanner doesn't start up while we're freeing memory.
3893 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3900 * check to make sure that swapfs has enough space so that anon
3901 * reservations can still succeed. anon_resvmem() checks that the
3902 * availrmem is greater than swapfs_minfree, and the number of reserved
3903 * swap pages. We also add a bit of extra here just to prevent
3904 * circumstances from getting really dire.
3906 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3907 desfree - arc_swapfs_reserve);
3910 r = FMR_SWAPFS_MINFREE;
3915 * Check that we have enough availrmem that memory locking (e.g., via
3916 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3917 * stores the number of pages that cannot be locked; when availrmem
3918 * drops below pages_pp_maximum, page locking mechanisms such as
3919 * page_pp_lock() will fail.)
3921 n = PAGESIZE * (availrmem - pages_pp_maximum -
3922 arc_pages_pp_reserve);
3925 r = FMR_PAGES_PP_MAXIMUM;
3928 #endif /* illumos */
3929 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3931 * If we're on an i386 platform, it's possible that we'll exhaust the
3932 * kernel heap space before we ever run out of available physical
3933 * memory. Most checks of the size of the heap_area compare against
3934 * tune.t_minarmem, which is the minimum available real memory that we
3935 * can have in the system. However, this is generally fixed at 25 pages
3936 * which is so low that it's useless. In this comparison, we seek to
3937 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3938 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3941 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3942 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3947 #define zio_arena NULL
3949 #define zio_arena heap_arena
3953 * If zio data pages are being allocated out of a separate heap segment,
3954 * then enforce that the size of available vmem for this arena remains
3955 * above about 1/16th free.
3957 * Note: The 1/16th arena free requirement was put in place
3958 * to aggressively evict memory from the arc in order to avoid
3959 * memory fragmentation issues.
3961 if (zio_arena != NULL) {
3962 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3963 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3971 * Above limits know nothing about real level of KVA fragmentation.
3972 * Start aggressive reclamation if too little sequential KVA left.
3975 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3976 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3985 /* Every 100 calls, free a small amount */
3986 if (spa_get_random(100) == 0)
3988 #endif /* _KERNEL */
3990 last_free_memory = lowest;
3991 last_free_reason = r;
3992 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3998 * Determine if the system is under memory pressure and is asking
3999 * to reclaim memory. A return value of B_TRUE indicates that the system
4000 * is under memory pressure and that the arc should adjust accordingly.
4003 arc_reclaim_needed(void)
4005 return (arc_available_memory() < 0);
4008 extern kmem_cache_t *zio_buf_cache[];
4009 extern kmem_cache_t *zio_data_buf_cache[];
4010 extern kmem_cache_t *range_seg_cache;
4012 static __noinline void
4013 arc_kmem_reap_now(void)
4016 kmem_cache_t *prev_cache = NULL;
4017 kmem_cache_t *prev_data_cache = NULL;
4019 DTRACE_PROBE(arc__kmem_reap_start);
4021 if (arc_meta_used >= arc_meta_limit) {
4023 * We are exceeding our meta-data cache limit.
4024 * Purge some DNLC entries to release holds on meta-data.
4026 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4030 * Reclaim unused memory from all kmem caches.
4036 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4037 if (zio_buf_cache[i] != prev_cache) {
4038 prev_cache = zio_buf_cache[i];
4039 kmem_cache_reap_now(zio_buf_cache[i]);
4041 if (zio_data_buf_cache[i] != prev_data_cache) {
4042 prev_data_cache = zio_data_buf_cache[i];
4043 kmem_cache_reap_now(zio_data_buf_cache[i]);
4046 kmem_cache_reap_now(buf_cache);
4047 kmem_cache_reap_now(hdr_full_cache);
4048 kmem_cache_reap_now(hdr_l2only_cache);
4049 kmem_cache_reap_now(range_seg_cache);
4052 if (zio_arena != NULL) {
4054 * Ask the vmem arena to reclaim unused memory from its
4057 vmem_qcache_reap(zio_arena);
4060 DTRACE_PROBE(arc__kmem_reap_end);
4064 * Threads can block in arc_get_data_buf() waiting for this thread to evict
4065 * enough data and signal them to proceed. When this happens, the threads in
4066 * arc_get_data_buf() are sleeping while holding the hash lock for their
4067 * particular arc header. Thus, we must be careful to never sleep on a
4068 * hash lock in this thread. This is to prevent the following deadlock:
4070 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
4071 * waiting for the reclaim thread to signal it.
4073 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4074 * fails, and goes to sleep forever.
4076 * This possible deadlock is avoided by always acquiring a hash lock
4077 * using mutex_tryenter() from arc_reclaim_thread().
4080 arc_reclaim_thread(void *dummy __unused)
4082 hrtime_t growtime = 0;
4085 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4087 mutex_enter(&arc_reclaim_lock);
4088 while (!arc_reclaim_thread_exit) {
4089 int64_t free_memory = arc_available_memory();
4090 uint64_t evicted = 0;
4093 * This is necessary in order for the mdb ::arc dcmd to
4094 * show up to date information. Since the ::arc command
4095 * does not call the kstat's update function, without
4096 * this call, the command may show stale stats for the
4097 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4098 * with this change, the data might be up to 1 second
4099 * out of date; but that should suffice. The arc_state_t
4100 * structures can be queried directly if more accurate
4101 * information is needed.
4103 if (arc_ksp != NULL)
4104 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4106 mutex_exit(&arc_reclaim_lock);
4108 if (free_memory < 0) {
4110 arc_no_grow = B_TRUE;
4114 * Wait at least zfs_grow_retry (default 60) seconds
4115 * before considering growing.
4117 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4119 arc_kmem_reap_now();
4122 * If we are still low on memory, shrink the ARC
4123 * so that we have arc_shrink_min free space.
4125 free_memory = arc_available_memory();
4128 (arc_c >> arc_shrink_shift) - free_memory;
4131 to_free = MAX(to_free, ptob(needfree));
4133 arc_shrink(to_free);
4135 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4136 arc_no_grow = B_TRUE;
4137 } else if (gethrtime() >= growtime) {
4138 arc_no_grow = B_FALSE;
4141 evicted = arc_adjust();
4143 mutex_enter(&arc_reclaim_lock);
4146 * If evicted is zero, we couldn't evict anything via
4147 * arc_adjust(). This could be due to hash lock
4148 * collisions, but more likely due to the majority of
4149 * arc buffers being unevictable. Therefore, even if
4150 * arc_size is above arc_c, another pass is unlikely to
4151 * be helpful and could potentially cause us to enter an
4154 if (arc_size <= arc_c || evicted == 0) {
4159 * We're either no longer overflowing, or we
4160 * can't evict anything more, so we should wake
4161 * up any threads before we go to sleep.
4163 cv_broadcast(&arc_reclaim_waiters_cv);
4166 * Block until signaled, or after one second (we
4167 * might need to perform arc_kmem_reap_now()
4168 * even if we aren't being signalled)
4170 CALLB_CPR_SAFE_BEGIN(&cpr);
4171 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4172 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4173 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4177 arc_reclaim_thread_exit = B_FALSE;
4178 cv_broadcast(&arc_reclaim_thread_cv);
4179 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
4184 * Adapt arc info given the number of bytes we are trying to add and
4185 * the state that we are comming from. This function is only called
4186 * when we are adding new content to the cache.
4189 arc_adapt(int bytes, arc_state_t *state)
4192 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4193 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
4194 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
4196 if (state == arc_l2c_only)
4201 * Adapt the target size of the MRU list:
4202 * - if we just hit in the MRU ghost list, then increase
4203 * the target size of the MRU list.
4204 * - if we just hit in the MFU ghost list, then increase
4205 * the target size of the MFU list by decreasing the
4206 * target size of the MRU list.
4208 if (state == arc_mru_ghost) {
4209 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4210 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4212 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4213 } else if (state == arc_mfu_ghost) {
4216 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4217 mult = MIN(mult, 10);
4219 delta = MIN(bytes * mult, arc_p);
4220 arc_p = MAX(arc_p_min, arc_p - delta);
4222 ASSERT((int64_t)arc_p >= 0);
4224 if (arc_reclaim_needed()) {
4225 cv_signal(&arc_reclaim_thread_cv);
4232 if (arc_c >= arc_c_max)
4236 * If we're within (2 * maxblocksize) bytes of the target
4237 * cache size, increment the target cache size
4239 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
4240 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
4241 atomic_add_64(&arc_c, (int64_t)bytes);
4242 if (arc_c > arc_c_max)
4244 else if (state == arc_anon)
4245 atomic_add_64(&arc_p, (int64_t)bytes);
4249 ASSERT((int64_t)arc_p >= 0);
4253 * Check if arc_size has grown past our upper threshold, determined by
4254 * zfs_arc_overflow_shift.
4257 arc_is_overflowing(void)
4259 /* Always allow at least one block of overflow */
4260 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4261 arc_c >> zfs_arc_overflow_shift);
4263 return (arc_size >= arc_c + overflow);
4267 * Allocate a block and return it to the caller. If we are hitting the
4268 * hard limit for the cache size, we must sleep, waiting for the eviction
4269 * thread to catch up. If we're past the target size but below the hard
4270 * limit, we'll only signal the reclaim thread and continue on.
4273 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4276 arc_state_t *state = hdr->b_l1hdr.b_state;
4277 arc_buf_contents_t type = arc_buf_type(hdr);
4279 arc_adapt(size, state);
4282 * If arc_size is currently overflowing, and has grown past our
4283 * upper limit, we must be adding data faster than the evict
4284 * thread can evict. Thus, to ensure we don't compound the
4285 * problem by adding more data and forcing arc_size to grow even
4286 * further past it's target size, we halt and wait for the
4287 * eviction thread to catch up.
4289 * It's also possible that the reclaim thread is unable to evict
4290 * enough buffers to get arc_size below the overflow limit (e.g.
4291 * due to buffers being un-evictable, or hash lock collisions).
4292 * In this case, we want to proceed regardless if we're
4293 * overflowing; thus we don't use a while loop here.
4295 if (arc_is_overflowing()) {
4296 mutex_enter(&arc_reclaim_lock);
4299 * Now that we've acquired the lock, we may no longer be
4300 * over the overflow limit, lets check.
4302 * We're ignoring the case of spurious wake ups. If that
4303 * were to happen, it'd let this thread consume an ARC
4304 * buffer before it should have (i.e. before we're under
4305 * the overflow limit and were signalled by the reclaim
4306 * thread). As long as that is a rare occurrence, it
4307 * shouldn't cause any harm.
4309 if (arc_is_overflowing()) {
4310 cv_signal(&arc_reclaim_thread_cv);
4311 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
4314 mutex_exit(&arc_reclaim_lock);
4317 VERIFY3U(hdr->b_type, ==, type);
4318 if (type == ARC_BUFC_METADATA) {
4319 datap = zio_buf_alloc(size);
4320 arc_space_consume(size, ARC_SPACE_META);
4322 ASSERT(type == ARC_BUFC_DATA);
4323 datap = zio_data_buf_alloc(size);
4324 arc_space_consume(size, ARC_SPACE_DATA);
4328 * Update the state size. Note that ghost states have a
4329 * "ghost size" and so don't need to be updated.
4331 if (!GHOST_STATE(state)) {
4333 (void) refcount_add_many(&state->arcs_size, size, tag);
4336 * If this is reached via arc_read, the link is
4337 * protected by the hash lock. If reached via
4338 * arc_buf_alloc, the header should not be accessed by
4339 * any other thread. And, if reached via arc_read_done,
4340 * the hash lock will protect it if it's found in the
4341 * hash table; otherwise no other thread should be
4342 * trying to [add|remove]_reference it.
4344 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4345 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4346 (void) refcount_add_many(&state->arcs_esize[type],
4351 * If we are growing the cache, and we are adding anonymous
4352 * data, and we have outgrown arc_p, update arc_p
4354 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
4355 (refcount_count(&arc_anon->arcs_size) +
4356 refcount_count(&arc_mru->arcs_size) > arc_p))
4357 arc_p = MIN(arc_c, arc_p + size);
4359 ARCSTAT_BUMP(arcstat_allocated);
4364 * Free the arc data buffer.
4367 arc_free_data_buf(arc_buf_hdr_t *hdr, void *data, uint64_t size, void *tag)
4369 arc_state_t *state = hdr->b_l1hdr.b_state;
4370 arc_buf_contents_t type = arc_buf_type(hdr);
4372 /* protected by hash lock, if in the hash table */
4373 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4374 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4375 ASSERT(state != arc_anon && state != arc_l2c_only);
4377 (void) refcount_remove_many(&state->arcs_esize[type],
4380 (void) refcount_remove_many(&state->arcs_size, size, tag);
4382 VERIFY3U(hdr->b_type, ==, type);
4383 if (type == ARC_BUFC_METADATA) {
4384 zio_buf_free(data, size);
4385 arc_space_return(size, ARC_SPACE_META);
4387 ASSERT(type == ARC_BUFC_DATA);
4388 zio_data_buf_free(data, size);
4389 arc_space_return(size, ARC_SPACE_DATA);
4394 * This routine is called whenever a buffer is accessed.
4395 * NOTE: the hash lock is dropped in this function.
4398 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4402 ASSERT(MUTEX_HELD(hash_lock));
4403 ASSERT(HDR_HAS_L1HDR(hdr));
4405 if (hdr->b_l1hdr.b_state == arc_anon) {
4407 * This buffer is not in the cache, and does not
4408 * appear in our "ghost" list. Add the new buffer
4412 ASSERT0(hdr->b_l1hdr.b_arc_access);
4413 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4414 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4415 arc_change_state(arc_mru, hdr, hash_lock);
4417 } else if (hdr->b_l1hdr.b_state == arc_mru) {
4418 now = ddi_get_lbolt();
4421 * If this buffer is here because of a prefetch, then either:
4422 * - clear the flag if this is a "referencing" read
4423 * (any subsequent access will bump this into the MFU state).
4425 * - move the buffer to the head of the list if this is
4426 * another prefetch (to make it less likely to be evicted).
4428 if (HDR_PREFETCH(hdr)) {
4429 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4430 /* link protected by hash lock */
4431 ASSERT(multilist_link_active(
4432 &hdr->b_l1hdr.b_arc_node));
4434 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4435 ARCSTAT_BUMP(arcstat_mru_hits);
4437 hdr->b_l1hdr.b_arc_access = now;
4442 * This buffer has been "accessed" only once so far,
4443 * but it is still in the cache. Move it to the MFU
4446 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4448 * More than 125ms have passed since we
4449 * instantiated this buffer. Move it to the
4450 * most frequently used state.
4452 hdr->b_l1hdr.b_arc_access = now;
4453 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4454 arc_change_state(arc_mfu, hdr, hash_lock);
4456 ARCSTAT_BUMP(arcstat_mru_hits);
4457 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4458 arc_state_t *new_state;
4460 * This buffer has been "accessed" recently, but
4461 * was evicted from the cache. Move it to the
4465 if (HDR_PREFETCH(hdr)) {
4466 new_state = arc_mru;
4467 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4468 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4469 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4471 new_state = arc_mfu;
4472 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4475 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4476 arc_change_state(new_state, hdr, hash_lock);
4478 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4479 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
4481 * This buffer has been accessed more than once and is
4482 * still in the cache. Keep it in the MFU state.
4484 * NOTE: an add_reference() that occurred when we did
4485 * the arc_read() will have kicked this off the list.
4486 * If it was a prefetch, we will explicitly move it to
4487 * the head of the list now.
4489 if ((HDR_PREFETCH(hdr)) != 0) {
4490 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4491 /* link protected by hash_lock */
4492 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4494 ARCSTAT_BUMP(arcstat_mfu_hits);
4495 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4496 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4497 arc_state_t *new_state = arc_mfu;
4499 * This buffer has been accessed more than once but has
4500 * been evicted from the cache. Move it back to the
4504 if (HDR_PREFETCH(hdr)) {
4506 * This is a prefetch access...
4507 * move this block back to the MRU state.
4509 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4510 new_state = arc_mru;
4513 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4514 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4515 arc_change_state(new_state, hdr, hash_lock);
4517 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4518 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4520 * This buffer is on the 2nd Level ARC.
4523 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4524 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4525 arc_change_state(arc_mfu, hdr, hash_lock);
4527 ASSERT(!"invalid arc state");
4531 /* a generic arc_done_func_t which you can use */
4534 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4536 if (zio == NULL || zio->io_error == 0)
4537 bcopy(buf->b_data, arg, HDR_GET_LSIZE(buf->b_hdr));
4538 arc_buf_destroy(buf, arg);
4541 /* a generic arc_done_func_t */
4543 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4545 arc_buf_t **bufp = arg;
4546 if (zio && zio->io_error) {
4547 arc_buf_destroy(buf, arg);
4551 ASSERT(buf->b_data);
4556 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4558 if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4559 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4560 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4562 if (HDR_COMPRESSION_ENABLED(hdr)) {
4563 ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4564 BP_GET_COMPRESS(bp));
4566 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4567 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4572 arc_read_done(zio_t *zio)
4574 arc_buf_hdr_t *hdr = zio->io_private;
4575 arc_buf_t *abuf = NULL; /* buffer we're assigning to callback */
4576 kmutex_t *hash_lock = NULL;
4577 arc_callback_t *callback_list, *acb;
4578 int freeable = B_FALSE;
4581 * The hdr was inserted into hash-table and removed from lists
4582 * prior to starting I/O. We should find this header, since
4583 * it's in the hash table, and it should be legit since it's
4584 * not possible to evict it during the I/O. The only possible
4585 * reason for it not to be found is if we were freed during the
4588 if (HDR_IN_HASH_TABLE(hdr)) {
4589 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4590 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4591 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4592 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4593 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4595 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4598 ASSERT((found == hdr &&
4599 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4600 (found == hdr && HDR_L2_READING(hdr)));
4601 ASSERT3P(hash_lock, !=, NULL);
4604 if (zio->io_error == 0) {
4605 /* byteswap if necessary */
4606 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4607 if (BP_GET_LEVEL(zio->io_bp) > 0) {
4608 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4610 hdr->b_l1hdr.b_byteswap =
4611 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4614 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4618 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
4619 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4620 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4622 callback_list = hdr->b_l1hdr.b_acb;
4623 ASSERT3P(callback_list, !=, NULL);
4625 if (hash_lock && zio->io_error == 0 &&
4626 hdr->b_l1hdr.b_state == arc_anon) {
4628 * Only call arc_access on anonymous buffers. This is because
4629 * if we've issued an I/O for an evicted buffer, we've already
4630 * called arc_access (to prevent any simultaneous readers from
4631 * getting confused).
4633 arc_access(hdr, hash_lock);
4636 /* create copies of the data buffer for the callers */
4637 for (acb = callback_list; acb; acb = acb->acb_next) {
4638 if (acb->acb_done != NULL) {
4640 * If we're here, then this must be a demand read
4641 * since prefetch requests don't have callbacks.
4642 * If a read request has a callback (i.e. acb_done is
4643 * not NULL), then we decompress the data for the
4644 * first request and clone the rest. This avoids
4645 * having to waste cpu resources decompressing data
4646 * that nobody is explicitly waiting to read.
4649 acb->acb_buf = arc_buf_alloc_impl(hdr,
4651 if (zio->io_error == 0) {
4653 arc_decompress(acb->acb_buf);
4655 abuf = acb->acb_buf;
4657 add_reference(hdr, acb->acb_private);
4658 acb->acb_buf = arc_buf_clone(abuf);
4662 hdr->b_l1hdr.b_acb = NULL;
4663 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
4666 * This buffer didn't have a callback so it must
4669 ASSERT(HDR_PREFETCH(hdr));
4670 ASSERT0(hdr->b_l1hdr.b_bufcnt);
4671 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
4674 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4675 callback_list != NULL);
4677 if (zio->io_error == 0) {
4678 arc_hdr_verify(hdr, zio->io_bp);
4680 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
4681 if (hdr->b_l1hdr.b_state != arc_anon)
4682 arc_change_state(arc_anon, hdr, hash_lock);
4683 if (HDR_IN_HASH_TABLE(hdr))
4684 buf_hash_remove(hdr);
4685 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4689 * Broadcast before we drop the hash_lock to avoid the possibility
4690 * that the hdr (and hence the cv) might be freed before we get to
4691 * the cv_broadcast().
4693 cv_broadcast(&hdr->b_l1hdr.b_cv);
4695 if (hash_lock != NULL) {
4696 mutex_exit(hash_lock);
4699 * This block was freed while we waited for the read to
4700 * complete. It has been removed from the hash table and
4701 * moved to the anonymous state (so that it won't show up
4704 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4705 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4708 /* execute each callback and free its structure */
4709 while ((acb = callback_list) != NULL) {
4711 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4713 if (acb->acb_zio_dummy != NULL) {
4714 acb->acb_zio_dummy->io_error = zio->io_error;
4715 zio_nowait(acb->acb_zio_dummy);
4718 callback_list = acb->acb_next;
4719 kmem_free(acb, sizeof (arc_callback_t));
4723 arc_hdr_destroy(hdr);
4727 * "Read" the block at the specified DVA (in bp) via the
4728 * cache. If the block is found in the cache, invoke the provided
4729 * callback immediately and return. Note that the `zio' parameter
4730 * in the callback will be NULL in this case, since no IO was
4731 * required. If the block is not in the cache pass the read request
4732 * on to the spa with a substitute callback function, so that the
4733 * requested block will be added to the cache.
4735 * If a read request arrives for a block that has a read in-progress,
4736 * either wait for the in-progress read to complete (and return the
4737 * results); or, if this is a read with a "done" func, add a record
4738 * to the read to invoke the "done" func when the read completes,
4739 * and return; or just return.
4741 * arc_read_done() will invoke all the requested "done" functions
4742 * for readers of this block.
4745 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4746 void *private, zio_priority_t priority, int zio_flags,
4747 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4749 arc_buf_hdr_t *hdr = NULL;
4750 kmutex_t *hash_lock = NULL;
4752 uint64_t guid = spa_load_guid(spa);
4754 ASSERT(!BP_IS_EMBEDDED(bp) ||
4755 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4758 if (!BP_IS_EMBEDDED(bp)) {
4760 * Embedded BP's have no DVA and require no I/O to "read".
4761 * Create an anonymous arc buf to back it.
4763 hdr = buf_hash_find(guid, bp, &hash_lock);
4766 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pdata != NULL) {
4767 arc_buf_t *buf = NULL;
4768 *arc_flags |= ARC_FLAG_CACHED;
4770 if (HDR_IO_IN_PROGRESS(hdr)) {
4772 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4773 priority == ZIO_PRIORITY_SYNC_READ) {
4775 * This sync read must wait for an
4776 * in-progress async read (e.g. a predictive
4777 * prefetch). Async reads are queued
4778 * separately at the vdev_queue layer, so
4779 * this is a form of priority inversion.
4780 * Ideally, we would "inherit" the demand
4781 * i/o's priority by moving the i/o from
4782 * the async queue to the synchronous queue,
4783 * but there is currently no mechanism to do
4784 * so. Track this so that we can evaluate
4785 * the magnitude of this potential performance
4788 * Note that if the prefetch i/o is already
4789 * active (has been issued to the device),
4790 * the prefetch improved performance, because
4791 * we issued it sooner than we would have
4792 * without the prefetch.
4794 DTRACE_PROBE1(arc__sync__wait__for__async,
4795 arc_buf_hdr_t *, hdr);
4796 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4798 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4799 arc_hdr_clear_flags(hdr,
4800 ARC_FLAG_PREDICTIVE_PREFETCH);
4803 if (*arc_flags & ARC_FLAG_WAIT) {
4804 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4805 mutex_exit(hash_lock);
4808 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4811 arc_callback_t *acb = NULL;
4813 acb = kmem_zalloc(sizeof (arc_callback_t),
4815 acb->acb_done = done;
4816 acb->acb_private = private;
4818 acb->acb_zio_dummy = zio_null(pio,
4819 spa, NULL, NULL, NULL, zio_flags);
4821 ASSERT3P(acb->acb_done, !=, NULL);
4822 acb->acb_next = hdr->b_l1hdr.b_acb;
4823 hdr->b_l1hdr.b_acb = acb;
4824 mutex_exit(hash_lock);
4827 mutex_exit(hash_lock);
4831 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4832 hdr->b_l1hdr.b_state == arc_mfu);
4835 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4837 * This is a demand read which does not have to
4838 * wait for i/o because we did a predictive
4839 * prefetch i/o for it, which has completed.
4842 arc__demand__hit__predictive__prefetch,
4843 arc_buf_hdr_t *, hdr);
4845 arcstat_demand_hit_predictive_prefetch);
4846 arc_hdr_clear_flags(hdr,
4847 ARC_FLAG_PREDICTIVE_PREFETCH);
4849 ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
4852 * If this block is already in use, create a new
4853 * copy of the data so that we will be guaranteed
4854 * that arc_release() will always succeed.
4856 buf = hdr->b_l1hdr.b_buf;
4858 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4859 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
4860 buf = arc_buf_alloc_impl(hdr, private);
4861 VERIFY0(arc_decompress(buf));
4863 add_reference(hdr, private);
4864 buf = arc_buf_clone(buf);
4866 ASSERT3P(buf->b_data, !=, NULL);
4868 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4869 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4870 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
4872 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4873 arc_access(hdr, hash_lock);
4874 if (*arc_flags & ARC_FLAG_L2CACHE)
4875 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
4876 mutex_exit(hash_lock);
4877 ARCSTAT_BUMP(arcstat_hits);
4878 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4879 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4880 data, metadata, hits);
4883 done(NULL, buf, private);
4885 uint64_t lsize = BP_GET_LSIZE(bp);
4886 uint64_t psize = BP_GET_PSIZE(bp);
4887 arc_callback_t *acb;
4890 boolean_t devw = B_FALSE;
4894 /* this block is not in the cache */
4895 arc_buf_hdr_t *exists = NULL;
4896 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4897 hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
4898 BP_GET_COMPRESS(bp), type);
4900 if (!BP_IS_EMBEDDED(bp)) {
4901 hdr->b_dva = *BP_IDENTITY(bp);
4902 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4903 exists = buf_hash_insert(hdr, &hash_lock);
4905 if (exists != NULL) {
4906 /* somebody beat us to the hash insert */
4907 mutex_exit(hash_lock);
4908 buf_discard_identity(hdr);
4909 arc_hdr_destroy(hdr);
4910 goto top; /* restart the IO request */
4914 * This block is in the ghost cache. If it was L2-only
4915 * (and thus didn't have an L1 hdr), we realloc the
4916 * header to add an L1 hdr.
4918 if (!HDR_HAS_L1HDR(hdr)) {
4919 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4922 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
4923 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4924 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4925 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4926 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4929 * This is a delicate dance that we play here.
4930 * This hdr is in the ghost list so we access it
4931 * to move it out of the ghost list before we
4932 * initiate the read. If it's a prefetch then
4933 * it won't have a callback so we'll remove the
4934 * reference that arc_buf_alloc_impl() created. We
4935 * do this after we've called arc_access() to
4936 * avoid hitting an assert in remove_reference().
4938 arc_access(hdr, hash_lock);
4939 arc_hdr_alloc_pdata(hdr);
4941 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
4942 size = arc_hdr_size(hdr);
4945 * If compression is enabled on the hdr, then will do
4946 * RAW I/O and will store the compressed data in the hdr's
4947 * data block. Otherwise, the hdr's data block will contain
4948 * the uncompressed data.
4950 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
4951 zio_flags |= ZIO_FLAG_RAW;
4954 if (*arc_flags & ARC_FLAG_PREFETCH)
4955 arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
4956 if (*arc_flags & ARC_FLAG_L2CACHE)
4957 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
4958 if (BP_GET_LEVEL(bp) > 0)
4959 arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
4960 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4961 arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
4962 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4964 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4965 acb->acb_done = done;
4966 acb->acb_private = private;
4968 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
4969 hdr->b_l1hdr.b_acb = acb;
4970 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
4972 if (HDR_HAS_L2HDR(hdr) &&
4973 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4974 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4975 addr = hdr->b_l2hdr.b_daddr;
4977 * Lock out device removal.
4979 if (vdev_is_dead(vd) ||
4980 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4984 if (priority == ZIO_PRIORITY_ASYNC_READ)
4985 arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
4987 arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
4989 if (hash_lock != NULL)
4990 mutex_exit(hash_lock);
4993 * At this point, we have a level 1 cache miss. Try again in
4994 * L2ARC if possible.
4996 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
4998 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4999 uint64_t, lsize, zbookmark_phys_t *, zb);
5000 ARCSTAT_BUMP(arcstat_misses);
5001 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5002 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5003 data, metadata, misses);
5005 curthread->td_ru.ru_inblock++;
5008 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5010 * Read from the L2ARC if the following are true:
5011 * 1. The L2ARC vdev was previously cached.
5012 * 2. This buffer still has L2ARC metadata.
5013 * 3. This buffer isn't currently writing to the L2ARC.
5014 * 4. The L2ARC entry wasn't evicted, which may
5015 * also have invalidated the vdev.
5016 * 5. This isn't prefetch and l2arc_noprefetch is set.
5018 if (HDR_HAS_L2HDR(hdr) &&
5019 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5020 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5021 l2arc_read_callback_t *cb;
5024 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5025 ARCSTAT_BUMP(arcstat_l2_hits);
5027 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5029 cb->l2rcb_hdr = hdr;
5032 cb->l2rcb_flags = zio_flags;
5033 uint64_t asize = vdev_psize_to_asize(vd, size);
5034 if (asize != size) {
5035 b_data = zio_data_buf_alloc(asize);
5036 cb->l2rcb_data = b_data;
5038 b_data = hdr->b_l1hdr.b_pdata;
5041 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5042 addr + asize < vd->vdev_psize -
5043 VDEV_LABEL_END_SIZE);
5046 * l2arc read. The SCL_L2ARC lock will be
5047 * released by l2arc_read_done().
5048 * Issue a null zio if the underlying buffer
5049 * was squashed to zero size by compression.
5051 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5052 ZIO_COMPRESS_EMPTY);
5053 rzio = zio_read_phys(pio, vd, addr,
5056 l2arc_read_done, cb, priority,
5057 zio_flags | ZIO_FLAG_DONT_CACHE |
5059 ZIO_FLAG_DONT_PROPAGATE |
5060 ZIO_FLAG_DONT_RETRY, B_FALSE);
5061 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5063 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5065 if (*arc_flags & ARC_FLAG_NOWAIT) {
5070 ASSERT(*arc_flags & ARC_FLAG_WAIT);
5071 if (zio_wait(rzio) == 0)
5074 /* l2arc read error; goto zio_read() */
5076 DTRACE_PROBE1(l2arc__miss,
5077 arc_buf_hdr_t *, hdr);
5078 ARCSTAT_BUMP(arcstat_l2_misses);
5079 if (HDR_L2_WRITING(hdr))
5080 ARCSTAT_BUMP(arcstat_l2_rw_clash);
5081 spa_config_exit(spa, SCL_L2ARC, vd);
5085 spa_config_exit(spa, SCL_L2ARC, vd);
5086 if (l2arc_ndev != 0) {
5087 DTRACE_PROBE1(l2arc__miss,
5088 arc_buf_hdr_t *, hdr);
5089 ARCSTAT_BUMP(arcstat_l2_misses);
5093 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pdata, size,
5094 arc_read_done, hdr, priority, zio_flags, zb);
5096 if (*arc_flags & ARC_FLAG_WAIT)
5097 return (zio_wait(rzio));
5099 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5106 * Notify the arc that a block was freed, and thus will never be used again.
5109 arc_freed(spa_t *spa, const blkptr_t *bp)
5112 kmutex_t *hash_lock;
5113 uint64_t guid = spa_load_guid(spa);
5115 ASSERT(!BP_IS_EMBEDDED(bp));
5117 hdr = buf_hash_find(guid, bp, &hash_lock);
5122 * We might be trying to free a block that is still doing I/O
5123 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5124 * dmu_sync-ed block). If this block is being prefetched, then it
5125 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5126 * until the I/O completes. A block may also have a reference if it is
5127 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5128 * have written the new block to its final resting place on disk but
5129 * without the dedup flag set. This would have left the hdr in the MRU
5130 * state and discoverable. When the txg finally syncs it detects that
5131 * the block was overridden in open context and issues an override I/O.
5132 * Since this is a dedup block, the override I/O will determine if the
5133 * block is already in the DDT. If so, then it will replace the io_bp
5134 * with the bp from the DDT and allow the I/O to finish. When the I/O
5135 * reaches the done callback, dbuf_write_override_done, it will
5136 * check to see if the io_bp and io_bp_override are identical.
5137 * If they are not, then it indicates that the bp was replaced with
5138 * the bp in the DDT and the override bp is freed. This allows
5139 * us to arrive here with a reference on a block that is being
5140 * freed. So if we have an I/O in progress, or a reference to
5141 * this hdr, then we don't destroy the hdr.
5143 if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5144 refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5145 arc_change_state(arc_anon, hdr, hash_lock);
5146 arc_hdr_destroy(hdr);
5147 mutex_exit(hash_lock);
5149 mutex_exit(hash_lock);
5155 * Release this buffer from the cache, making it an anonymous buffer. This
5156 * must be done after a read and prior to modifying the buffer contents.
5157 * If the buffer has more than one reference, we must make
5158 * a new hdr for the buffer.
5161 arc_release(arc_buf_t *buf, void *tag)
5163 arc_buf_hdr_t *hdr = buf->b_hdr;
5166 * It would be nice to assert that if it's DMU metadata (level >
5167 * 0 || it's the dnode file), then it must be syncing context.
5168 * But we don't know that information at this level.
5171 mutex_enter(&buf->b_evict_lock);
5173 ASSERT(HDR_HAS_L1HDR(hdr));
5176 * We don't grab the hash lock prior to this check, because if
5177 * the buffer's header is in the arc_anon state, it won't be
5178 * linked into the hash table.
5180 if (hdr->b_l1hdr.b_state == arc_anon) {
5181 mutex_exit(&buf->b_evict_lock);
5182 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5183 ASSERT(!HDR_IN_HASH_TABLE(hdr));
5184 ASSERT(!HDR_HAS_L2HDR(hdr));
5185 ASSERT(HDR_EMPTY(hdr));
5186 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5187 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5188 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5190 hdr->b_l1hdr.b_arc_access = 0;
5193 * If the buf is being overridden then it may already
5194 * have a hdr that is not empty.
5196 buf_discard_identity(hdr);
5202 kmutex_t *hash_lock = HDR_LOCK(hdr);
5203 mutex_enter(hash_lock);
5206 * This assignment is only valid as long as the hash_lock is
5207 * held, we must be careful not to reference state or the
5208 * b_state field after dropping the lock.
5210 arc_state_t *state = hdr->b_l1hdr.b_state;
5211 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5212 ASSERT3P(state, !=, arc_anon);
5214 /* this buffer is not on any list */
5215 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
5217 if (HDR_HAS_L2HDR(hdr)) {
5218 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5221 * We have to recheck this conditional again now that
5222 * we're holding the l2ad_mtx to prevent a race with
5223 * another thread which might be concurrently calling
5224 * l2arc_evict(). In that case, l2arc_evict() might have
5225 * destroyed the header's L2 portion as we were waiting
5226 * to acquire the l2ad_mtx.
5228 if (HDR_HAS_L2HDR(hdr)) {
5230 arc_hdr_l2hdr_destroy(hdr);
5233 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5237 * Do we have more than one buf?
5239 if (hdr->b_l1hdr.b_bufcnt > 1) {
5240 arc_buf_hdr_t *nhdr;
5242 uint64_t spa = hdr->b_spa;
5243 uint64_t psize = HDR_GET_PSIZE(hdr);
5244 uint64_t lsize = HDR_GET_LSIZE(hdr);
5245 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5246 arc_buf_contents_t type = arc_buf_type(hdr);
5247 VERIFY3U(hdr->b_type, ==, type);
5249 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5250 (void) remove_reference(hdr, hash_lock, tag);
5252 if (arc_buf_is_shared(buf)) {
5253 ASSERT(HDR_SHARED_DATA(hdr));
5254 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5255 ASSERT(ARC_BUF_LAST(buf));
5259 * Pull the data off of this hdr and attach it to
5260 * a new anonymous hdr. Also find the last buffer
5261 * in the hdr's buffer list.
5263 arc_buf_t *lastbuf = NULL;
5264 bufp = &hdr->b_l1hdr.b_buf;
5265 while (*bufp != NULL) {
5267 *bufp = buf->b_next;
5271 * If we've removed a buffer in the middle of
5272 * the list then update the lastbuf and update
5275 if (*bufp != NULL) {
5277 bufp = &(*bufp)->b_next;
5281 ASSERT3P(lastbuf, !=, buf);
5282 ASSERT3P(lastbuf, !=, NULL);
5285 * If the current arc_buf_t and the hdr are sharing their data
5286 * buffer, then we must stop sharing that block, transfer
5287 * ownership and setup sharing with a new arc_buf_t at the end
5288 * of the hdr's b_buf list.
5290 if (arc_buf_is_shared(buf)) {
5291 ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5292 ASSERT(ARC_BUF_LAST(lastbuf));
5293 VERIFY(!arc_buf_is_shared(lastbuf));
5296 * First, sever the block sharing relationship between
5297 * buf and the arc_buf_hdr_t. Then, setup a new
5298 * block sharing relationship with the last buffer
5299 * on the arc_buf_t list.
5301 arc_unshare_buf(hdr, buf);
5302 arc_share_buf(hdr, lastbuf);
5303 VERIFY3P(lastbuf->b_data, !=, NULL);
5304 } else if (HDR_SHARED_DATA(hdr)) {
5305 ASSERT(arc_buf_is_shared(lastbuf));
5307 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
5308 ASSERT3P(state, !=, arc_l2c_only);
5310 (void) refcount_remove_many(&state->arcs_size,
5311 HDR_GET_LSIZE(hdr), buf);
5313 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5314 ASSERT3P(state, !=, arc_l2c_only);
5315 (void) refcount_remove_many(&state->arcs_esize[type],
5316 HDR_GET_LSIZE(hdr), buf);
5319 hdr->b_l1hdr.b_bufcnt -= 1;
5320 arc_cksum_verify(buf);
5322 arc_buf_unwatch(buf);
5325 mutex_exit(hash_lock);
5328 * Allocate a new hdr. The new hdr will contain a b_pdata
5329 * buffer which will be freed in arc_write().
5331 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5332 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5333 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5334 ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
5335 VERIFY3U(nhdr->b_type, ==, type);
5336 ASSERT(!HDR_SHARED_DATA(nhdr));
5338 nhdr->b_l1hdr.b_buf = buf;
5339 nhdr->b_l1hdr.b_bufcnt = 1;
5340 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5343 mutex_exit(&buf->b_evict_lock);
5344 (void) refcount_add_many(&arc_anon->arcs_size,
5345 HDR_GET_LSIZE(nhdr), buf);
5347 mutex_exit(&buf->b_evict_lock);
5348 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5349 /* protected by hash lock, or hdr is on arc_anon */
5350 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5351 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5352 arc_change_state(arc_anon, hdr, hash_lock);
5353 hdr->b_l1hdr.b_arc_access = 0;
5354 mutex_exit(hash_lock);
5356 buf_discard_identity(hdr);
5362 arc_released(arc_buf_t *buf)
5366 mutex_enter(&buf->b_evict_lock);
5367 released = (buf->b_data != NULL &&
5368 buf->b_hdr->b_l1hdr.b_state == arc_anon);
5369 mutex_exit(&buf->b_evict_lock);
5375 arc_referenced(arc_buf_t *buf)
5379 mutex_enter(&buf->b_evict_lock);
5380 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5381 mutex_exit(&buf->b_evict_lock);
5382 return (referenced);
5387 arc_write_ready(zio_t *zio)
5389 arc_write_callback_t *callback = zio->io_private;
5390 arc_buf_t *buf = callback->awcb_buf;
5391 arc_buf_hdr_t *hdr = buf->b_hdr;
5392 uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5394 ASSERT(HDR_HAS_L1HDR(hdr));
5395 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5396 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5399 * If we're reexecuting this zio because the pool suspended, then
5400 * cleanup any state that was previously set the first time the
5401 * callback as invoked.
5403 if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5404 arc_cksum_free(hdr);
5406 arc_buf_unwatch(buf);
5408 if (hdr->b_l1hdr.b_pdata != NULL) {
5409 if (arc_buf_is_shared(buf)) {
5410 ASSERT(HDR_SHARED_DATA(hdr));
5412 arc_unshare_buf(hdr, buf);
5414 arc_hdr_free_pdata(hdr);
5418 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5419 ASSERT(!HDR_SHARED_DATA(hdr));
5420 ASSERT(!arc_buf_is_shared(buf));
5422 callback->awcb_ready(zio, buf, callback->awcb_private);
5424 if (HDR_IO_IN_PROGRESS(hdr))
5425 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5427 arc_cksum_compute(buf);
5428 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5430 enum zio_compress compress;
5431 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5432 compress = ZIO_COMPRESS_OFF;
5434 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5435 compress = BP_GET_COMPRESS(zio->io_bp);
5437 HDR_SET_PSIZE(hdr, psize);
5438 arc_hdr_set_compress(hdr, compress);
5441 * If the hdr is compressed, then copy the compressed
5442 * zio contents into arc_buf_hdr_t. Otherwise, copy the original
5443 * data buf into the hdr. Ideally, we would like to always copy the
5444 * io_data into b_pdata but the user may have disabled compressed
5445 * arc thus the on-disk block may or may not match what we maintain
5446 * in the hdr's b_pdata field.
5448 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5449 ASSERT(BP_GET_COMPRESS(zio->io_bp) != ZIO_COMPRESS_OFF);
5450 ASSERT3U(psize, >, 0);
5451 arc_hdr_alloc_pdata(hdr);
5452 bcopy(zio->io_data, hdr->b_l1hdr.b_pdata, psize);
5454 ASSERT3P(buf->b_data, ==, zio->io_orig_data);
5455 ASSERT3U(zio->io_orig_size, ==, HDR_GET_LSIZE(hdr));
5456 ASSERT3U(hdr->b_l1hdr.b_byteswap, ==, DMU_BSWAP_NUMFUNCS);
5457 ASSERT(!HDR_SHARED_DATA(hdr));
5458 ASSERT(!arc_buf_is_shared(buf));
5459 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5460 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5463 * This hdr is not compressed so we're able to share
5464 * the arc_buf_t data buffer with the hdr.
5466 arc_share_buf(hdr, buf);
5467 VERIFY0(bcmp(zio->io_orig_data, hdr->b_l1hdr.b_pdata,
5468 HDR_GET_LSIZE(hdr)));
5470 arc_hdr_verify(hdr, zio->io_bp);
5474 arc_write_children_ready(zio_t *zio)
5476 arc_write_callback_t *callback = zio->io_private;
5477 arc_buf_t *buf = callback->awcb_buf;
5479 callback->awcb_children_ready(zio, buf, callback->awcb_private);
5483 * The SPA calls this callback for each physical write that happens on behalf
5484 * of a logical write. See the comment in dbuf_write_physdone() for details.
5487 arc_write_physdone(zio_t *zio)
5489 arc_write_callback_t *cb = zio->io_private;
5490 if (cb->awcb_physdone != NULL)
5491 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
5495 arc_write_done(zio_t *zio)
5497 arc_write_callback_t *callback = zio->io_private;
5498 arc_buf_t *buf = callback->awcb_buf;
5499 arc_buf_hdr_t *hdr = buf->b_hdr;
5501 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5503 if (zio->io_error == 0) {
5504 arc_hdr_verify(hdr, zio->io_bp);
5506 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5507 buf_discard_identity(hdr);
5509 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5510 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5513 ASSERT(HDR_EMPTY(hdr));
5517 * If the block to be written was all-zero or compressed enough to be
5518 * embedded in the BP, no write was performed so there will be no
5519 * dva/birth/checksum. The buffer must therefore remain anonymous
5522 if (!HDR_EMPTY(hdr)) {
5523 arc_buf_hdr_t *exists;
5524 kmutex_t *hash_lock;
5526 ASSERT(zio->io_error == 0);
5528 arc_cksum_verify(buf);
5530 exists = buf_hash_insert(hdr, &hash_lock);
5531 if (exists != NULL) {
5533 * This can only happen if we overwrite for
5534 * sync-to-convergence, because we remove
5535 * buffers from the hash table when we arc_free().
5537 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5538 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5539 panic("bad overwrite, hdr=%p exists=%p",
5540 (void *)hdr, (void *)exists);
5541 ASSERT(refcount_is_zero(
5542 &exists->b_l1hdr.b_refcnt));
5543 arc_change_state(arc_anon, exists, hash_lock);
5544 mutex_exit(hash_lock);
5545 arc_hdr_destroy(exists);
5546 exists = buf_hash_insert(hdr, &hash_lock);
5547 ASSERT3P(exists, ==, NULL);
5548 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5550 ASSERT(zio->io_prop.zp_nopwrite);
5551 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5552 panic("bad nopwrite, hdr=%p exists=%p",
5553 (void *)hdr, (void *)exists);
5556 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
5557 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5558 ASSERT(BP_GET_DEDUP(zio->io_bp));
5559 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5562 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5563 /* if it's not anon, we are doing a scrub */
5564 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5565 arc_access(hdr, hash_lock);
5566 mutex_exit(hash_lock);
5568 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5571 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5572 callback->awcb_done(zio, buf, callback->awcb_private);
5574 kmem_free(callback, sizeof (arc_write_callback_t));
5578 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5579 boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
5580 arc_done_func_t *children_ready, arc_done_func_t *physdone,
5581 arc_done_func_t *done, void *private, zio_priority_t priority,
5582 int zio_flags, const zbookmark_phys_t *zb)
5584 arc_buf_hdr_t *hdr = buf->b_hdr;
5585 arc_write_callback_t *callback;
5588 ASSERT3P(ready, !=, NULL);
5589 ASSERT3P(done, !=, NULL);
5590 ASSERT(!HDR_IO_ERROR(hdr));
5591 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5592 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5593 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
5595 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5596 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5597 callback->awcb_ready = ready;
5598 callback->awcb_children_ready = children_ready;
5599 callback->awcb_physdone = physdone;
5600 callback->awcb_done = done;
5601 callback->awcb_private = private;
5602 callback->awcb_buf = buf;
5605 * The hdr's b_pdata is now stale, free it now. A new data block
5606 * will be allocated when the zio pipeline calls arc_write_ready().
5608 if (hdr->b_l1hdr.b_pdata != NULL) {
5610 * If the buf is currently sharing the data block with
5611 * the hdr then we need to break that relationship here.
5612 * The hdr will remain with a NULL data pointer and the
5613 * buf will take sole ownership of the block.
5615 if (arc_buf_is_shared(buf)) {
5616 ASSERT(ARC_BUF_LAST(buf));
5617 arc_unshare_buf(hdr, buf);
5619 arc_hdr_free_pdata(hdr);
5621 VERIFY3P(buf->b_data, !=, NULL);
5622 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5624 ASSERT(!arc_buf_is_shared(buf));
5625 ASSERT3P(hdr->b_l1hdr.b_pdata, ==, NULL);
5627 zio = zio_write(pio, spa, txg, bp, buf->b_data, HDR_GET_LSIZE(hdr), zp,
5629 (children_ready != NULL) ? arc_write_children_ready : NULL,
5630 arc_write_physdone, arc_write_done, callback,
5631 priority, zio_flags, zb);
5637 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5640 uint64_t available_memory = ptob(freemem);
5641 static uint64_t page_load = 0;
5642 static uint64_t last_txg = 0;
5644 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5646 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5649 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5652 if (txg > last_txg) {
5657 * If we are in pageout, we know that memory is already tight,
5658 * the arc is already going to be evicting, so we just want to
5659 * continue to let page writes occur as quickly as possible.
5661 if (curproc == pageproc) {
5662 if (page_load > MAX(ptob(minfree), available_memory) / 4)
5663 return (SET_ERROR(ERESTART));
5664 /* Note: reserve is inflated, so we deflate */
5665 page_load += reserve / 8;
5667 } else if (page_load > 0 && arc_reclaim_needed()) {
5668 /* memory is low, delay before restarting */
5669 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5670 return (SET_ERROR(EAGAIN));
5678 arc_tempreserve_clear(uint64_t reserve)
5680 atomic_add_64(&arc_tempreserve, -reserve);
5681 ASSERT((int64_t)arc_tempreserve >= 0);
5685 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5690 if (reserve > arc_c/4 && !arc_no_grow) {
5691 arc_c = MIN(arc_c_max, reserve * 4);
5692 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5694 if (reserve > arc_c)
5695 return (SET_ERROR(ENOMEM));
5698 * Don't count loaned bufs as in flight dirty data to prevent long
5699 * network delays from blocking transactions that are ready to be
5700 * assigned to a txg.
5702 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5703 arc_loaned_bytes), 0);
5706 * Writes will, almost always, require additional memory allocations
5707 * in order to compress/encrypt/etc the data. We therefore need to
5708 * make sure that there is sufficient available memory for this.
5710 error = arc_memory_throttle(reserve, txg);
5715 * Throttle writes when the amount of dirty data in the cache
5716 * gets too large. We try to keep the cache less than half full
5717 * of dirty blocks so that our sync times don't grow too large.
5718 * Note: if two requests come in concurrently, we might let them
5719 * both succeed, when one of them should fail. Not a huge deal.
5722 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5723 anon_size > arc_c / 4) {
5724 uint64_t meta_esize =
5725 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5726 uint64_t data_esize =
5727 refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5728 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5729 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5730 arc_tempreserve >> 10, meta_esize >> 10,
5731 data_esize >> 10, reserve >> 10, arc_c >> 10);
5732 return (SET_ERROR(ERESTART));
5734 atomic_add_64(&arc_tempreserve, reserve);
5739 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5740 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5742 size->value.ui64 = refcount_count(&state->arcs_size);
5743 evict_data->value.ui64 =
5744 refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5745 evict_metadata->value.ui64 =
5746 refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
5750 arc_kstat_update(kstat_t *ksp, int rw)
5752 arc_stats_t *as = ksp->ks_data;
5754 if (rw == KSTAT_WRITE) {
5757 arc_kstat_update_state(arc_anon,
5758 &as->arcstat_anon_size,
5759 &as->arcstat_anon_evictable_data,
5760 &as->arcstat_anon_evictable_metadata);
5761 arc_kstat_update_state(arc_mru,
5762 &as->arcstat_mru_size,
5763 &as->arcstat_mru_evictable_data,
5764 &as->arcstat_mru_evictable_metadata);
5765 arc_kstat_update_state(arc_mru_ghost,
5766 &as->arcstat_mru_ghost_size,
5767 &as->arcstat_mru_ghost_evictable_data,
5768 &as->arcstat_mru_ghost_evictable_metadata);
5769 arc_kstat_update_state(arc_mfu,
5770 &as->arcstat_mfu_size,
5771 &as->arcstat_mfu_evictable_data,
5772 &as->arcstat_mfu_evictable_metadata);
5773 arc_kstat_update_state(arc_mfu_ghost,
5774 &as->arcstat_mfu_ghost_size,
5775 &as->arcstat_mfu_ghost_evictable_data,
5776 &as->arcstat_mfu_ghost_evictable_metadata);
5783 * This function *must* return indices evenly distributed between all
5784 * sublists of the multilist. This is needed due to how the ARC eviction
5785 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5786 * distributed between all sublists and uses this assumption when
5787 * deciding which sublist to evict from and how much to evict from it.
5790 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5792 arc_buf_hdr_t *hdr = obj;
5795 * We rely on b_dva to generate evenly distributed index
5796 * numbers using buf_hash below. So, as an added precaution,
5797 * let's make sure we never add empty buffers to the arc lists.
5799 ASSERT(!HDR_EMPTY(hdr));
5802 * The assumption here, is the hash value for a given
5803 * arc_buf_hdr_t will remain constant throughout it's lifetime
5804 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5805 * Thus, we don't need to store the header's sublist index
5806 * on insertion, as this index can be recalculated on removal.
5808 * Also, the low order bits of the hash value are thought to be
5809 * distributed evenly. Otherwise, in the case that the multilist
5810 * has a power of two number of sublists, each sublists' usage
5811 * would not be evenly distributed.
5813 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5814 multilist_get_num_sublists(ml));
5818 static eventhandler_tag arc_event_lowmem = NULL;
5821 arc_lowmem(void *arg __unused, int howto __unused)
5824 mutex_enter(&arc_reclaim_lock);
5825 /* XXX: Memory deficit should be passed as argument. */
5826 needfree = btoc(arc_c >> arc_shrink_shift);
5827 DTRACE_PROBE(arc__needfree);
5828 cv_signal(&arc_reclaim_thread_cv);
5831 * It is unsafe to block here in arbitrary threads, because we can come
5832 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5833 * with ARC reclaim thread.
5835 if (curproc == pageproc)
5836 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5837 mutex_exit(&arc_reclaim_lock);
5842 arc_state_init(void)
5844 arc_anon = &ARC_anon;
5846 arc_mru_ghost = &ARC_mru_ghost;
5848 arc_mfu_ghost = &ARC_mfu_ghost;
5849 arc_l2c_only = &ARC_l2c_only;
5851 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5852 sizeof (arc_buf_hdr_t),
5853 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5854 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5855 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5856 sizeof (arc_buf_hdr_t),
5857 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5858 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5859 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5860 sizeof (arc_buf_hdr_t),
5861 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5862 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5863 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5864 sizeof (arc_buf_hdr_t),
5865 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5866 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5867 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5868 sizeof (arc_buf_hdr_t),
5869 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5870 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5871 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5872 sizeof (arc_buf_hdr_t),
5873 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5874 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5875 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5876 sizeof (arc_buf_hdr_t),
5877 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5878 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5879 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5880 sizeof (arc_buf_hdr_t),
5881 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5882 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5883 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5884 sizeof (arc_buf_hdr_t),
5885 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5886 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5887 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5888 sizeof (arc_buf_hdr_t),
5889 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5890 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5892 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5893 refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5894 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
5895 refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
5896 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
5897 refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
5898 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
5899 refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
5900 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
5901 refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
5902 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
5903 refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
5905 refcount_create(&arc_anon->arcs_size);
5906 refcount_create(&arc_mru->arcs_size);
5907 refcount_create(&arc_mru_ghost->arcs_size);
5908 refcount_create(&arc_mfu->arcs_size);
5909 refcount_create(&arc_mfu_ghost->arcs_size);
5910 refcount_create(&arc_l2c_only->arcs_size);
5914 arc_state_fini(void)
5916 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5917 refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5918 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
5919 refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
5920 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
5921 refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
5922 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
5923 refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
5924 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
5925 refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
5926 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
5927 refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
5929 refcount_destroy(&arc_anon->arcs_size);
5930 refcount_destroy(&arc_mru->arcs_size);
5931 refcount_destroy(&arc_mru_ghost->arcs_size);
5932 refcount_destroy(&arc_mfu->arcs_size);
5933 refcount_destroy(&arc_mfu_ghost->arcs_size);
5934 refcount_destroy(&arc_l2c_only->arcs_size);
5936 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5937 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5938 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5939 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5940 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5941 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5942 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5943 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5955 int i, prefetch_tunable_set = 0;
5957 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5958 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5959 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5961 /* Convert seconds to clock ticks */
5962 arc_min_prefetch_lifespan = 1 * hz;
5964 /* Start out with 1/8 of all memory */
5965 arc_c = kmem_size() / 8;
5970 * On architectures where the physical memory can be larger
5971 * than the addressable space (intel in 32-bit mode), we may
5972 * need to limit the cache to 1/8 of VM size.
5974 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5976 #endif /* illumos */
5977 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
5978 arc_c_min = MAX(arc_c / 4, arc_abs_min);
5979 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5980 if (arc_c * 8 >= 1 << 30)
5981 arc_c_max = (arc_c * 8) - (1 << 30);
5983 arc_c_max = arc_c_min;
5984 arc_c_max = MAX(arc_c * 5, arc_c_max);
5987 * In userland, there's only the memory pressure that we artificially
5988 * create (see arc_available_memory()). Don't let arc_c get too
5989 * small, because it can cause transactions to be larger than
5990 * arc_c, causing arc_tempreserve_space() to fail.
5993 arc_c_min = arc_c_max / 2;
5998 * Allow the tunables to override our calculations if they are
6001 if (zfs_arc_max > arc_abs_min && zfs_arc_max < kmem_size())
6002 arc_c_max = zfs_arc_max;
6003 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
6004 arc_c_min = zfs_arc_min;
6008 arc_p = (arc_c >> 1);
6011 /* limit meta-data to 1/4 of the arc capacity */
6012 arc_meta_limit = arc_c_max / 4;
6014 /* Allow the tunable to override if it is reasonable */
6015 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6016 arc_meta_limit = zfs_arc_meta_limit;
6018 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6019 arc_c_min = arc_meta_limit / 2;
6021 if (zfs_arc_meta_min > 0) {
6022 arc_meta_min = zfs_arc_meta_min;
6024 arc_meta_min = arc_c_min / 2;
6027 if (zfs_arc_grow_retry > 0)
6028 arc_grow_retry = zfs_arc_grow_retry;
6030 if (zfs_arc_shrink_shift > 0)
6031 arc_shrink_shift = zfs_arc_shrink_shift;
6034 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6036 if (arc_no_grow_shift >= arc_shrink_shift)
6037 arc_no_grow_shift = arc_shrink_shift - 1;
6039 if (zfs_arc_p_min_shift > 0)
6040 arc_p_min_shift = zfs_arc_p_min_shift;
6042 if (zfs_arc_num_sublists_per_state < 1)
6043 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
6045 /* if kmem_flags are set, lets try to use less memory */
6046 if (kmem_debugging())
6048 if (arc_c < arc_c_min)
6051 zfs_arc_min = arc_c_min;
6052 zfs_arc_max = arc_c_max;
6057 arc_reclaim_thread_exit = B_FALSE;
6059 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6060 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6062 if (arc_ksp != NULL) {
6063 arc_ksp->ks_data = &arc_stats;
6064 arc_ksp->ks_update = arc_kstat_update;
6065 kstat_install(arc_ksp);
6068 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
6069 TS_RUN, minclsyspri);
6072 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
6073 EVENTHANDLER_PRI_FIRST);
6080 * Calculate maximum amount of dirty data per pool.
6082 * If it has been set by /etc/system, take that.
6083 * Otherwise, use a percentage of physical memory defined by
6084 * zfs_dirty_data_max_percent (default 10%) with a cap at
6085 * zfs_dirty_data_max_max (default 4GB).
6087 if (zfs_dirty_data_max == 0) {
6088 zfs_dirty_data_max = ptob(physmem) *
6089 zfs_dirty_data_max_percent / 100;
6090 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6091 zfs_dirty_data_max_max);
6095 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
6096 prefetch_tunable_set = 1;
6099 if (prefetch_tunable_set == 0) {
6100 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
6102 printf(" add \"vfs.zfs.prefetch_disable=0\" "
6103 "to /boot/loader.conf.\n");
6104 zfs_prefetch_disable = 1;
6107 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
6108 prefetch_tunable_set == 0) {
6109 printf("ZFS NOTICE: Prefetch is disabled by default if less "
6110 "than 4GB of RAM is present;\n"
6111 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
6112 "to /boot/loader.conf.\n");
6113 zfs_prefetch_disable = 1;
6116 /* Warn about ZFS memory and address space requirements. */
6117 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
6118 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
6119 "expect unstable behavior.\n");
6121 if (kmem_size() < 512 * (1 << 20)) {
6122 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
6123 "expect unstable behavior.\n");
6124 printf(" Consider tuning vm.kmem_size and "
6125 "vm.kmem_size_max\n");
6126 printf(" in /boot/loader.conf.\n");
6134 mutex_enter(&arc_reclaim_lock);
6135 arc_reclaim_thread_exit = B_TRUE;
6137 * The reclaim thread will set arc_reclaim_thread_exit back to
6138 * B_FALSE when it is finished exiting; we're waiting for that.
6140 while (arc_reclaim_thread_exit) {
6141 cv_signal(&arc_reclaim_thread_cv);
6142 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
6144 mutex_exit(&arc_reclaim_lock);
6146 /* Use B_TRUE to ensure *all* buffers are evicted */
6147 arc_flush(NULL, B_TRUE);
6151 if (arc_ksp != NULL) {
6152 kstat_delete(arc_ksp);
6156 mutex_destroy(&arc_reclaim_lock);
6157 cv_destroy(&arc_reclaim_thread_cv);
6158 cv_destroy(&arc_reclaim_waiters_cv);
6163 ASSERT0(arc_loaned_bytes);
6166 if (arc_event_lowmem != NULL)
6167 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
6174 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6175 * It uses dedicated storage devices to hold cached data, which are populated
6176 * using large infrequent writes. The main role of this cache is to boost
6177 * the performance of random read workloads. The intended L2ARC devices
6178 * include short-stroked disks, solid state disks, and other media with
6179 * substantially faster read latency than disk.
6181 * +-----------------------+
6183 * +-----------------------+
6186 * l2arc_feed_thread() arc_read()
6190 * +---------------+ |
6192 * +---------------+ |
6197 * +-------+ +-------+
6199 * | cache | | cache |
6200 * +-------+ +-------+
6201 * +=========+ .-----.
6202 * : L2ARC : |-_____-|
6203 * : devices : | Disks |
6204 * +=========+ `-_____-'
6206 * Read requests are satisfied from the following sources, in order:
6209 * 2) vdev cache of L2ARC devices
6211 * 4) vdev cache of disks
6214 * Some L2ARC device types exhibit extremely slow write performance.
6215 * To accommodate for this there are some significant differences between
6216 * the L2ARC and traditional cache design:
6218 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
6219 * the ARC behave as usual, freeing buffers and placing headers on ghost
6220 * lists. The ARC does not send buffers to the L2ARC during eviction as
6221 * this would add inflated write latencies for all ARC memory pressure.
6223 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6224 * It does this by periodically scanning buffers from the eviction-end of
6225 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6226 * not already there. It scans until a headroom of buffers is satisfied,
6227 * which itself is a buffer for ARC eviction. If a compressible buffer is
6228 * found during scanning and selected for writing to an L2ARC device, we
6229 * temporarily boost scanning headroom during the next scan cycle to make
6230 * sure we adapt to compression effects (which might significantly reduce
6231 * the data volume we write to L2ARC). The thread that does this is
6232 * l2arc_feed_thread(), illustrated below; example sizes are included to
6233 * provide a better sense of ratio than this diagram:
6236 * +---------------------+----------+
6237 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
6238 * +---------------------+----------+ | o L2ARC eligible
6239 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
6240 * +---------------------+----------+ |
6241 * 15.9 Gbytes ^ 32 Mbytes |
6243 * l2arc_feed_thread()
6245 * l2arc write hand <--[oooo]--'
6249 * +==============================+
6250 * L2ARC dev |####|#|###|###| |####| ... |
6251 * +==============================+
6254 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6255 * evicted, then the L2ARC has cached a buffer much sooner than it probably
6256 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
6257 * safe to say that this is an uncommon case, since buffers at the end of
6258 * the ARC lists have moved there due to inactivity.
6260 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6261 * then the L2ARC simply misses copying some buffers. This serves as a
6262 * pressure valve to prevent heavy read workloads from both stalling the ARC
6263 * with waits and clogging the L2ARC with writes. This also helps prevent
6264 * the potential for the L2ARC to churn if it attempts to cache content too
6265 * quickly, such as during backups of the entire pool.
6267 * 5. After system boot and before the ARC has filled main memory, there are
6268 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
6269 * lists can remain mostly static. Instead of searching from tail of these
6270 * lists as pictured, the l2arc_feed_thread() will search from the list heads
6271 * for eligible buffers, greatly increasing its chance of finding them.
6273 * The L2ARC device write speed is also boosted during this time so that
6274 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
6275 * there are no L2ARC reads, and no fear of degrading read performance
6276 * through increased writes.
6278 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6279 * the vdev queue can aggregate them into larger and fewer writes. Each
6280 * device is written to in a rotor fashion, sweeping writes through
6281 * available space then repeating.
6283 * 7. The L2ARC does not store dirty content. It never needs to flush
6284 * write buffers back to disk based storage.
6286 * 8. If an ARC buffer is written (and dirtied) which also exists in the
6287 * L2ARC, the now stale L2ARC buffer is immediately dropped.
6289 * The performance of the L2ARC can be tweaked by a number of tunables, which
6290 * may be necessary for different workloads:
6292 * l2arc_write_max max write bytes per interval
6293 * l2arc_write_boost extra write bytes during device warmup
6294 * l2arc_noprefetch skip caching prefetched buffers
6295 * l2arc_headroom number of max device writes to precache
6296 * l2arc_headroom_boost when we find compressed buffers during ARC
6297 * scanning, we multiply headroom by this
6298 * percentage factor for the next scan cycle,
6299 * since more compressed buffers are likely to
6301 * l2arc_feed_secs seconds between L2ARC writing
6303 * Tunables may be removed or added as future performance improvements are
6304 * integrated, and also may become zpool properties.
6306 * There are three key functions that control how the L2ARC warms up:
6308 * l2arc_write_eligible() check if a buffer is eligible to cache
6309 * l2arc_write_size() calculate how much to write
6310 * l2arc_write_interval() calculate sleep delay between writes
6312 * These three functions determine what to write, how much, and how quickly
6317 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
6320 * A buffer is *not* eligible for the L2ARC if it:
6321 * 1. belongs to a different spa.
6322 * 2. is already cached on the L2ARC.
6323 * 3. has an I/O in progress (it may be an incomplete read).
6324 * 4. is flagged not eligible (zfs property).
6326 if (hdr->b_spa != spa_guid) {
6327 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
6330 if (HDR_HAS_L2HDR(hdr)) {
6331 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
6334 if (HDR_IO_IN_PROGRESS(hdr)) {
6335 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
6338 if (!HDR_L2CACHE(hdr)) {
6339 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
6347 l2arc_write_size(void)
6352 * Make sure our globals have meaningful values in case the user
6355 size = l2arc_write_max;
6357 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6358 "be greater than zero, resetting it to the default (%d)",
6360 size = l2arc_write_max = L2ARC_WRITE_SIZE;
6363 if (arc_warm == B_FALSE)
6364 size += l2arc_write_boost;
6371 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
6373 clock_t interval, next, now;
6376 * If the ARC lists are busy, increase our write rate; if the
6377 * lists are stale, idle back. This is achieved by checking
6378 * how much we previously wrote - if it was more than half of
6379 * what we wanted, schedule the next write much sooner.
6381 if (l2arc_feed_again && wrote > (wanted / 2))
6382 interval = (hz * l2arc_feed_min_ms) / 1000;
6384 interval = hz * l2arc_feed_secs;
6386 now = ddi_get_lbolt();
6387 next = MAX(now, MIN(now + interval, began + interval));
6393 * Cycle through L2ARC devices. This is how L2ARC load balances.
6394 * If a device is returned, this also returns holding the spa config lock.
6396 static l2arc_dev_t *
6397 l2arc_dev_get_next(void)
6399 l2arc_dev_t *first, *next = NULL;
6402 * Lock out the removal of spas (spa_namespace_lock), then removal
6403 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
6404 * both locks will be dropped and a spa config lock held instead.
6406 mutex_enter(&spa_namespace_lock);
6407 mutex_enter(&l2arc_dev_mtx);
6409 /* if there are no vdevs, there is nothing to do */
6410 if (l2arc_ndev == 0)
6414 next = l2arc_dev_last;
6416 /* loop around the list looking for a non-faulted vdev */
6418 next = list_head(l2arc_dev_list);
6420 next = list_next(l2arc_dev_list, next);
6422 next = list_head(l2arc_dev_list);
6425 /* if we have come back to the start, bail out */
6428 else if (next == first)
6431 } while (vdev_is_dead(next->l2ad_vdev));
6433 /* if we were unable to find any usable vdevs, return NULL */
6434 if (vdev_is_dead(next->l2ad_vdev))
6437 l2arc_dev_last = next;
6440 mutex_exit(&l2arc_dev_mtx);
6443 * Grab the config lock to prevent the 'next' device from being
6444 * removed while we are writing to it.
6447 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
6448 mutex_exit(&spa_namespace_lock);
6454 * Free buffers that were tagged for destruction.
6457 l2arc_do_free_on_write()
6460 l2arc_data_free_t *df, *df_prev;
6462 mutex_enter(&l2arc_free_on_write_mtx);
6463 buflist = l2arc_free_on_write;
6465 for (df = list_tail(buflist); df; df = df_prev) {
6466 df_prev = list_prev(buflist, df);
6467 ASSERT3P(df->l2df_data, !=, NULL);
6468 if (df->l2df_type == ARC_BUFC_METADATA) {
6469 zio_buf_free(df->l2df_data, df->l2df_size);
6471 ASSERT(df->l2df_type == ARC_BUFC_DATA);
6472 zio_data_buf_free(df->l2df_data, df->l2df_size);
6474 list_remove(buflist, df);
6475 kmem_free(df, sizeof (l2arc_data_free_t));
6478 mutex_exit(&l2arc_free_on_write_mtx);
6482 * A write to a cache device has completed. Update all headers to allow
6483 * reads from these buffers to begin.
6486 l2arc_write_done(zio_t *zio)
6488 l2arc_write_callback_t *cb;
6491 arc_buf_hdr_t *head, *hdr, *hdr_prev;
6492 kmutex_t *hash_lock;
6493 int64_t bytes_dropped = 0;
6495 cb = zio->io_private;
6496 ASSERT3P(cb, !=, NULL);
6497 dev = cb->l2wcb_dev;
6498 ASSERT3P(dev, !=, NULL);
6499 head = cb->l2wcb_head;
6500 ASSERT3P(head, !=, NULL);
6501 buflist = &dev->l2ad_buflist;
6502 ASSERT3P(buflist, !=, NULL);
6503 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6504 l2arc_write_callback_t *, cb);
6506 if (zio->io_error != 0)
6507 ARCSTAT_BUMP(arcstat_l2_writes_error);
6510 * All writes completed, or an error was hit.
6513 mutex_enter(&dev->l2ad_mtx);
6514 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
6515 hdr_prev = list_prev(buflist, hdr);
6517 hash_lock = HDR_LOCK(hdr);
6520 * We cannot use mutex_enter or else we can deadlock
6521 * with l2arc_write_buffers (due to swapping the order
6522 * the hash lock and l2ad_mtx are taken).
6524 if (!mutex_tryenter(hash_lock)) {
6526 * Missed the hash lock. We must retry so we
6527 * don't leave the ARC_FLAG_L2_WRITING bit set.
6529 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6532 * We don't want to rescan the headers we've
6533 * already marked as having been written out, so
6534 * we reinsert the head node so we can pick up
6535 * where we left off.
6537 list_remove(buflist, head);
6538 list_insert_after(buflist, hdr, head);
6540 mutex_exit(&dev->l2ad_mtx);
6543 * We wait for the hash lock to become available
6544 * to try and prevent busy waiting, and increase
6545 * the chance we'll be able to acquire the lock
6546 * the next time around.
6548 mutex_enter(hash_lock);
6549 mutex_exit(hash_lock);
6554 * We could not have been moved into the arc_l2c_only
6555 * state while in-flight due to our ARC_FLAG_L2_WRITING
6556 * bit being set. Let's just ensure that's being enforced.
6558 ASSERT(HDR_HAS_L1HDR(hdr));
6560 if (zio->io_error != 0) {
6562 * Error - drop L2ARC entry.
6564 list_remove(buflist, hdr);
6566 arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
6568 ARCSTAT_INCR(arcstat_l2_asize, -arc_hdr_size(hdr));
6569 ARCSTAT_INCR(arcstat_l2_size, -HDR_GET_LSIZE(hdr));
6571 bytes_dropped += arc_hdr_size(hdr);
6572 (void) refcount_remove_many(&dev->l2ad_alloc,
6573 arc_hdr_size(hdr), hdr);
6577 * Allow ARC to begin reads and ghost list evictions to
6580 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6582 mutex_exit(hash_lock);
6585 atomic_inc_64(&l2arc_writes_done);
6586 list_remove(buflist, head);
6587 ASSERT(!HDR_HAS_L1HDR(head));
6588 kmem_cache_free(hdr_l2only_cache, head);
6589 mutex_exit(&dev->l2ad_mtx);
6591 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6593 l2arc_do_free_on_write();
6595 kmem_free(cb, sizeof (l2arc_write_callback_t));
6599 * A read to a cache device completed. Validate buffer contents before
6600 * handing over to the regular ARC routines.
6603 l2arc_read_done(zio_t *zio)
6605 l2arc_read_callback_t *cb;
6607 kmutex_t *hash_lock;
6608 boolean_t valid_cksum;
6610 ASSERT3P(zio->io_vd, !=, NULL);
6611 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6613 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6615 cb = zio->io_private;
6616 ASSERT3P(cb, !=, NULL);
6617 hdr = cb->l2rcb_hdr;
6618 ASSERT3P(hdr, !=, NULL);
6620 hash_lock = HDR_LOCK(hdr);
6621 mutex_enter(hash_lock);
6622 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6625 * If the data was read into a temporary buffer,
6626 * move it and free the buffer.
6628 if (cb->l2rcb_data != NULL) {
6629 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
6630 if (zio->io_error == 0) {
6631 bcopy(cb->l2rcb_data, hdr->b_l1hdr.b_pdata,
6636 * The following must be done regardless of whether
6637 * there was an error:
6638 * - free the temporary buffer
6639 * - point zio to the real ARC buffer
6640 * - set zio size accordingly
6641 * These are required because zio is either re-used for
6642 * an I/O of the block in the case of the error
6643 * or the zio is passed to arc_read_done() and it
6646 zio_data_buf_free(cb->l2rcb_data, zio->io_size);
6647 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
6648 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_pdata;
6651 ASSERT3P(zio->io_data, !=, NULL);
6654 * Check this survived the L2ARC journey.
6656 ASSERT3P(zio->io_data, ==, hdr->b_l1hdr.b_pdata);
6657 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6658 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6660 valid_cksum = arc_cksum_is_equal(hdr, zio);
6661 if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6662 mutex_exit(hash_lock);
6663 zio->io_private = hdr;
6666 mutex_exit(hash_lock);
6668 * Buffer didn't survive caching. Increment stats and
6669 * reissue to the original storage device.
6671 if (zio->io_error != 0) {
6672 ARCSTAT_BUMP(arcstat_l2_io_error);
6674 zio->io_error = SET_ERROR(EIO);
6677 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6680 * If there's no waiter, issue an async i/o to the primary
6681 * storage now. If there *is* a waiter, the caller must
6682 * issue the i/o in a context where it's OK to block.
6684 if (zio->io_waiter == NULL) {
6685 zio_t *pio = zio_unique_parent(zio);
6687 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6689 zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6690 hdr->b_l1hdr.b_pdata, zio->io_size, arc_read_done,
6691 hdr, zio->io_priority, cb->l2rcb_flags,
6696 kmem_free(cb, sizeof (l2arc_read_callback_t));
6700 * This is the list priority from which the L2ARC will search for pages to
6701 * cache. This is used within loops (0..3) to cycle through lists in the
6702 * desired order. This order can have a significant effect on cache
6705 * Currently the metadata lists are hit first, MFU then MRU, followed by
6706 * the data lists. This function returns a locked list, and also returns
6709 static multilist_sublist_t *
6710 l2arc_sublist_lock(int list_num)
6712 multilist_t *ml = NULL;
6715 ASSERT(list_num >= 0 && list_num <= 3);
6719 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6722 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6725 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6728 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6733 * Return a randomly-selected sublist. This is acceptable
6734 * because the caller feeds only a little bit of data for each
6735 * call (8MB). Subsequent calls will result in different
6736 * sublists being selected.
6738 idx = multilist_get_random_index(ml);
6739 return (multilist_sublist_lock(ml, idx));
6743 * Evict buffers from the device write hand to the distance specified in
6744 * bytes. This distance may span populated buffers, it may span nothing.
6745 * This is clearing a region on the L2ARC device ready for writing.
6746 * If the 'all' boolean is set, every buffer is evicted.
6749 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6752 arc_buf_hdr_t *hdr, *hdr_prev;
6753 kmutex_t *hash_lock;
6756 buflist = &dev->l2ad_buflist;
6758 if (!all && dev->l2ad_first) {
6760 * This is the first sweep through the device. There is
6766 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6768 * When nearing the end of the device, evict to the end
6769 * before the device write hand jumps to the start.
6771 taddr = dev->l2ad_end;
6773 taddr = dev->l2ad_hand + distance;
6775 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6776 uint64_t, taddr, boolean_t, all);
6779 mutex_enter(&dev->l2ad_mtx);
6780 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6781 hdr_prev = list_prev(buflist, hdr);
6783 hash_lock = HDR_LOCK(hdr);
6786 * We cannot use mutex_enter or else we can deadlock
6787 * with l2arc_write_buffers (due to swapping the order
6788 * the hash lock and l2ad_mtx are taken).
6790 if (!mutex_tryenter(hash_lock)) {
6792 * Missed the hash lock. Retry.
6794 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6795 mutex_exit(&dev->l2ad_mtx);
6796 mutex_enter(hash_lock);
6797 mutex_exit(hash_lock);
6801 if (HDR_L2_WRITE_HEAD(hdr)) {
6803 * We hit a write head node. Leave it for
6804 * l2arc_write_done().
6806 list_remove(buflist, hdr);
6807 mutex_exit(hash_lock);
6811 if (!all && HDR_HAS_L2HDR(hdr) &&
6812 (hdr->b_l2hdr.b_daddr > taddr ||
6813 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6815 * We've evicted to the target address,
6816 * or the end of the device.
6818 mutex_exit(hash_lock);
6822 ASSERT(HDR_HAS_L2HDR(hdr));
6823 if (!HDR_HAS_L1HDR(hdr)) {
6824 ASSERT(!HDR_L2_READING(hdr));
6826 * This doesn't exist in the ARC. Destroy.
6827 * arc_hdr_destroy() will call list_remove()
6828 * and decrement arcstat_l2_size.
6830 arc_change_state(arc_anon, hdr, hash_lock);
6831 arc_hdr_destroy(hdr);
6833 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6834 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6836 * Invalidate issued or about to be issued
6837 * reads, since we may be about to write
6838 * over this location.
6840 if (HDR_L2_READING(hdr)) {
6841 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6842 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
6845 /* Ensure this header has finished being written */
6846 ASSERT(!HDR_L2_WRITING(hdr));
6848 arc_hdr_l2hdr_destroy(hdr);
6850 mutex_exit(hash_lock);
6852 mutex_exit(&dev->l2ad_mtx);
6856 * Find and write ARC buffers to the L2ARC device.
6858 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6859 * for reading until they have completed writing.
6860 * The headroom_boost is an in-out parameter used to maintain headroom boost
6861 * state between calls to this function.
6863 * Returns the number of bytes actually written (which may be smaller than
6864 * the delta by which the device hand has changed due to alignment).
6867 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
6869 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6870 uint64_t write_asize, write_psize, write_sz, headroom;
6872 l2arc_write_callback_t *cb;
6874 uint64_t guid = spa_load_guid(spa);
6877 ASSERT3P(dev->l2ad_vdev, !=, NULL);
6880 write_sz = write_asize = write_psize = 0;
6882 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6883 arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
6885 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6887 * Copy buffers for L2ARC writing.
6889 for (try = 0; try <= 3; try++) {
6890 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6891 uint64_t passed_sz = 0;
6893 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6896 * L2ARC fast warmup.
6898 * Until the ARC is warm and starts to evict, read from the
6899 * head of the ARC lists rather than the tail.
6901 if (arc_warm == B_FALSE)
6902 hdr = multilist_sublist_head(mls);
6904 hdr = multilist_sublist_tail(mls);
6906 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6908 headroom = target_sz * l2arc_headroom;
6909 if (zfs_compressed_arc_enabled)
6910 headroom = (headroom * l2arc_headroom_boost) / 100;
6912 for (; hdr; hdr = hdr_prev) {
6913 kmutex_t *hash_lock;
6915 if (arc_warm == B_FALSE)
6916 hdr_prev = multilist_sublist_next(mls, hdr);
6918 hdr_prev = multilist_sublist_prev(mls, hdr);
6919 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
6920 HDR_GET_LSIZE(hdr));
6922 hash_lock = HDR_LOCK(hdr);
6923 if (!mutex_tryenter(hash_lock)) {
6924 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6926 * Skip this buffer rather than waiting.
6931 passed_sz += HDR_GET_LSIZE(hdr);
6932 if (passed_sz > headroom) {
6936 mutex_exit(hash_lock);
6937 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6941 if (!l2arc_write_eligible(guid, hdr)) {
6942 mutex_exit(hash_lock);
6946 if ((write_asize + HDR_GET_LSIZE(hdr)) > target_sz) {
6948 mutex_exit(hash_lock);
6949 ARCSTAT_BUMP(arcstat_l2_write_full);
6955 * Insert a dummy header on the buflist so
6956 * l2arc_write_done() can find where the
6957 * write buffers begin without searching.
6959 mutex_enter(&dev->l2ad_mtx);
6960 list_insert_head(&dev->l2ad_buflist, head);
6961 mutex_exit(&dev->l2ad_mtx);
6964 sizeof (l2arc_write_callback_t), KM_SLEEP);
6965 cb->l2wcb_dev = dev;
6966 cb->l2wcb_head = head;
6967 pio = zio_root(spa, l2arc_write_done, cb,
6969 ARCSTAT_BUMP(arcstat_l2_write_pios);
6972 hdr->b_l2hdr.b_dev = dev;
6973 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6974 arc_hdr_set_flags(hdr,
6975 ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
6977 mutex_enter(&dev->l2ad_mtx);
6978 list_insert_head(&dev->l2ad_buflist, hdr);
6979 mutex_exit(&dev->l2ad_mtx);
6982 * We rely on the L1 portion of the header below, so
6983 * it's invalid for this header to have been evicted out
6984 * of the ghost cache, prior to being written out. The
6985 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6987 ASSERT(HDR_HAS_L1HDR(hdr));
6989 ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
6990 ASSERT3P(hdr->b_l1hdr.b_pdata, !=, NULL);
6991 ASSERT3U(arc_hdr_size(hdr), >, 0);
6992 uint64_t size = arc_hdr_size(hdr);
6993 uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
6996 (void) refcount_add_many(&dev->l2ad_alloc, size, hdr);
6999 * Normally the L2ARC can use the hdr's data, but if
7000 * we're sharing data between the hdr and one of its
7001 * bufs, L2ARC needs its own copy of the data so that
7002 * the ZIO below can't race with the buf consumer. To
7003 * ensure that this copy will be available for the
7004 * lifetime of the ZIO and be cleaned up afterwards, we
7005 * add it to the l2arc_free_on_write queue.
7008 if (!HDR_SHARED_DATA(hdr) && size == asize) {
7009 to_write = hdr->b_l1hdr.b_pdata;
7011 arc_buf_contents_t type = arc_buf_type(hdr);
7012 if (type == ARC_BUFC_METADATA) {
7013 to_write = zio_buf_alloc(asize);
7015 ASSERT3U(type, ==, ARC_BUFC_DATA);
7016 to_write = zio_data_buf_alloc(asize);
7019 bcopy(hdr->b_l1hdr.b_pdata, to_write, size);
7021 bzero(to_write + size, asize - size);
7022 l2arc_free_data_on_write(to_write, asize, type);
7024 wzio = zio_write_phys(pio, dev->l2ad_vdev,
7025 hdr->b_l2hdr.b_daddr, asize, to_write,
7026 ZIO_CHECKSUM_OFF, NULL, hdr,
7027 ZIO_PRIORITY_ASYNC_WRITE,
7028 ZIO_FLAG_CANFAIL, B_FALSE);
7030 write_sz += HDR_GET_LSIZE(hdr);
7031 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7034 write_asize += size;
7035 write_psize += asize;
7036 dev->l2ad_hand += asize;
7038 mutex_exit(hash_lock);
7040 (void) zio_nowait(wzio);
7043 multilist_sublist_unlock(mls);
7049 /* No buffers selected for writing? */
7052 ASSERT(!HDR_HAS_L1HDR(head));
7053 kmem_cache_free(hdr_l2only_cache, head);
7057 ASSERT3U(write_asize, <=, target_sz);
7058 ARCSTAT_BUMP(arcstat_l2_writes_sent);
7059 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
7060 ARCSTAT_INCR(arcstat_l2_size, write_sz);
7061 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
7062 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
7065 * Bump device hand to the device start if it is approaching the end.
7066 * l2arc_evict() will already have evicted ahead for this case.
7068 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7069 dev->l2ad_hand = dev->l2ad_start;
7070 dev->l2ad_first = B_FALSE;
7073 dev->l2ad_writing = B_TRUE;
7074 (void) zio_wait(pio);
7075 dev->l2ad_writing = B_FALSE;
7077 return (write_asize);
7081 * This thread feeds the L2ARC at regular intervals. This is the beating
7082 * heart of the L2ARC.
7085 l2arc_feed_thread(void *dummy __unused)
7090 uint64_t size, wrote;
7091 clock_t begin, next = ddi_get_lbolt();
7093 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7095 mutex_enter(&l2arc_feed_thr_lock);
7097 while (l2arc_thread_exit == 0) {
7098 CALLB_CPR_SAFE_BEGIN(&cpr);
7099 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7100 next - ddi_get_lbolt());
7101 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7102 next = ddi_get_lbolt() + hz;
7105 * Quick check for L2ARC devices.
7107 mutex_enter(&l2arc_dev_mtx);
7108 if (l2arc_ndev == 0) {
7109 mutex_exit(&l2arc_dev_mtx);
7112 mutex_exit(&l2arc_dev_mtx);
7113 begin = ddi_get_lbolt();
7116 * This selects the next l2arc device to write to, and in
7117 * doing so the next spa to feed from: dev->l2ad_spa. This
7118 * will return NULL if there are now no l2arc devices or if
7119 * they are all faulted.
7121 * If a device is returned, its spa's config lock is also
7122 * held to prevent device removal. l2arc_dev_get_next()
7123 * will grab and release l2arc_dev_mtx.
7125 if ((dev = l2arc_dev_get_next()) == NULL)
7128 spa = dev->l2ad_spa;
7129 ASSERT3P(spa, !=, NULL);
7132 * If the pool is read-only then force the feed thread to
7133 * sleep a little longer.
7135 if (!spa_writeable(spa)) {
7136 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7137 spa_config_exit(spa, SCL_L2ARC, dev);
7142 * Avoid contributing to memory pressure.
7144 if (arc_reclaim_needed()) {
7145 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7146 spa_config_exit(spa, SCL_L2ARC, dev);
7150 ARCSTAT_BUMP(arcstat_l2_feeds);
7152 size = l2arc_write_size();
7155 * Evict L2ARC buffers that will be overwritten.
7157 l2arc_evict(dev, size, B_FALSE);
7160 * Write ARC buffers.
7162 wrote = l2arc_write_buffers(spa, dev, size);
7165 * Calculate interval between writes.
7167 next = l2arc_write_interval(begin, size, wrote);
7168 spa_config_exit(spa, SCL_L2ARC, dev);
7171 l2arc_thread_exit = 0;
7172 cv_broadcast(&l2arc_feed_thr_cv);
7173 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
7178 l2arc_vdev_present(vdev_t *vd)
7182 mutex_enter(&l2arc_dev_mtx);
7183 for (dev = list_head(l2arc_dev_list); dev != NULL;
7184 dev = list_next(l2arc_dev_list, dev)) {
7185 if (dev->l2ad_vdev == vd)
7188 mutex_exit(&l2arc_dev_mtx);
7190 return (dev != NULL);
7194 * Add a vdev for use by the L2ARC. By this point the spa has already
7195 * validated the vdev and opened it.
7198 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7200 l2arc_dev_t *adddev;
7202 ASSERT(!l2arc_vdev_present(vd));
7204 vdev_ashift_optimize(vd);
7207 * Create a new l2arc device entry.
7209 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7210 adddev->l2ad_spa = spa;
7211 adddev->l2ad_vdev = vd;
7212 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7213 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7214 adddev->l2ad_hand = adddev->l2ad_start;
7215 adddev->l2ad_first = B_TRUE;
7216 adddev->l2ad_writing = B_FALSE;
7218 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7220 * This is a list of all ARC buffers that are still valid on the
7223 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7224 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7226 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7227 refcount_create(&adddev->l2ad_alloc);
7230 * Add device to global list
7232 mutex_enter(&l2arc_dev_mtx);
7233 list_insert_head(l2arc_dev_list, adddev);
7234 atomic_inc_64(&l2arc_ndev);
7235 mutex_exit(&l2arc_dev_mtx);
7239 * Remove a vdev from the L2ARC.
7242 l2arc_remove_vdev(vdev_t *vd)
7244 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7247 * Find the device by vdev
7249 mutex_enter(&l2arc_dev_mtx);
7250 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7251 nextdev = list_next(l2arc_dev_list, dev);
7252 if (vd == dev->l2ad_vdev) {
7257 ASSERT3P(remdev, !=, NULL);
7260 * Remove device from global list
7262 list_remove(l2arc_dev_list, remdev);
7263 l2arc_dev_last = NULL; /* may have been invalidated */
7264 atomic_dec_64(&l2arc_ndev);
7265 mutex_exit(&l2arc_dev_mtx);
7268 * Clear all buflists and ARC references. L2ARC device flush.
7270 l2arc_evict(remdev, 0, B_TRUE);
7271 list_destroy(&remdev->l2ad_buflist);
7272 mutex_destroy(&remdev->l2ad_mtx);
7273 refcount_destroy(&remdev->l2ad_alloc);
7274 kmem_free(remdev, sizeof (l2arc_dev_t));
7280 l2arc_thread_exit = 0;
7282 l2arc_writes_sent = 0;
7283 l2arc_writes_done = 0;
7285 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7286 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7287 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7288 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7290 l2arc_dev_list = &L2ARC_dev_list;
7291 l2arc_free_on_write = &L2ARC_free_on_write;
7292 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7293 offsetof(l2arc_dev_t, l2ad_node));
7294 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7295 offsetof(l2arc_data_free_t, l2df_list_node));
7302 * This is called from dmu_fini(), which is called from spa_fini();
7303 * Because of this, we can assume that all l2arc devices have
7304 * already been removed when the pools themselves were removed.
7307 l2arc_do_free_on_write();
7309 mutex_destroy(&l2arc_feed_thr_lock);
7310 cv_destroy(&l2arc_feed_thr_cv);
7311 mutex_destroy(&l2arc_dev_mtx);
7312 mutex_destroy(&l2arc_free_on_write_mtx);
7314 list_destroy(l2arc_dev_list);
7315 list_destroy(l2arc_free_on_write);
7321 if (!(spa_mode_global & FWRITE))
7324 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7325 TS_RUN, minclsyspri);
7331 if (!(spa_mode_global & FWRITE))
7334 mutex_enter(&l2arc_feed_thr_lock);
7335 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7336 l2arc_thread_exit = 1;
7337 while (l2arc_thread_exit != 0)
7338 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7339 mutex_exit(&l2arc_feed_thr_lock);