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
125 #include <sys/zio_compress.h>
126 #include <sys/zfs_context.h>
128 #include <sys/refcount.h>
129 #include <sys/vdev.h>
130 #include <sys/vdev_impl.h>
131 #include <sys/dsl_pool.h>
132 #include <sys/multilist.h>
134 #include <sys/dnlc.h>
136 #include <sys/callb.h>
137 #include <sys/kstat.h>
138 #include <sys/trim_map.h>
139 #include <zfs_fletcher.h>
142 #include <machine/vmparam.h>
146 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
147 boolean_t arc_watch = B_FALSE;
152 static kmutex_t arc_reclaim_lock;
153 static kcondvar_t arc_reclaim_thread_cv;
154 static boolean_t arc_reclaim_thread_exit;
155 static kcondvar_t arc_reclaim_waiters_cv;
157 static kmutex_t arc_user_evicts_lock;
158 static kcondvar_t arc_user_evicts_cv;
159 static boolean_t arc_user_evicts_thread_exit;
161 uint_t arc_reduce_dnlc_percent = 3;
164 * The number of headers to evict in arc_evict_state_impl() before
165 * dropping the sublist lock and evicting from another sublist. A lower
166 * value means we're more likely to evict the "correct" header (i.e. the
167 * oldest header in the arc state), but comes with higher overhead
168 * (i.e. more invocations of arc_evict_state_impl()).
170 int zfs_arc_evict_batch_limit = 10;
173 * The number of sublists used for each of the arc state lists. If this
174 * is not set to a suitable value by the user, it will be configured to
175 * the number of CPUs on the system in arc_init().
177 int zfs_arc_num_sublists_per_state = 0;
179 /* number of seconds before growing cache again */
180 static int arc_grow_retry = 60;
182 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
183 int zfs_arc_overflow_shift = 8;
185 /* shift of arc_c for calculating both min and max arc_p */
186 static int arc_p_min_shift = 4;
188 /* log2(fraction of arc to reclaim) */
189 static int arc_shrink_shift = 7;
192 * log2(fraction of ARC which must be free to allow growing).
193 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
194 * when reading a new block into the ARC, we will evict an equal-sized block
197 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
198 * we will still not allow it to grow.
200 int arc_no_grow_shift = 5;
204 * minimum lifespan of a prefetch block in clock ticks
205 * (initialized in arc_init())
207 static int arc_min_prefetch_lifespan;
210 * If this percent of memory is free, don't throttle.
212 int arc_lotsfree_percent = 10;
215 extern boolean_t zfs_prefetch_disable;
218 * The arc has filled available memory and has now warmed up.
220 static boolean_t arc_warm;
223 * These tunables are for performance analysis.
225 uint64_t zfs_arc_max;
226 uint64_t zfs_arc_min;
227 uint64_t zfs_arc_meta_limit = 0;
228 uint64_t zfs_arc_meta_min = 0;
229 int zfs_arc_grow_retry = 0;
230 int zfs_arc_shrink_shift = 0;
231 int zfs_arc_p_min_shift = 0;
232 int zfs_disable_dup_eviction = 0;
233 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
234 u_int zfs_arc_free_target = 0;
236 /* Absolute min for arc min / max is 16MB. */
237 static uint64_t arc_abs_min = 16 << 20;
239 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
240 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
241 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
242 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
244 #if defined(__FreeBSD__) && defined(_KERNEL)
246 arc_free_target_init(void *unused __unused)
249 zfs_arc_free_target = vm_pageout_wakeup_thresh;
251 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
252 arc_free_target_init, NULL);
254 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
255 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
256 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
257 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
258 TUNABLE_QUAD("vfs.zfs.arc_average_blocksize", &zfs_arc_average_blocksize);
259 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
260 SYSCTL_DECL(_vfs_zfs);
261 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
262 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
263 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
264 0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
265 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
266 &zfs_arc_average_blocksize, 0,
267 "ARC average blocksize");
268 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
269 &arc_shrink_shift, 0,
270 "log2(fraction of arc to reclaim)");
273 * We don't have a tunable for arc_free_target due to the dependency on
274 * pagedaemon initialisation.
276 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
277 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
278 sysctl_vfs_zfs_arc_free_target, "IU",
279 "Desired number of free pages below which ARC triggers reclaim");
282 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
287 val = zfs_arc_free_target;
288 err = sysctl_handle_int(oidp, &val, 0, req);
289 if (err != 0 || req->newptr == NULL)
294 if (val > cnt.v_page_count)
297 zfs_arc_free_target = val;
303 * Must be declared here, before the definition of corresponding kstat
304 * macro which uses the same names will confuse the compiler.
306 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
307 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
308 sysctl_vfs_zfs_arc_meta_limit, "QU",
309 "ARC metadata limit");
313 * Note that buffers can be in one of 6 states:
314 * ARC_anon - anonymous (discussed below)
315 * ARC_mru - recently used, currently cached
316 * ARC_mru_ghost - recentely used, no longer in cache
317 * ARC_mfu - frequently used, currently cached
318 * ARC_mfu_ghost - frequently used, no longer in cache
319 * ARC_l2c_only - exists in L2ARC but not other states
320 * When there are no active references to the buffer, they are
321 * are linked onto a list in one of these arc states. These are
322 * the only buffers that can be evicted or deleted. Within each
323 * state there are multiple lists, one for meta-data and one for
324 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
325 * etc.) is tracked separately so that it can be managed more
326 * explicitly: favored over data, limited explicitly.
328 * Anonymous buffers are buffers that are not associated with
329 * a DVA. These are buffers that hold dirty block copies
330 * before they are written to stable storage. By definition,
331 * they are "ref'd" and are considered part of arc_mru
332 * that cannot be freed. Generally, they will aquire a DVA
333 * as they are written and migrate onto the arc_mru list.
335 * The ARC_l2c_only state is for buffers that are in the second
336 * level ARC but no longer in any of the ARC_m* lists. The second
337 * level ARC itself may also contain buffers that are in any of
338 * the ARC_m* states - meaning that a buffer can exist in two
339 * places. The reason for the ARC_l2c_only state is to keep the
340 * buffer header in the hash table, so that reads that hit the
341 * second level ARC benefit from these fast lookups.
344 typedef struct arc_state {
346 * list of evictable buffers
348 multilist_t arcs_list[ARC_BUFC_NUMTYPES];
350 * total amount of evictable data in this state
352 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];
354 * total amount of data in this state; this includes: evictable,
355 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
357 refcount_t arcs_size;
361 static arc_state_t ARC_anon;
362 static arc_state_t ARC_mru;
363 static arc_state_t ARC_mru_ghost;
364 static arc_state_t ARC_mfu;
365 static arc_state_t ARC_mfu_ghost;
366 static arc_state_t ARC_l2c_only;
368 typedef struct arc_stats {
369 kstat_named_t arcstat_hits;
370 kstat_named_t arcstat_misses;
371 kstat_named_t arcstat_demand_data_hits;
372 kstat_named_t arcstat_demand_data_misses;
373 kstat_named_t arcstat_demand_metadata_hits;
374 kstat_named_t arcstat_demand_metadata_misses;
375 kstat_named_t arcstat_prefetch_data_hits;
376 kstat_named_t arcstat_prefetch_data_misses;
377 kstat_named_t arcstat_prefetch_metadata_hits;
378 kstat_named_t arcstat_prefetch_metadata_misses;
379 kstat_named_t arcstat_mru_hits;
380 kstat_named_t arcstat_mru_ghost_hits;
381 kstat_named_t arcstat_mfu_hits;
382 kstat_named_t arcstat_mfu_ghost_hits;
383 kstat_named_t arcstat_allocated;
384 kstat_named_t arcstat_deleted;
386 * Number of buffers that could not be evicted because the hash lock
387 * was held by another thread. The lock may not necessarily be held
388 * by something using the same buffer, since hash locks are shared
389 * by multiple buffers.
391 kstat_named_t arcstat_mutex_miss;
393 * Number of buffers skipped because they have I/O in progress, are
394 * indrect prefetch buffers that have not lived long enough, or are
395 * not from the spa we're trying to evict from.
397 kstat_named_t arcstat_evict_skip;
399 * Number of times arc_evict_state() was unable to evict enough
400 * buffers to reach it's target amount.
402 kstat_named_t arcstat_evict_not_enough;
403 kstat_named_t arcstat_evict_l2_cached;
404 kstat_named_t arcstat_evict_l2_eligible;
405 kstat_named_t arcstat_evict_l2_ineligible;
406 kstat_named_t arcstat_evict_l2_skip;
407 kstat_named_t arcstat_hash_elements;
408 kstat_named_t arcstat_hash_elements_max;
409 kstat_named_t arcstat_hash_collisions;
410 kstat_named_t arcstat_hash_chains;
411 kstat_named_t arcstat_hash_chain_max;
412 kstat_named_t arcstat_p;
413 kstat_named_t arcstat_c;
414 kstat_named_t arcstat_c_min;
415 kstat_named_t arcstat_c_max;
416 kstat_named_t arcstat_size;
418 * Number of bytes consumed by internal ARC structures necessary
419 * for tracking purposes; these structures are not actually
420 * backed by ARC buffers. This includes arc_buf_hdr_t structures
421 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
422 * caches), and arc_buf_t structures (allocated via arc_buf_t
425 kstat_named_t arcstat_hdr_size;
427 * Number of bytes consumed by ARC buffers of type equal to
428 * ARC_BUFC_DATA. This is generally consumed by buffers backing
429 * on disk user data (e.g. plain file contents).
431 kstat_named_t arcstat_data_size;
433 * Number of bytes consumed by ARC buffers of type equal to
434 * ARC_BUFC_METADATA. This is generally consumed by buffers
435 * backing on disk data that is used for internal ZFS
436 * structures (e.g. ZAP, dnode, indirect blocks, etc).
438 kstat_named_t arcstat_metadata_size;
440 * Number of bytes consumed by various buffers and structures
441 * not actually backed with ARC buffers. This includes bonus
442 * buffers (allocated directly via zio_buf_* functions),
443 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
444 * cache), and dnode_t structures (allocated via dnode_t cache).
446 kstat_named_t arcstat_other_size;
448 * Total number of bytes consumed by ARC buffers residing in the
449 * arc_anon state. This includes *all* buffers in the arc_anon
450 * state; e.g. data, metadata, evictable, and unevictable buffers
451 * are all included in this value.
453 kstat_named_t arcstat_anon_size;
455 * Number of bytes consumed by ARC buffers that meet the
456 * following criteria: backing buffers of type ARC_BUFC_DATA,
457 * residing in the arc_anon state, and are eligible for eviction
458 * (e.g. have no outstanding holds on the buffer).
460 kstat_named_t arcstat_anon_evictable_data;
462 * Number of bytes consumed by ARC buffers that meet the
463 * following criteria: backing buffers of type ARC_BUFC_METADATA,
464 * residing in the arc_anon state, and are eligible for eviction
465 * (e.g. have no outstanding holds on the buffer).
467 kstat_named_t arcstat_anon_evictable_metadata;
469 * Total number of bytes consumed by ARC buffers residing in the
470 * arc_mru state. This includes *all* buffers in the arc_mru
471 * state; e.g. data, metadata, evictable, and unevictable buffers
472 * are all included in this value.
474 kstat_named_t arcstat_mru_size;
476 * Number of bytes consumed by ARC buffers that meet the
477 * following criteria: backing buffers of type ARC_BUFC_DATA,
478 * residing in the arc_mru state, and are eligible for eviction
479 * (e.g. have no outstanding holds on the buffer).
481 kstat_named_t arcstat_mru_evictable_data;
483 * Number of bytes consumed by ARC buffers that meet the
484 * following criteria: backing buffers of type ARC_BUFC_METADATA,
485 * residing in the arc_mru state, and are eligible for eviction
486 * (e.g. have no outstanding holds on the buffer).
488 kstat_named_t arcstat_mru_evictable_metadata;
490 * Total number of bytes that *would have been* consumed by ARC
491 * buffers in the arc_mru_ghost state. The key thing to note
492 * here, is the fact that this size doesn't actually indicate
493 * RAM consumption. The ghost lists only consist of headers and
494 * don't actually have ARC buffers linked off of these headers.
495 * Thus, *if* the headers had associated ARC buffers, these
496 * buffers *would have* consumed this number of bytes.
498 kstat_named_t arcstat_mru_ghost_size;
500 * Number of bytes that *would have been* consumed by ARC
501 * buffers that are eligible for eviction, of type
502 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
504 kstat_named_t arcstat_mru_ghost_evictable_data;
506 * Number of bytes that *would have been* consumed by ARC
507 * buffers that are eligible for eviction, of type
508 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
510 kstat_named_t arcstat_mru_ghost_evictable_metadata;
512 * Total number of bytes consumed by ARC buffers residing in the
513 * arc_mfu state. This includes *all* buffers in the arc_mfu
514 * state; e.g. data, metadata, evictable, and unevictable buffers
515 * are all included in this value.
517 kstat_named_t arcstat_mfu_size;
519 * Number of bytes consumed by ARC buffers that are eligible for
520 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
523 kstat_named_t arcstat_mfu_evictable_data;
525 * Number of bytes consumed by ARC buffers that are eligible for
526 * eviction, of type ARC_BUFC_METADATA, and reside in the
529 kstat_named_t arcstat_mfu_evictable_metadata;
531 * Total number of bytes that *would have been* consumed by ARC
532 * buffers in the arc_mfu_ghost state. See the comment above
533 * arcstat_mru_ghost_size for more details.
535 kstat_named_t arcstat_mfu_ghost_size;
537 * Number of bytes that *would have been* consumed by ARC
538 * buffers that are eligible for eviction, of type
539 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
541 kstat_named_t arcstat_mfu_ghost_evictable_data;
543 * Number of bytes that *would have been* consumed by ARC
544 * buffers that are eligible for eviction, of type
545 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
547 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
548 kstat_named_t arcstat_l2_hits;
549 kstat_named_t arcstat_l2_misses;
550 kstat_named_t arcstat_l2_feeds;
551 kstat_named_t arcstat_l2_rw_clash;
552 kstat_named_t arcstat_l2_read_bytes;
553 kstat_named_t arcstat_l2_write_bytes;
554 kstat_named_t arcstat_l2_writes_sent;
555 kstat_named_t arcstat_l2_writes_done;
556 kstat_named_t arcstat_l2_writes_error;
557 kstat_named_t arcstat_l2_writes_lock_retry;
558 kstat_named_t arcstat_l2_evict_lock_retry;
559 kstat_named_t arcstat_l2_evict_reading;
560 kstat_named_t arcstat_l2_evict_l1cached;
561 kstat_named_t arcstat_l2_free_on_write;
562 kstat_named_t arcstat_l2_cdata_free_on_write;
563 kstat_named_t arcstat_l2_abort_lowmem;
564 kstat_named_t arcstat_l2_cksum_bad;
565 kstat_named_t arcstat_l2_io_error;
566 kstat_named_t arcstat_l2_size;
567 kstat_named_t arcstat_l2_asize;
568 kstat_named_t arcstat_l2_hdr_size;
569 kstat_named_t arcstat_l2_compress_successes;
570 kstat_named_t arcstat_l2_compress_zeros;
571 kstat_named_t arcstat_l2_compress_failures;
572 kstat_named_t arcstat_l2_padding_needed;
573 kstat_named_t arcstat_l2_write_trylock_fail;
574 kstat_named_t arcstat_l2_write_passed_headroom;
575 kstat_named_t arcstat_l2_write_spa_mismatch;
576 kstat_named_t arcstat_l2_write_in_l2;
577 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
578 kstat_named_t arcstat_l2_write_not_cacheable;
579 kstat_named_t arcstat_l2_write_full;
580 kstat_named_t arcstat_l2_write_buffer_iter;
581 kstat_named_t arcstat_l2_write_pios;
582 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
583 kstat_named_t arcstat_l2_write_buffer_list_iter;
584 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
585 kstat_named_t arcstat_memory_throttle_count;
586 kstat_named_t arcstat_duplicate_buffers;
587 kstat_named_t arcstat_duplicate_buffers_size;
588 kstat_named_t arcstat_duplicate_reads;
589 kstat_named_t arcstat_meta_used;
590 kstat_named_t arcstat_meta_limit;
591 kstat_named_t arcstat_meta_max;
592 kstat_named_t arcstat_meta_min;
593 kstat_named_t arcstat_sync_wait_for_async;
594 kstat_named_t arcstat_demand_hit_predictive_prefetch;
597 static arc_stats_t arc_stats = {
598 { "hits", KSTAT_DATA_UINT64 },
599 { "misses", KSTAT_DATA_UINT64 },
600 { "demand_data_hits", KSTAT_DATA_UINT64 },
601 { "demand_data_misses", KSTAT_DATA_UINT64 },
602 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
603 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
604 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
605 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
606 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
607 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
608 { "mru_hits", KSTAT_DATA_UINT64 },
609 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
610 { "mfu_hits", KSTAT_DATA_UINT64 },
611 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
612 { "allocated", KSTAT_DATA_UINT64 },
613 { "deleted", KSTAT_DATA_UINT64 },
614 { "mutex_miss", KSTAT_DATA_UINT64 },
615 { "evict_skip", KSTAT_DATA_UINT64 },
616 { "evict_not_enough", KSTAT_DATA_UINT64 },
617 { "evict_l2_cached", KSTAT_DATA_UINT64 },
618 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
619 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
620 { "evict_l2_skip", KSTAT_DATA_UINT64 },
621 { "hash_elements", KSTAT_DATA_UINT64 },
622 { "hash_elements_max", KSTAT_DATA_UINT64 },
623 { "hash_collisions", KSTAT_DATA_UINT64 },
624 { "hash_chains", KSTAT_DATA_UINT64 },
625 { "hash_chain_max", KSTAT_DATA_UINT64 },
626 { "p", KSTAT_DATA_UINT64 },
627 { "c", KSTAT_DATA_UINT64 },
628 { "c_min", KSTAT_DATA_UINT64 },
629 { "c_max", KSTAT_DATA_UINT64 },
630 { "size", KSTAT_DATA_UINT64 },
631 { "hdr_size", KSTAT_DATA_UINT64 },
632 { "data_size", KSTAT_DATA_UINT64 },
633 { "metadata_size", KSTAT_DATA_UINT64 },
634 { "other_size", KSTAT_DATA_UINT64 },
635 { "anon_size", KSTAT_DATA_UINT64 },
636 { "anon_evictable_data", KSTAT_DATA_UINT64 },
637 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
638 { "mru_size", KSTAT_DATA_UINT64 },
639 { "mru_evictable_data", KSTAT_DATA_UINT64 },
640 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
641 { "mru_ghost_size", KSTAT_DATA_UINT64 },
642 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
643 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
644 { "mfu_size", KSTAT_DATA_UINT64 },
645 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
646 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
647 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
648 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
649 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
650 { "l2_hits", KSTAT_DATA_UINT64 },
651 { "l2_misses", KSTAT_DATA_UINT64 },
652 { "l2_feeds", KSTAT_DATA_UINT64 },
653 { "l2_rw_clash", KSTAT_DATA_UINT64 },
654 { "l2_read_bytes", KSTAT_DATA_UINT64 },
655 { "l2_write_bytes", KSTAT_DATA_UINT64 },
656 { "l2_writes_sent", KSTAT_DATA_UINT64 },
657 { "l2_writes_done", KSTAT_DATA_UINT64 },
658 { "l2_writes_error", KSTAT_DATA_UINT64 },
659 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
660 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
661 { "l2_evict_reading", KSTAT_DATA_UINT64 },
662 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
663 { "l2_free_on_write", KSTAT_DATA_UINT64 },
664 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
665 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
666 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
667 { "l2_io_error", KSTAT_DATA_UINT64 },
668 { "l2_size", KSTAT_DATA_UINT64 },
669 { "l2_asize", KSTAT_DATA_UINT64 },
670 { "l2_hdr_size", KSTAT_DATA_UINT64 },
671 { "l2_compress_successes", KSTAT_DATA_UINT64 },
672 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
673 { "l2_compress_failures", KSTAT_DATA_UINT64 },
674 { "l2_padding_needed", KSTAT_DATA_UINT64 },
675 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
676 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
677 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
678 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
679 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
680 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
681 { "l2_write_full", KSTAT_DATA_UINT64 },
682 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
683 { "l2_write_pios", KSTAT_DATA_UINT64 },
684 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
685 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
686 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
687 { "memory_throttle_count", KSTAT_DATA_UINT64 },
688 { "duplicate_buffers", KSTAT_DATA_UINT64 },
689 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
690 { "duplicate_reads", KSTAT_DATA_UINT64 },
691 { "arc_meta_used", KSTAT_DATA_UINT64 },
692 { "arc_meta_limit", KSTAT_DATA_UINT64 },
693 { "arc_meta_max", KSTAT_DATA_UINT64 },
694 { "arc_meta_min", KSTAT_DATA_UINT64 },
695 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
696 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
699 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
701 #define ARCSTAT_INCR(stat, val) \
702 atomic_add_64(&arc_stats.stat.value.ui64, (val))
704 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
705 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
707 #define ARCSTAT_MAX(stat, val) { \
709 while ((val) > (m = arc_stats.stat.value.ui64) && \
710 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
714 #define ARCSTAT_MAXSTAT(stat) \
715 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
718 * We define a macro to allow ARC hits/misses to be easily broken down by
719 * two separate conditions, giving a total of four different subtypes for
720 * each of hits and misses (so eight statistics total).
722 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
725 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
727 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
731 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
733 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
738 static arc_state_t *arc_anon;
739 static arc_state_t *arc_mru;
740 static arc_state_t *arc_mru_ghost;
741 static arc_state_t *arc_mfu;
742 static arc_state_t *arc_mfu_ghost;
743 static arc_state_t *arc_l2c_only;
746 * There are several ARC variables that are critical to export as kstats --
747 * but we don't want to have to grovel around in the kstat whenever we wish to
748 * manipulate them. For these variables, we therefore define them to be in
749 * terms of the statistic variable. This assures that we are not introducing
750 * the possibility of inconsistency by having shadow copies of the variables,
751 * while still allowing the code to be readable.
753 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
754 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
755 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
756 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
757 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
758 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
759 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
760 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
761 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
763 #define L2ARC_IS_VALID_COMPRESS(_c_) \
764 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
766 static int arc_no_grow; /* Don't try to grow cache size */
767 static uint64_t arc_tempreserve;
768 static uint64_t arc_loaned_bytes;
770 typedef struct arc_callback arc_callback_t;
772 struct arc_callback {
774 arc_done_func_t *acb_done;
776 zio_t *acb_zio_dummy;
777 arc_callback_t *acb_next;
780 typedef struct arc_write_callback arc_write_callback_t;
782 struct arc_write_callback {
784 arc_done_func_t *awcb_ready;
785 arc_done_func_t *awcb_children_ready;
786 arc_done_func_t *awcb_physdone;
787 arc_done_func_t *awcb_done;
792 * ARC buffers are separated into multiple structs as a memory saving measure:
793 * - Common fields struct, always defined, and embedded within it:
794 * - L2-only fields, always allocated but undefined when not in L2ARC
795 * - L1-only fields, only allocated when in L1ARC
797 * Buffer in L1 Buffer only in L2
798 * +------------------------+ +------------------------+
799 * | arc_buf_hdr_t | | arc_buf_hdr_t |
803 * +------------------------+ +------------------------+
804 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
805 * | (undefined if L1-only) | | |
806 * +------------------------+ +------------------------+
807 * | l1arc_buf_hdr_t |
812 * +------------------------+
814 * Because it's possible for the L2ARC to become extremely large, we can wind
815 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
816 * is minimized by only allocating the fields necessary for an L1-cached buffer
817 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
818 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
819 * words in pointers. arc_hdr_realloc() is used to switch a header between
820 * these two allocation states.
822 typedef struct l1arc_buf_hdr {
823 kmutex_t b_freeze_lock;
826 * used for debugging wtih kmem_flags - by allocating and freeing
827 * b_thawed when the buffer is thawed, we get a record of the stack
828 * trace that thawed it.
835 /* for waiting on writes to complete */
838 /* protected by arc state mutex */
839 arc_state_t *b_state;
840 multilist_node_t b_arc_node;
842 /* updated atomically */
843 clock_t b_arc_access;
845 /* self protecting */
848 arc_callback_t *b_acb;
849 /* temporary buffer holder for in-flight compressed or padded data */
853 typedef struct l2arc_dev l2arc_dev_t;
855 typedef struct l2arc_buf_hdr {
856 /* protected by arc_buf_hdr mutex */
857 l2arc_dev_t *b_dev; /* L2ARC device */
858 uint64_t b_daddr; /* disk address, offset byte */
859 /* real alloc'd buffer size depending on b_compress applied */
863 list_node_t b_l2node;
867 /* protected by hash lock */
871 * Even though this checksum is only set/verified when a buffer is in
872 * the L1 cache, it needs to be in the set of common fields because it
873 * must be preserved from the time before a buffer is written out to
874 * L2ARC until after it is read back in.
876 zio_cksum_t *b_freeze_cksum;
878 arc_buf_hdr_t *b_hash_next;
885 /* L2ARC fields. Undefined when not in L2ARC. */
886 l2arc_buf_hdr_t b_l2hdr;
887 /* L1ARC fields. Undefined when in l2arc_only state */
888 l1arc_buf_hdr_t b_l1hdr;
891 #if defined(__FreeBSD__) && defined(_KERNEL)
893 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
898 val = arc_meta_limit;
899 err = sysctl_handle_64(oidp, &val, 0, req);
900 if (err != 0 || req->newptr == NULL)
903 if (val <= 0 || val > arc_c_max)
906 arc_meta_limit = val;
911 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
917 err = sysctl_handle_64(oidp, &val, 0, req);
918 if (err != 0 || req->newptr == NULL)
921 if (zfs_arc_max == 0) {
922 /* Loader tunable so blindly set */
927 if (val < arc_abs_min || val > kmem_size())
931 if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
937 arc_p = (arc_c >> 1);
939 if (zfs_arc_meta_limit == 0) {
940 /* limit meta-data to 1/4 of the arc capacity */
941 arc_meta_limit = arc_c_max / 4;
944 /* if kmem_flags are set, lets try to use less memory */
945 if (kmem_debugging())
954 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
960 err = sysctl_handle_64(oidp, &val, 0, req);
961 if (err != 0 || req->newptr == NULL)
964 if (zfs_arc_min == 0) {
965 /* Loader tunable so blindly set */
970 if (val < arc_abs_min || val > arc_c_max)
975 if (zfs_arc_meta_min == 0)
976 arc_meta_min = arc_c_min / 2;
978 if (arc_c < arc_c_min)
981 zfs_arc_min = arc_c_min;
987 static arc_buf_t *arc_eviction_list;
988 static arc_buf_hdr_t arc_eviction_hdr;
990 #define GHOST_STATE(state) \
991 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
992 (state) == arc_l2c_only)
994 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
995 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
996 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
997 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
998 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
999 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
1001 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1002 #define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
1003 #define HDR_L2_READING(hdr) \
1004 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
1005 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1006 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1007 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1008 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1010 #define HDR_ISTYPE_METADATA(hdr) \
1011 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1012 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
1014 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1015 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1021 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1022 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1025 * Hash table routines
1028 #define HT_LOCK_PAD CACHE_LINE_SIZE
1033 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1037 #define BUF_LOCKS 256
1038 typedef struct buf_hash_table {
1040 arc_buf_hdr_t **ht_table;
1041 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1044 static buf_hash_table_t buf_hash_table;
1046 #define BUF_HASH_INDEX(spa, dva, birth) \
1047 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1048 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1049 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1050 #define HDR_LOCK(hdr) \
1051 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1053 uint64_t zfs_crc64_table[256];
1059 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
1060 #define L2ARC_HEADROOM 2 /* num of writes */
1062 * If we discover during ARC scan any buffers to be compressed, we boost
1063 * our headroom for the next scanning cycle by this percentage multiple.
1065 #define L2ARC_HEADROOM_BOOST 200
1066 #define L2ARC_FEED_SECS 1 /* caching interval secs */
1067 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
1070 * Used to distinguish headers that are being process by
1071 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
1072 * address. This can happen when the header is added to the l2arc's list
1073 * of buffers to write in the first stage of l2arc_write_buffers(), but
1074 * has not yet been written out which happens in the second stage of
1075 * l2arc_write_buffers().
1077 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
1079 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
1080 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
1082 /* L2ARC Performance Tunables */
1083 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1084 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1085 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1086 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1087 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1088 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1089 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1090 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1091 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1093 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1094 &l2arc_write_max, 0, "max write size");
1095 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1096 &l2arc_write_boost, 0, "extra write during warmup");
1097 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1098 &l2arc_headroom, 0, "number of dev writes");
1099 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1100 &l2arc_feed_secs, 0, "interval seconds");
1101 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1102 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1104 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1105 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1106 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1107 &l2arc_feed_again, 0, "turbo warmup");
1108 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1109 &l2arc_norw, 0, "no reads during writes");
1111 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1112 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1113 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1114 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1115 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1116 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1118 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1119 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1120 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1121 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1122 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1123 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1125 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1126 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1127 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1128 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1129 "size of metadata in mru ghost state");
1130 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1131 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1132 "size of data in mru ghost state");
1134 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1135 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1136 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1137 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1138 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1139 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1141 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1142 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1143 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1144 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1145 "size of metadata in mfu ghost state");
1146 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1147 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1148 "size of data in mfu ghost state");
1150 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1151 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1157 vdev_t *l2ad_vdev; /* vdev */
1158 spa_t *l2ad_spa; /* spa */
1159 uint64_t l2ad_hand; /* next write location */
1160 uint64_t l2ad_start; /* first addr on device */
1161 uint64_t l2ad_end; /* last addr on device */
1162 boolean_t l2ad_first; /* first sweep through */
1163 boolean_t l2ad_writing; /* currently writing */
1164 kmutex_t l2ad_mtx; /* lock for buffer list */
1165 list_t l2ad_buflist; /* buffer list */
1166 list_node_t l2ad_node; /* device list node */
1167 refcount_t l2ad_alloc; /* allocated bytes */
1170 static list_t L2ARC_dev_list; /* device list */
1171 static list_t *l2arc_dev_list; /* device list pointer */
1172 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1173 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1174 static list_t L2ARC_free_on_write; /* free after write buf list */
1175 static list_t *l2arc_free_on_write; /* free after write list ptr */
1176 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1177 static uint64_t l2arc_ndev; /* number of devices */
1179 typedef struct l2arc_read_callback {
1180 arc_buf_t *l2rcb_buf; /* read buffer */
1181 spa_t *l2rcb_spa; /* spa */
1182 blkptr_t l2rcb_bp; /* original blkptr */
1183 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1184 int l2rcb_flags; /* original flags */
1185 enum zio_compress l2rcb_compress; /* applied compress */
1186 void *l2rcb_data; /* temporary buffer */
1187 } l2arc_read_callback_t;
1189 typedef struct l2arc_write_callback {
1190 l2arc_dev_t *l2wcb_dev; /* device info */
1191 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1192 } l2arc_write_callback_t;
1194 typedef struct l2arc_data_free {
1195 /* protected by l2arc_free_on_write_mtx */
1198 void (*l2df_func)(void *, size_t);
1199 list_node_t l2df_list_node;
1200 } l2arc_data_free_t;
1202 static kmutex_t l2arc_feed_thr_lock;
1203 static kcondvar_t l2arc_feed_thr_cv;
1204 static uint8_t l2arc_thread_exit;
1206 static void arc_get_data_buf(arc_buf_t *);
1207 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1208 static boolean_t arc_is_overflowing();
1209 static void arc_buf_watch(arc_buf_t *);
1211 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1212 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1214 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1215 static void l2arc_read_done(zio_t *);
1217 static boolean_t l2arc_transform_buf(arc_buf_hdr_t *, boolean_t);
1218 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1219 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1222 l2arc_trim(const arc_buf_hdr_t *hdr)
1224 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1226 ASSERT(HDR_HAS_L2HDR(hdr));
1227 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1229 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET)
1231 if (hdr->b_l2hdr.b_asize != 0) {
1232 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1233 hdr->b_l2hdr.b_asize, 0);
1235 ASSERT3U(hdr->b_l2hdr.b_compress, ==, ZIO_COMPRESS_EMPTY);
1240 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1242 uint8_t *vdva = (uint8_t *)dva;
1243 uint64_t crc = -1ULL;
1246 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1248 for (i = 0; i < sizeof (dva_t); i++)
1249 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1251 crc ^= (spa>>8) ^ birth;
1256 #define BUF_EMPTY(buf) \
1257 ((buf)->b_dva.dva_word[0] == 0 && \
1258 (buf)->b_dva.dva_word[1] == 0)
1260 #define BUF_EQUAL(spa, dva, birth, buf) \
1261 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1262 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1263 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1266 buf_discard_identity(arc_buf_hdr_t *hdr)
1268 hdr->b_dva.dva_word[0] = 0;
1269 hdr->b_dva.dva_word[1] = 0;
1273 static arc_buf_hdr_t *
1274 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1276 const dva_t *dva = BP_IDENTITY(bp);
1277 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1278 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1279 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1282 mutex_enter(hash_lock);
1283 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1284 hdr = hdr->b_hash_next) {
1285 if (BUF_EQUAL(spa, dva, birth, hdr)) {
1290 mutex_exit(hash_lock);
1296 * Insert an entry into the hash table. If there is already an element
1297 * equal to elem in the hash table, then the already existing element
1298 * will be returned and the new element will not be inserted.
1299 * Otherwise returns NULL.
1300 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1302 static arc_buf_hdr_t *
1303 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1305 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1306 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1307 arc_buf_hdr_t *fhdr;
1310 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1311 ASSERT(hdr->b_birth != 0);
1312 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1314 if (lockp != NULL) {
1316 mutex_enter(hash_lock);
1318 ASSERT(MUTEX_HELD(hash_lock));
1321 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1322 fhdr = fhdr->b_hash_next, i++) {
1323 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1327 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1328 buf_hash_table.ht_table[idx] = hdr;
1329 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1331 /* collect some hash table performance data */
1333 ARCSTAT_BUMP(arcstat_hash_collisions);
1335 ARCSTAT_BUMP(arcstat_hash_chains);
1337 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1340 ARCSTAT_BUMP(arcstat_hash_elements);
1341 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1347 buf_hash_remove(arc_buf_hdr_t *hdr)
1349 arc_buf_hdr_t *fhdr, **hdrp;
1350 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1352 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1353 ASSERT(HDR_IN_HASH_TABLE(hdr));
1355 hdrp = &buf_hash_table.ht_table[idx];
1356 while ((fhdr = *hdrp) != hdr) {
1357 ASSERT(fhdr != NULL);
1358 hdrp = &fhdr->b_hash_next;
1360 *hdrp = hdr->b_hash_next;
1361 hdr->b_hash_next = NULL;
1362 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1364 /* collect some hash table performance data */
1365 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1367 if (buf_hash_table.ht_table[idx] &&
1368 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1369 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1373 * Global data structures and functions for the buf kmem cache.
1375 static kmem_cache_t *hdr_full_cache;
1376 static kmem_cache_t *hdr_l2only_cache;
1377 static kmem_cache_t *buf_cache;
1384 kmem_free(buf_hash_table.ht_table,
1385 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1386 for (i = 0; i < BUF_LOCKS; i++)
1387 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1388 kmem_cache_destroy(hdr_full_cache);
1389 kmem_cache_destroy(hdr_l2only_cache);
1390 kmem_cache_destroy(buf_cache);
1394 * Constructor callback - called when the cache is empty
1395 * and a new buf is requested.
1399 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1401 arc_buf_hdr_t *hdr = vbuf;
1403 bzero(hdr, HDR_FULL_SIZE);
1404 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1405 refcount_create(&hdr->b_l1hdr.b_refcnt);
1406 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1407 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1408 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1415 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1417 arc_buf_hdr_t *hdr = vbuf;
1419 bzero(hdr, HDR_L2ONLY_SIZE);
1420 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1427 buf_cons(void *vbuf, void *unused, int kmflag)
1429 arc_buf_t *buf = vbuf;
1431 bzero(buf, sizeof (arc_buf_t));
1432 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1433 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1439 * Destructor callback - called when a cached buf is
1440 * no longer required.
1444 hdr_full_dest(void *vbuf, void *unused)
1446 arc_buf_hdr_t *hdr = vbuf;
1448 ASSERT(BUF_EMPTY(hdr));
1449 cv_destroy(&hdr->b_l1hdr.b_cv);
1450 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1451 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1452 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1453 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1458 hdr_l2only_dest(void *vbuf, void *unused)
1460 arc_buf_hdr_t *hdr = vbuf;
1462 ASSERT(BUF_EMPTY(hdr));
1463 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1468 buf_dest(void *vbuf, void *unused)
1470 arc_buf_t *buf = vbuf;
1472 mutex_destroy(&buf->b_evict_lock);
1473 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1477 * Reclaim callback -- invoked when memory is low.
1481 hdr_recl(void *unused)
1483 dprintf("hdr_recl called\n");
1485 * umem calls the reclaim func when we destroy the buf cache,
1486 * which is after we do arc_fini().
1489 cv_signal(&arc_reclaim_thread_cv);
1496 uint64_t hsize = 1ULL << 12;
1500 * The hash table is big enough to fill all of physical memory
1501 * with an average block size of zfs_arc_average_blocksize (default 8K).
1502 * By default, the table will take up
1503 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1505 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1508 buf_hash_table.ht_mask = hsize - 1;
1509 buf_hash_table.ht_table =
1510 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1511 if (buf_hash_table.ht_table == NULL) {
1512 ASSERT(hsize > (1ULL << 8));
1517 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1518 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1519 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1520 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1522 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1523 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1525 for (i = 0; i < 256; i++)
1526 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1527 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1529 for (i = 0; i < BUF_LOCKS; i++) {
1530 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1531 NULL, MUTEX_DEFAULT, NULL);
1536 * Transition between the two allocation states for the arc_buf_hdr struct.
1537 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1538 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1539 * version is used when a cache buffer is only in the L2ARC in order to reduce
1542 static arc_buf_hdr_t *
1543 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1545 ASSERT(HDR_HAS_L2HDR(hdr));
1547 arc_buf_hdr_t *nhdr;
1548 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1550 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1551 (old == hdr_l2only_cache && new == hdr_full_cache));
1553 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1555 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1556 buf_hash_remove(hdr);
1558 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1560 if (new == hdr_full_cache) {
1561 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1563 * arc_access and arc_change_state need to be aware that a
1564 * header has just come out of L2ARC, so we set its state to
1565 * l2c_only even though it's about to change.
1567 nhdr->b_l1hdr.b_state = arc_l2c_only;
1569 /* Verify previous threads set to NULL before freeing */
1570 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1572 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1573 ASSERT0(hdr->b_l1hdr.b_datacnt);
1576 * If we've reached here, We must have been called from
1577 * arc_evict_hdr(), as such we should have already been
1578 * removed from any ghost list we were previously on
1579 * (which protects us from racing with arc_evict_state),
1580 * thus no locking is needed during this check.
1582 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1585 * A buffer must not be moved into the arc_l2c_only
1586 * state if it's not finished being written out to the
1587 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1588 * might try to be accessed, even though it was removed.
1590 VERIFY(!HDR_L2_WRITING(hdr));
1591 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1594 if (hdr->b_l1hdr.b_thawed != NULL) {
1595 kmem_free(hdr->b_l1hdr.b_thawed, 1);
1596 hdr->b_l1hdr.b_thawed = NULL;
1600 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1603 * The header has been reallocated so we need to re-insert it into any
1606 (void) buf_hash_insert(nhdr, NULL);
1608 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1610 mutex_enter(&dev->l2ad_mtx);
1613 * We must place the realloc'ed header back into the list at
1614 * the same spot. Otherwise, if it's placed earlier in the list,
1615 * l2arc_write_buffers() could find it during the function's
1616 * write phase, and try to write it out to the l2arc.
1618 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1619 list_remove(&dev->l2ad_buflist, hdr);
1621 mutex_exit(&dev->l2ad_mtx);
1624 * Since we're using the pointer address as the tag when
1625 * incrementing and decrementing the l2ad_alloc refcount, we
1626 * must remove the old pointer (that we're about to destroy) and
1627 * add the new pointer to the refcount. Otherwise we'd remove
1628 * the wrong pointer address when calling arc_hdr_destroy() later.
1631 (void) refcount_remove_many(&dev->l2ad_alloc,
1632 hdr->b_l2hdr.b_asize, hdr);
1634 (void) refcount_add_many(&dev->l2ad_alloc,
1635 nhdr->b_l2hdr.b_asize, nhdr);
1637 buf_discard_identity(hdr);
1638 hdr->b_freeze_cksum = NULL;
1639 kmem_cache_free(old, hdr);
1645 #define ARC_MINTIME (hz>>4) /* 62 ms */
1648 arc_cksum_verify(arc_buf_t *buf)
1652 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1655 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1656 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1657 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1660 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1661 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1662 panic("buffer modified while frozen!");
1663 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1667 arc_cksum_equal(arc_buf_t *buf)
1672 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1673 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1674 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1675 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1681 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1683 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1686 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1687 if (buf->b_hdr->b_freeze_cksum != NULL) {
1688 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1691 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1692 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1693 NULL, buf->b_hdr->b_freeze_cksum);
1694 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1702 typedef struct procctl {
1710 arc_buf_unwatch(arc_buf_t *buf)
1717 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1718 ctl.prwatch.pr_size = 0;
1719 ctl.prwatch.pr_wflags = 0;
1720 result = write(arc_procfd, &ctl, sizeof (ctl));
1721 ASSERT3U(result, ==, sizeof (ctl));
1728 arc_buf_watch(arc_buf_t *buf)
1735 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1736 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1737 ctl.prwatch.pr_wflags = WA_WRITE;
1738 result = write(arc_procfd, &ctl, sizeof (ctl));
1739 ASSERT3U(result, ==, sizeof (ctl));
1743 #endif /* illumos */
1745 static arc_buf_contents_t
1746 arc_buf_type(arc_buf_hdr_t *hdr)
1748 if (HDR_ISTYPE_METADATA(hdr)) {
1749 return (ARC_BUFC_METADATA);
1751 return (ARC_BUFC_DATA);
1756 arc_bufc_to_flags(arc_buf_contents_t type)
1760 /* metadata field is 0 if buffer contains normal data */
1762 case ARC_BUFC_METADATA:
1763 return (ARC_FLAG_BUFC_METADATA);
1767 panic("undefined ARC buffer type!");
1768 return ((uint32_t)-1);
1772 arc_buf_thaw(arc_buf_t *buf)
1774 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1775 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1776 panic("modifying non-anon buffer!");
1777 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1778 panic("modifying buffer while i/o in progress!");
1779 arc_cksum_verify(buf);
1782 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1783 if (buf->b_hdr->b_freeze_cksum != NULL) {
1784 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1785 buf->b_hdr->b_freeze_cksum = NULL;
1789 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1790 if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1791 kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1792 buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1796 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1799 arc_buf_unwatch(buf);
1804 arc_buf_freeze(arc_buf_t *buf)
1806 kmutex_t *hash_lock;
1808 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1811 hash_lock = HDR_LOCK(buf->b_hdr);
1812 mutex_enter(hash_lock);
1814 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1815 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1816 arc_cksum_compute(buf, B_FALSE);
1817 mutex_exit(hash_lock);
1822 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1824 ASSERT(HDR_HAS_L1HDR(hdr));
1825 ASSERT(MUTEX_HELD(hash_lock));
1826 arc_state_t *state = hdr->b_l1hdr.b_state;
1828 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1829 (state != arc_anon)) {
1830 /* We don't use the L2-only state list. */
1831 if (state != arc_l2c_only) {
1832 arc_buf_contents_t type = arc_buf_type(hdr);
1833 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1834 multilist_t *list = &state->arcs_list[type];
1835 uint64_t *size = &state->arcs_lsize[type];
1837 multilist_remove(list, hdr);
1839 if (GHOST_STATE(state)) {
1840 ASSERT0(hdr->b_l1hdr.b_datacnt);
1841 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1842 delta = hdr->b_size;
1845 ASSERT3U(*size, >=, delta);
1846 atomic_add_64(size, -delta);
1848 /* remove the prefetch flag if we get a reference */
1849 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1854 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1857 arc_state_t *state = hdr->b_l1hdr.b_state;
1859 ASSERT(HDR_HAS_L1HDR(hdr));
1860 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1861 ASSERT(!GHOST_STATE(state));
1864 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1865 * check to prevent usage of the arc_l2c_only list.
1867 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1868 (state != arc_anon)) {
1869 arc_buf_contents_t type = arc_buf_type(hdr);
1870 multilist_t *list = &state->arcs_list[type];
1871 uint64_t *size = &state->arcs_lsize[type];
1873 multilist_insert(list, hdr);
1875 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1876 atomic_add_64(size, hdr->b_size *
1877 hdr->b_l1hdr.b_datacnt);
1883 * Move the supplied buffer to the indicated state. The hash lock
1884 * for the buffer must be held by the caller.
1887 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1888 kmutex_t *hash_lock)
1890 arc_state_t *old_state;
1893 uint64_t from_delta, to_delta;
1894 arc_buf_contents_t buftype = arc_buf_type(hdr);
1897 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1898 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1899 * L1 hdr doesn't always exist when we change state to arc_anon before
1900 * destroying a header, in which case reallocating to add the L1 hdr is
1903 if (HDR_HAS_L1HDR(hdr)) {
1904 old_state = hdr->b_l1hdr.b_state;
1905 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1906 datacnt = hdr->b_l1hdr.b_datacnt;
1908 old_state = arc_l2c_only;
1913 ASSERT(MUTEX_HELD(hash_lock));
1914 ASSERT3P(new_state, !=, old_state);
1915 ASSERT(refcnt == 0 || datacnt > 0);
1916 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1917 ASSERT(old_state != arc_anon || datacnt <= 1);
1919 from_delta = to_delta = datacnt * hdr->b_size;
1922 * If this buffer is evictable, transfer it from the
1923 * old state list to the new state list.
1926 if (old_state != arc_anon && old_state != arc_l2c_only) {
1927 uint64_t *size = &old_state->arcs_lsize[buftype];
1929 ASSERT(HDR_HAS_L1HDR(hdr));
1930 multilist_remove(&old_state->arcs_list[buftype], hdr);
1933 * If prefetching out of the ghost cache,
1934 * we will have a non-zero datacnt.
1936 if (GHOST_STATE(old_state) && datacnt == 0) {
1937 /* ghost elements have a ghost size */
1938 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1939 from_delta = hdr->b_size;
1941 ASSERT3U(*size, >=, from_delta);
1942 atomic_add_64(size, -from_delta);
1944 if (new_state != arc_anon && new_state != arc_l2c_only) {
1945 uint64_t *size = &new_state->arcs_lsize[buftype];
1948 * An L1 header always exists here, since if we're
1949 * moving to some L1-cached state (i.e. not l2c_only or
1950 * anonymous), we realloc the header to add an L1hdr
1953 ASSERT(HDR_HAS_L1HDR(hdr));
1954 multilist_insert(&new_state->arcs_list[buftype], hdr);
1956 /* ghost elements have a ghost size */
1957 if (GHOST_STATE(new_state)) {
1959 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1960 to_delta = hdr->b_size;
1962 atomic_add_64(size, to_delta);
1966 ASSERT(!BUF_EMPTY(hdr));
1967 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1968 buf_hash_remove(hdr);
1970 /* adjust state sizes (ignore arc_l2c_only) */
1972 if (to_delta && new_state != arc_l2c_only) {
1973 ASSERT(HDR_HAS_L1HDR(hdr));
1974 if (GHOST_STATE(new_state)) {
1978 * We moving a header to a ghost state, we first
1979 * remove all arc buffers. Thus, we'll have a
1980 * datacnt of zero, and no arc buffer to use for
1981 * the reference. As a result, we use the arc
1982 * header pointer for the reference.
1984 (void) refcount_add_many(&new_state->arcs_size,
1987 ASSERT3U(datacnt, !=, 0);
1990 * Each individual buffer holds a unique reference,
1991 * thus we must remove each of these references one
1994 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1995 buf = buf->b_next) {
1996 (void) refcount_add_many(&new_state->arcs_size,
2002 if (from_delta && old_state != arc_l2c_only) {
2003 ASSERT(HDR_HAS_L1HDR(hdr));
2004 if (GHOST_STATE(old_state)) {
2006 * When moving a header off of a ghost state,
2007 * there's the possibility for datacnt to be
2008 * non-zero. This is because we first add the
2009 * arc buffer to the header prior to changing
2010 * the header's state. Since we used the header
2011 * for the reference when putting the header on
2012 * the ghost state, we must balance that and use
2013 * the header when removing off the ghost state
2014 * (even though datacnt is non zero).
2017 IMPLY(datacnt == 0, new_state == arc_anon ||
2018 new_state == arc_l2c_only);
2020 (void) refcount_remove_many(&old_state->arcs_size,
2023 ASSERT3P(datacnt, !=, 0);
2026 * Each individual buffer holds a unique reference,
2027 * thus we must remove each of these references one
2030 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2031 buf = buf->b_next) {
2032 (void) refcount_remove_many(
2033 &old_state->arcs_size, hdr->b_size, buf);
2038 if (HDR_HAS_L1HDR(hdr))
2039 hdr->b_l1hdr.b_state = new_state;
2042 * L2 headers should never be on the L2 state list since they don't
2043 * have L1 headers allocated.
2045 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2046 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2050 arc_space_consume(uint64_t space, arc_space_type_t type)
2052 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2055 case ARC_SPACE_DATA:
2056 ARCSTAT_INCR(arcstat_data_size, space);
2058 case ARC_SPACE_META:
2059 ARCSTAT_INCR(arcstat_metadata_size, space);
2061 case ARC_SPACE_OTHER:
2062 ARCSTAT_INCR(arcstat_other_size, space);
2064 case ARC_SPACE_HDRS:
2065 ARCSTAT_INCR(arcstat_hdr_size, space);
2067 case ARC_SPACE_L2HDRS:
2068 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
2072 if (type != ARC_SPACE_DATA)
2073 ARCSTAT_INCR(arcstat_meta_used, space);
2075 atomic_add_64(&arc_size, space);
2079 arc_space_return(uint64_t space, arc_space_type_t type)
2081 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2084 case ARC_SPACE_DATA:
2085 ARCSTAT_INCR(arcstat_data_size, -space);
2087 case ARC_SPACE_META:
2088 ARCSTAT_INCR(arcstat_metadata_size, -space);
2090 case ARC_SPACE_OTHER:
2091 ARCSTAT_INCR(arcstat_other_size, -space);
2093 case ARC_SPACE_HDRS:
2094 ARCSTAT_INCR(arcstat_hdr_size, -space);
2096 case ARC_SPACE_L2HDRS:
2097 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2101 if (type != ARC_SPACE_DATA) {
2102 ASSERT(arc_meta_used >= space);
2103 if (arc_meta_max < arc_meta_used)
2104 arc_meta_max = arc_meta_used;
2105 ARCSTAT_INCR(arcstat_meta_used, -space);
2108 ASSERT(arc_size >= space);
2109 atomic_add_64(&arc_size, -space);
2113 arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2118 ASSERT3U(size, >, 0);
2119 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2120 ASSERT(BUF_EMPTY(hdr));
2121 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
2123 hdr->b_spa = spa_load_guid(spa);
2125 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2128 buf->b_efunc = NULL;
2129 buf->b_private = NULL;
2132 hdr->b_flags = arc_bufc_to_flags(type);
2133 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
2135 hdr->b_l1hdr.b_buf = buf;
2136 hdr->b_l1hdr.b_state = arc_anon;
2137 hdr->b_l1hdr.b_arc_access = 0;
2138 hdr->b_l1hdr.b_datacnt = 1;
2139 hdr->b_l1hdr.b_tmp_cdata = NULL;
2141 arc_get_data_buf(buf);
2142 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2143 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2148 static char *arc_onloan_tag = "onloan";
2151 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2152 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2153 * buffers must be returned to the arc before they can be used by the DMU or
2157 arc_loan_buf(spa_t *spa, int size)
2161 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2163 atomic_add_64(&arc_loaned_bytes, size);
2168 * Return a loaned arc buffer to the arc.
2171 arc_return_buf(arc_buf_t *buf, void *tag)
2173 arc_buf_hdr_t *hdr = buf->b_hdr;
2175 ASSERT(buf->b_data != NULL);
2176 ASSERT(HDR_HAS_L1HDR(hdr));
2177 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2178 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2180 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2183 /* Detach an arc_buf from a dbuf (tag) */
2185 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2187 arc_buf_hdr_t *hdr = buf->b_hdr;
2189 ASSERT(buf->b_data != NULL);
2190 ASSERT(HDR_HAS_L1HDR(hdr));
2191 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2192 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2193 buf->b_efunc = NULL;
2194 buf->b_private = NULL;
2196 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2200 arc_buf_clone(arc_buf_t *from)
2203 arc_buf_hdr_t *hdr = from->b_hdr;
2204 uint64_t size = hdr->b_size;
2206 ASSERT(HDR_HAS_L1HDR(hdr));
2207 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2209 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2212 buf->b_efunc = NULL;
2213 buf->b_private = NULL;
2214 buf->b_next = hdr->b_l1hdr.b_buf;
2215 hdr->b_l1hdr.b_buf = buf;
2216 arc_get_data_buf(buf);
2217 bcopy(from->b_data, buf->b_data, size);
2220 * This buffer already exists in the arc so create a duplicate
2221 * copy for the caller. If the buffer is associated with user data
2222 * then track the size and number of duplicates. These stats will be
2223 * updated as duplicate buffers are created and destroyed.
2225 if (HDR_ISTYPE_DATA(hdr)) {
2226 ARCSTAT_BUMP(arcstat_duplicate_buffers);
2227 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2229 hdr->b_l1hdr.b_datacnt += 1;
2234 arc_buf_add_ref(arc_buf_t *buf, void* tag)
2237 kmutex_t *hash_lock;
2240 * Check to see if this buffer is evicted. Callers
2241 * must verify b_data != NULL to know if the add_ref
2244 mutex_enter(&buf->b_evict_lock);
2245 if (buf->b_data == NULL) {
2246 mutex_exit(&buf->b_evict_lock);
2249 hash_lock = HDR_LOCK(buf->b_hdr);
2250 mutex_enter(hash_lock);
2252 ASSERT(HDR_HAS_L1HDR(hdr));
2253 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2254 mutex_exit(&buf->b_evict_lock);
2256 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2257 hdr->b_l1hdr.b_state == arc_mfu);
2259 add_reference(hdr, hash_lock, tag);
2260 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2261 arc_access(hdr, hash_lock);
2262 mutex_exit(hash_lock);
2263 ARCSTAT_BUMP(arcstat_hits);
2264 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2265 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2266 data, metadata, hits);
2270 arc_buf_free_on_write(void *data, size_t size,
2271 void (*free_func)(void *, size_t))
2273 l2arc_data_free_t *df;
2275 df = kmem_alloc(sizeof (*df), KM_SLEEP);
2276 df->l2df_data = data;
2277 df->l2df_size = size;
2278 df->l2df_func = free_func;
2279 mutex_enter(&l2arc_free_on_write_mtx);
2280 list_insert_head(l2arc_free_on_write, df);
2281 mutex_exit(&l2arc_free_on_write_mtx);
2285 * Free the arc data buffer. If it is an l2arc write in progress,
2286 * the buffer is placed on l2arc_free_on_write to be freed later.
2289 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2291 arc_buf_hdr_t *hdr = buf->b_hdr;
2293 if (HDR_L2_WRITING(hdr)) {
2294 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2295 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2297 free_func(buf->b_data, hdr->b_size);
2302 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2304 size_t align, asize, len;
2306 ASSERT(HDR_HAS_L2HDR(hdr));
2307 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2310 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2311 * that doesn't exist, the header is in the arc_l2c_only state,
2312 * and there isn't anything to free (it's already been freed).
2314 if (!HDR_HAS_L1HDR(hdr))
2318 * The header isn't being written to the l2arc device, thus it
2319 * shouldn't have a b_tmp_cdata to free.
2321 if (!HDR_L2_WRITING(hdr)) {
2322 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2327 * The bufer has been chosen for writing to L2ARC, but it's
2328 * not being written just yet. In other words,
2329 * b_tmp_cdata points to exactly the same buffer as b_data,
2330 * l2arc_transform_buf hasn't been called.
2332 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET) {
2333 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==,
2334 hdr->b_l1hdr.b_buf->b_data);
2335 ASSERT3U(hdr->b_l2hdr.b_compress, ==, ZIO_COMPRESS_OFF);
2336 hdr->b_l1hdr.b_tmp_cdata = NULL;
2341 * There's nothing to free since the buffer was all zero's and
2342 * compressed to a zero length buffer.
2344 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_EMPTY) {
2345 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2350 * Nothing to do if the temporary buffer was not required.
2352 if (hdr->b_l1hdr.b_tmp_cdata == NULL)
2355 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2357 align = (size_t)1 << hdr->b_l2hdr.b_dev->l2ad_vdev->vdev_ashift;
2358 asize = P2ROUNDUP(len, align);
2359 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata, asize,
2361 hdr->b_l1hdr.b_tmp_cdata = NULL;
2365 * Free up buf->b_data and if 'remove' is set, then pull the
2366 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2369 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2373 /* free up data associated with the buf */
2374 if (buf->b_data != NULL) {
2375 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2376 uint64_t size = buf->b_hdr->b_size;
2377 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2379 arc_cksum_verify(buf);
2381 arc_buf_unwatch(buf);
2384 if (type == ARC_BUFC_METADATA) {
2385 arc_buf_data_free(buf, zio_buf_free);
2386 arc_space_return(size, ARC_SPACE_META);
2388 ASSERT(type == ARC_BUFC_DATA);
2389 arc_buf_data_free(buf, zio_data_buf_free);
2390 arc_space_return(size, ARC_SPACE_DATA);
2393 /* protected by hash lock, if in the hash table */
2394 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2395 uint64_t *cnt = &state->arcs_lsize[type];
2397 ASSERT(refcount_is_zero(
2398 &buf->b_hdr->b_l1hdr.b_refcnt));
2399 ASSERT(state != arc_anon && state != arc_l2c_only);
2401 ASSERT3U(*cnt, >=, size);
2402 atomic_add_64(cnt, -size);
2405 (void) refcount_remove_many(&state->arcs_size, size, buf);
2409 * If we're destroying a duplicate buffer make sure
2410 * that the appropriate statistics are updated.
2412 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2413 HDR_ISTYPE_DATA(buf->b_hdr)) {
2414 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2415 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2417 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2418 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2421 /* only remove the buf if requested */
2425 /* remove the buf from the hdr list */
2426 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2427 bufp = &(*bufp)->b_next)
2429 *bufp = buf->b_next;
2432 ASSERT(buf->b_efunc == NULL);
2434 /* clean up the buf */
2436 kmem_cache_free(buf_cache, buf);
2440 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2442 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2443 l2arc_dev_t *dev = l2hdr->b_dev;
2445 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2446 ASSERT(HDR_HAS_L2HDR(hdr));
2448 list_remove(&dev->l2ad_buflist, hdr);
2451 * We don't want to leak the b_tmp_cdata buffer that was
2452 * allocated in l2arc_write_buffers()
2454 arc_buf_l2_cdata_free(hdr);
2457 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2458 * this header is being processed by l2arc_write_buffers() (i.e.
2459 * it's in the first stage of l2arc_write_buffers()).
2460 * Re-affirming that truth here, just to serve as a reminder. If
2461 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2462 * may not have its HDR_L2_WRITING flag set. (the write may have
2463 * completed, in which case HDR_L2_WRITING will be false and the
2464 * b_daddr field will point to the address of the buffer on disk).
2466 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2469 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2470 * l2arc_write_buffers(). Since we've just removed this header
2471 * from the l2arc buffer list, this header will never reach the
2472 * second stage of l2arc_write_buffers(), which increments the
2473 * accounting stats for this header. Thus, we must be careful
2474 * not to decrement them for this header either.
2476 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2477 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2478 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2480 vdev_space_update(dev->l2ad_vdev,
2481 -l2hdr->b_asize, 0, 0);
2483 (void) refcount_remove_many(&dev->l2ad_alloc,
2484 l2hdr->b_asize, hdr);
2487 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2491 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2493 if (HDR_HAS_L1HDR(hdr)) {
2494 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2495 hdr->b_l1hdr.b_datacnt > 0);
2496 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2497 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2499 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2500 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2502 if (HDR_HAS_L2HDR(hdr)) {
2503 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2504 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2507 mutex_enter(&dev->l2ad_mtx);
2510 * Even though we checked this conditional above, we
2511 * need to check this again now that we have the
2512 * l2ad_mtx. This is because we could be racing with
2513 * another thread calling l2arc_evict() which might have
2514 * destroyed this header's L2 portion as we were waiting
2515 * to acquire the l2ad_mtx. If that happens, we don't
2516 * want to re-destroy the header's L2 portion.
2518 if (HDR_HAS_L2HDR(hdr)) {
2520 arc_hdr_l2hdr_destroy(hdr);
2524 mutex_exit(&dev->l2ad_mtx);
2527 if (!BUF_EMPTY(hdr))
2528 buf_discard_identity(hdr);
2530 if (hdr->b_freeze_cksum != NULL) {
2531 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2532 hdr->b_freeze_cksum = NULL;
2535 if (HDR_HAS_L1HDR(hdr)) {
2536 while (hdr->b_l1hdr.b_buf) {
2537 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2539 if (buf->b_efunc != NULL) {
2540 mutex_enter(&arc_user_evicts_lock);
2541 mutex_enter(&buf->b_evict_lock);
2542 ASSERT(buf->b_hdr != NULL);
2543 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2544 hdr->b_l1hdr.b_buf = buf->b_next;
2545 buf->b_hdr = &arc_eviction_hdr;
2546 buf->b_next = arc_eviction_list;
2547 arc_eviction_list = buf;
2548 mutex_exit(&buf->b_evict_lock);
2549 cv_signal(&arc_user_evicts_cv);
2550 mutex_exit(&arc_user_evicts_lock);
2552 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2556 if (hdr->b_l1hdr.b_thawed != NULL) {
2557 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2558 hdr->b_l1hdr.b_thawed = NULL;
2563 ASSERT3P(hdr->b_hash_next, ==, NULL);
2564 if (HDR_HAS_L1HDR(hdr)) {
2565 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2566 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2567 kmem_cache_free(hdr_full_cache, hdr);
2569 kmem_cache_free(hdr_l2only_cache, hdr);
2574 arc_buf_free(arc_buf_t *buf, void *tag)
2576 arc_buf_hdr_t *hdr = buf->b_hdr;
2577 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2579 ASSERT(buf->b_efunc == NULL);
2580 ASSERT(buf->b_data != NULL);
2583 kmutex_t *hash_lock = HDR_LOCK(hdr);
2585 mutex_enter(hash_lock);
2587 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2589 (void) remove_reference(hdr, hash_lock, tag);
2590 if (hdr->b_l1hdr.b_datacnt > 1) {
2591 arc_buf_destroy(buf, TRUE);
2593 ASSERT(buf == hdr->b_l1hdr.b_buf);
2594 ASSERT(buf->b_efunc == NULL);
2595 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2597 mutex_exit(hash_lock);
2598 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2601 * We are in the middle of an async write. Don't destroy
2602 * this buffer unless the write completes before we finish
2603 * decrementing the reference count.
2605 mutex_enter(&arc_user_evicts_lock);
2606 (void) remove_reference(hdr, NULL, tag);
2607 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2608 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2609 mutex_exit(&arc_user_evicts_lock);
2611 arc_hdr_destroy(hdr);
2613 if (remove_reference(hdr, NULL, tag) > 0)
2614 arc_buf_destroy(buf, TRUE);
2616 arc_hdr_destroy(hdr);
2621 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2623 arc_buf_hdr_t *hdr = buf->b_hdr;
2624 kmutex_t *hash_lock = HDR_LOCK(hdr);
2625 boolean_t no_callback = (buf->b_efunc == NULL);
2627 if (hdr->b_l1hdr.b_state == arc_anon) {
2628 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2629 arc_buf_free(buf, tag);
2630 return (no_callback);
2633 mutex_enter(hash_lock);
2635 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2636 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2637 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2638 ASSERT(buf->b_data != NULL);
2640 (void) remove_reference(hdr, hash_lock, tag);
2641 if (hdr->b_l1hdr.b_datacnt > 1) {
2643 arc_buf_destroy(buf, TRUE);
2644 } else if (no_callback) {
2645 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2646 ASSERT(buf->b_efunc == NULL);
2647 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2649 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2650 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2651 mutex_exit(hash_lock);
2652 return (no_callback);
2656 arc_buf_size(arc_buf_t *buf)
2658 return (buf->b_hdr->b_size);
2662 * Called from the DMU to determine if the current buffer should be
2663 * evicted. In order to ensure proper locking, the eviction must be initiated
2664 * from the DMU. Return true if the buffer is associated with user data and
2665 * duplicate buffers still exist.
2668 arc_buf_eviction_needed(arc_buf_t *buf)
2671 boolean_t evict_needed = B_FALSE;
2673 if (zfs_disable_dup_eviction)
2676 mutex_enter(&buf->b_evict_lock);
2680 * We are in arc_do_user_evicts(); let that function
2681 * perform the eviction.
2683 ASSERT(buf->b_data == NULL);
2684 mutex_exit(&buf->b_evict_lock);
2686 } else if (buf->b_data == NULL) {
2688 * We have already been added to the arc eviction list;
2689 * recommend eviction.
2691 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2692 mutex_exit(&buf->b_evict_lock);
2696 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2697 evict_needed = B_TRUE;
2699 mutex_exit(&buf->b_evict_lock);
2700 return (evict_needed);
2704 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2705 * state of the header is dependent on it's state prior to entering this
2706 * function. The following transitions are possible:
2708 * - arc_mru -> arc_mru_ghost
2709 * - arc_mfu -> arc_mfu_ghost
2710 * - arc_mru_ghost -> arc_l2c_only
2711 * - arc_mru_ghost -> deleted
2712 * - arc_mfu_ghost -> arc_l2c_only
2713 * - arc_mfu_ghost -> deleted
2716 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2718 arc_state_t *evicted_state, *state;
2719 int64_t bytes_evicted = 0;
2721 ASSERT(MUTEX_HELD(hash_lock));
2722 ASSERT(HDR_HAS_L1HDR(hdr));
2724 state = hdr->b_l1hdr.b_state;
2725 if (GHOST_STATE(state)) {
2726 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2727 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2730 * l2arc_write_buffers() relies on a header's L1 portion
2731 * (i.e. it's b_tmp_cdata field) during it's write phase.
2732 * Thus, we cannot push a header onto the arc_l2c_only
2733 * state (removing it's L1 piece) until the header is
2734 * done being written to the l2arc.
2736 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2737 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2738 return (bytes_evicted);
2741 ARCSTAT_BUMP(arcstat_deleted);
2742 bytes_evicted += hdr->b_size;
2744 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2746 if (HDR_HAS_L2HDR(hdr)) {
2748 * This buffer is cached on the 2nd Level ARC;
2749 * don't destroy the header.
2751 arc_change_state(arc_l2c_only, hdr, hash_lock);
2753 * dropping from L1+L2 cached to L2-only,
2754 * realloc to remove the L1 header.
2756 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2759 arc_change_state(arc_anon, hdr, hash_lock);
2760 arc_hdr_destroy(hdr);
2762 return (bytes_evicted);
2765 ASSERT(state == arc_mru || state == arc_mfu);
2766 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2768 /* prefetch buffers have a minimum lifespan */
2769 if (HDR_IO_IN_PROGRESS(hdr) ||
2770 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2771 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2772 arc_min_prefetch_lifespan)) {
2773 ARCSTAT_BUMP(arcstat_evict_skip);
2774 return (bytes_evicted);
2777 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2778 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2779 while (hdr->b_l1hdr.b_buf) {
2780 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2781 if (!mutex_tryenter(&buf->b_evict_lock)) {
2782 ARCSTAT_BUMP(arcstat_mutex_miss);
2785 if (buf->b_data != NULL)
2786 bytes_evicted += hdr->b_size;
2787 if (buf->b_efunc != NULL) {
2788 mutex_enter(&arc_user_evicts_lock);
2789 arc_buf_destroy(buf, FALSE);
2790 hdr->b_l1hdr.b_buf = buf->b_next;
2791 buf->b_hdr = &arc_eviction_hdr;
2792 buf->b_next = arc_eviction_list;
2793 arc_eviction_list = buf;
2794 cv_signal(&arc_user_evicts_cv);
2795 mutex_exit(&arc_user_evicts_lock);
2796 mutex_exit(&buf->b_evict_lock);
2798 mutex_exit(&buf->b_evict_lock);
2799 arc_buf_destroy(buf, TRUE);
2803 if (HDR_HAS_L2HDR(hdr)) {
2804 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2806 if (l2arc_write_eligible(hdr->b_spa, hdr))
2807 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2809 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2812 if (hdr->b_l1hdr.b_datacnt == 0) {
2813 arc_change_state(evicted_state, hdr, hash_lock);
2814 ASSERT(HDR_IN_HASH_TABLE(hdr));
2815 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2816 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2817 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2820 return (bytes_evicted);
2824 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2825 uint64_t spa, int64_t bytes)
2827 multilist_sublist_t *mls;
2828 uint64_t bytes_evicted = 0;
2830 kmutex_t *hash_lock;
2831 int evict_count = 0;
2833 ASSERT3P(marker, !=, NULL);
2834 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2836 mls = multilist_sublist_lock(ml, idx);
2838 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2839 hdr = multilist_sublist_prev(mls, marker)) {
2840 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2841 (evict_count >= zfs_arc_evict_batch_limit))
2845 * To keep our iteration location, move the marker
2846 * forward. Since we're not holding hdr's hash lock, we
2847 * must be very careful and not remove 'hdr' from the
2848 * sublist. Otherwise, other consumers might mistake the
2849 * 'hdr' as not being on a sublist when they call the
2850 * multilist_link_active() function (they all rely on
2851 * the hash lock protecting concurrent insertions and
2852 * removals). multilist_sublist_move_forward() was
2853 * specifically implemented to ensure this is the case
2854 * (only 'marker' will be removed and re-inserted).
2856 multilist_sublist_move_forward(mls, marker);
2859 * The only case where the b_spa field should ever be
2860 * zero, is the marker headers inserted by
2861 * arc_evict_state(). It's possible for multiple threads
2862 * to be calling arc_evict_state() concurrently (e.g.
2863 * dsl_pool_close() and zio_inject_fault()), so we must
2864 * skip any markers we see from these other threads.
2866 if (hdr->b_spa == 0)
2869 /* we're only interested in evicting buffers of a certain spa */
2870 if (spa != 0 && hdr->b_spa != spa) {
2871 ARCSTAT_BUMP(arcstat_evict_skip);
2875 hash_lock = HDR_LOCK(hdr);
2878 * We aren't calling this function from any code path
2879 * that would already be holding a hash lock, so we're
2880 * asserting on this assumption to be defensive in case
2881 * this ever changes. Without this check, it would be
2882 * possible to incorrectly increment arcstat_mutex_miss
2883 * below (e.g. if the code changed such that we called
2884 * this function with a hash lock held).
2886 ASSERT(!MUTEX_HELD(hash_lock));
2888 if (mutex_tryenter(hash_lock)) {
2889 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2890 mutex_exit(hash_lock);
2892 bytes_evicted += evicted;
2895 * If evicted is zero, arc_evict_hdr() must have
2896 * decided to skip this header, don't increment
2897 * evict_count in this case.
2903 * If arc_size isn't overflowing, signal any
2904 * threads that might happen to be waiting.
2906 * For each header evicted, we wake up a single
2907 * thread. If we used cv_broadcast, we could
2908 * wake up "too many" threads causing arc_size
2909 * to significantly overflow arc_c; since
2910 * arc_get_data_buf() doesn't check for overflow
2911 * when it's woken up (it doesn't because it's
2912 * possible for the ARC to be overflowing while
2913 * full of un-evictable buffers, and the
2914 * function should proceed in this case).
2916 * If threads are left sleeping, due to not
2917 * using cv_broadcast, they will be woken up
2918 * just before arc_reclaim_thread() sleeps.
2920 mutex_enter(&arc_reclaim_lock);
2921 if (!arc_is_overflowing())
2922 cv_signal(&arc_reclaim_waiters_cv);
2923 mutex_exit(&arc_reclaim_lock);
2925 ARCSTAT_BUMP(arcstat_mutex_miss);
2929 multilist_sublist_unlock(mls);
2931 return (bytes_evicted);
2935 * Evict buffers from the given arc state, until we've removed the
2936 * specified number of bytes. Move the removed buffers to the
2937 * appropriate evict state.
2939 * This function makes a "best effort". It skips over any buffers
2940 * it can't get a hash_lock on, and so, may not catch all candidates.
2941 * It may also return without evicting as much space as requested.
2943 * If bytes is specified using the special value ARC_EVICT_ALL, this
2944 * will evict all available (i.e. unlocked and evictable) buffers from
2945 * the given arc state; which is used by arc_flush().
2948 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2949 arc_buf_contents_t type)
2951 uint64_t total_evicted = 0;
2952 multilist_t *ml = &state->arcs_list[type];
2954 arc_buf_hdr_t **markers;
2956 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2958 num_sublists = multilist_get_num_sublists(ml);
2961 * If we've tried to evict from each sublist, made some
2962 * progress, but still have not hit the target number of bytes
2963 * to evict, we want to keep trying. The markers allow us to
2964 * pick up where we left off for each individual sublist, rather
2965 * than starting from the tail each time.
2967 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2968 for (int i = 0; i < num_sublists; i++) {
2969 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2972 * A b_spa of 0 is used to indicate that this header is
2973 * a marker. This fact is used in arc_adjust_type() and
2974 * arc_evict_state_impl().
2976 markers[i]->b_spa = 0;
2978 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2979 multilist_sublist_insert_tail(mls, markers[i]);
2980 multilist_sublist_unlock(mls);
2984 * While we haven't hit our target number of bytes to evict, or
2985 * we're evicting all available buffers.
2987 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2989 * Start eviction using a randomly selected sublist,
2990 * this is to try and evenly balance eviction across all
2991 * sublists. Always starting at the same sublist
2992 * (e.g. index 0) would cause evictions to favor certain
2993 * sublists over others.
2995 int sublist_idx = multilist_get_random_index(ml);
2996 uint64_t scan_evicted = 0;
2998 for (int i = 0; i < num_sublists; i++) {
2999 uint64_t bytes_remaining;
3000 uint64_t bytes_evicted;
3002 if (bytes == ARC_EVICT_ALL)
3003 bytes_remaining = ARC_EVICT_ALL;
3004 else if (total_evicted < bytes)
3005 bytes_remaining = bytes - total_evicted;
3009 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3010 markers[sublist_idx], spa, bytes_remaining);
3012 scan_evicted += bytes_evicted;
3013 total_evicted += bytes_evicted;
3015 /* we've reached the end, wrap to the beginning */
3016 if (++sublist_idx >= num_sublists)
3021 * If we didn't evict anything during this scan, we have
3022 * no reason to believe we'll evict more during another
3023 * scan, so break the loop.
3025 if (scan_evicted == 0) {
3026 /* This isn't possible, let's make that obvious */
3027 ASSERT3S(bytes, !=, 0);
3030 * When bytes is ARC_EVICT_ALL, the only way to
3031 * break the loop is when scan_evicted is zero.
3032 * In that case, we actually have evicted enough,
3033 * so we don't want to increment the kstat.
3035 if (bytes != ARC_EVICT_ALL) {
3036 ASSERT3S(total_evicted, <, bytes);
3037 ARCSTAT_BUMP(arcstat_evict_not_enough);
3044 for (int i = 0; i < num_sublists; i++) {
3045 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3046 multilist_sublist_remove(mls, markers[i]);
3047 multilist_sublist_unlock(mls);
3049 kmem_cache_free(hdr_full_cache, markers[i]);
3051 kmem_free(markers, sizeof (*markers) * num_sublists);
3053 return (total_evicted);
3057 * Flush all "evictable" data of the given type from the arc state
3058 * specified. This will not evict any "active" buffers (i.e. referenced).
3060 * When 'retry' is set to FALSE, the function will make a single pass
3061 * over the state and evict any buffers that it can. Since it doesn't
3062 * continually retry the eviction, it might end up leaving some buffers
3063 * in the ARC due to lock misses.
3065 * When 'retry' is set to TRUE, the function will continually retry the
3066 * eviction until *all* evictable buffers have been removed from the
3067 * state. As a result, if concurrent insertions into the state are
3068 * allowed (e.g. if the ARC isn't shutting down), this function might
3069 * wind up in an infinite loop, continually trying to evict buffers.
3072 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3075 uint64_t evicted = 0;
3077 while (state->arcs_lsize[type] != 0) {
3078 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3088 * Evict the specified number of bytes from the state specified,
3089 * restricting eviction to the spa and type given. This function
3090 * prevents us from trying to evict more from a state's list than
3091 * is "evictable", and to skip evicting altogether when passed a
3092 * negative value for "bytes". In contrast, arc_evict_state() will
3093 * evict everything it can, when passed a negative value for "bytes".
3096 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3097 arc_buf_contents_t type)
3101 if (bytes > 0 && state->arcs_lsize[type] > 0) {
3102 delta = MIN(state->arcs_lsize[type], bytes);
3103 return (arc_evict_state(state, spa, delta, type));
3110 * Evict metadata buffers from the cache, such that arc_meta_used is
3111 * capped by the arc_meta_limit tunable.
3114 arc_adjust_meta(void)
3116 uint64_t total_evicted = 0;
3120 * If we're over the meta limit, we want to evict enough
3121 * metadata to get back under the meta limit. We don't want to
3122 * evict so much that we drop the MRU below arc_p, though. If
3123 * we're over the meta limit more than we're over arc_p, we
3124 * evict some from the MRU here, and some from the MFU below.
3126 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3127 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3128 refcount_count(&arc_mru->arcs_size) - arc_p));
3130 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3133 * Similar to the above, we want to evict enough bytes to get us
3134 * below the meta limit, but not so much as to drop us below the
3135 * space alloted to the MFU (which is defined as arc_c - arc_p).
3137 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3138 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3140 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3142 return (total_evicted);
3146 * Return the type of the oldest buffer in the given arc state
3148 * This function will select a random sublist of type ARC_BUFC_DATA and
3149 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3150 * is compared, and the type which contains the "older" buffer will be
3153 static arc_buf_contents_t
3154 arc_adjust_type(arc_state_t *state)
3156 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3157 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3158 int data_idx = multilist_get_random_index(data_ml);
3159 int meta_idx = multilist_get_random_index(meta_ml);
3160 multilist_sublist_t *data_mls;
3161 multilist_sublist_t *meta_mls;
3162 arc_buf_contents_t type;
3163 arc_buf_hdr_t *data_hdr;
3164 arc_buf_hdr_t *meta_hdr;
3167 * We keep the sublist lock until we're finished, to prevent
3168 * the headers from being destroyed via arc_evict_state().
3170 data_mls = multilist_sublist_lock(data_ml, data_idx);
3171 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3174 * These two loops are to ensure we skip any markers that
3175 * might be at the tail of the lists due to arc_evict_state().
3178 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3179 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3180 if (data_hdr->b_spa != 0)
3184 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3185 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3186 if (meta_hdr->b_spa != 0)
3190 if (data_hdr == NULL && meta_hdr == NULL) {
3191 type = ARC_BUFC_DATA;
3192 } else if (data_hdr == NULL) {
3193 ASSERT3P(meta_hdr, !=, NULL);
3194 type = ARC_BUFC_METADATA;
3195 } else if (meta_hdr == NULL) {
3196 ASSERT3P(data_hdr, !=, NULL);
3197 type = ARC_BUFC_DATA;
3199 ASSERT3P(data_hdr, !=, NULL);
3200 ASSERT3P(meta_hdr, !=, NULL);
3202 /* The headers can't be on the sublist without an L1 header */
3203 ASSERT(HDR_HAS_L1HDR(data_hdr));
3204 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3206 if (data_hdr->b_l1hdr.b_arc_access <
3207 meta_hdr->b_l1hdr.b_arc_access) {
3208 type = ARC_BUFC_DATA;
3210 type = ARC_BUFC_METADATA;
3214 multilist_sublist_unlock(meta_mls);
3215 multilist_sublist_unlock(data_mls);
3221 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3226 uint64_t total_evicted = 0;
3231 * If we're over arc_meta_limit, we want to correct that before
3232 * potentially evicting data buffers below.
3234 total_evicted += arc_adjust_meta();
3239 * If we're over the target cache size, we want to evict enough
3240 * from the list to get back to our target size. We don't want
3241 * to evict too much from the MRU, such that it drops below
3242 * arc_p. So, if we're over our target cache size more than
3243 * the MRU is over arc_p, we'll evict enough to get back to
3244 * arc_p here, and then evict more from the MFU below.
3246 target = MIN((int64_t)(arc_size - arc_c),
3247 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3248 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3251 * If we're below arc_meta_min, always prefer to evict data.
3252 * Otherwise, try to satisfy the requested number of bytes to
3253 * evict from the type which contains older buffers; in an
3254 * effort to keep newer buffers in the cache regardless of their
3255 * type. If we cannot satisfy the number of bytes from this
3256 * type, spill over into the next type.
3258 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3259 arc_meta_used > arc_meta_min) {
3260 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3261 total_evicted += bytes;
3264 * If we couldn't evict our target number of bytes from
3265 * metadata, we try to get the rest from data.
3270 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3272 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3273 total_evicted += bytes;
3276 * If we couldn't evict our target number of bytes from
3277 * data, we try to get the rest from metadata.
3282 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3288 * Now that we've tried to evict enough from the MRU to get its
3289 * size back to arc_p, if we're still above the target cache
3290 * size, we evict the rest from the MFU.
3292 target = arc_size - arc_c;
3294 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3295 arc_meta_used > arc_meta_min) {
3296 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3297 total_evicted += bytes;
3300 * If we couldn't evict our target number of bytes from
3301 * metadata, we try to get the rest from data.
3306 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3308 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3309 total_evicted += bytes;
3312 * If we couldn't evict our target number of bytes from
3313 * data, we try to get the rest from data.
3318 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3322 * Adjust ghost lists
3324 * In addition to the above, the ARC also defines target values
3325 * for the ghost lists. The sum of the mru list and mru ghost
3326 * list should never exceed the target size of the cache, and
3327 * the sum of the mru list, mfu list, mru ghost list, and mfu
3328 * ghost list should never exceed twice the target size of the
3329 * cache. The following logic enforces these limits on the ghost
3330 * caches, and evicts from them as needed.
3332 target = refcount_count(&arc_mru->arcs_size) +
3333 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3335 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3336 total_evicted += bytes;
3341 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3344 * We assume the sum of the mru list and mfu list is less than
3345 * or equal to arc_c (we enforced this above), which means we
3346 * can use the simpler of the two equations below:
3348 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3349 * mru ghost + mfu ghost <= arc_c
3351 target = refcount_count(&arc_mru_ghost->arcs_size) +
3352 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3354 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3355 total_evicted += bytes;
3360 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3362 return (total_evicted);
3366 arc_do_user_evicts(void)
3368 mutex_enter(&arc_user_evicts_lock);
3369 while (arc_eviction_list != NULL) {
3370 arc_buf_t *buf = arc_eviction_list;
3371 arc_eviction_list = buf->b_next;
3372 mutex_enter(&buf->b_evict_lock);
3374 mutex_exit(&buf->b_evict_lock);
3375 mutex_exit(&arc_user_evicts_lock);
3377 if (buf->b_efunc != NULL)
3378 VERIFY0(buf->b_efunc(buf->b_private));
3380 buf->b_efunc = NULL;
3381 buf->b_private = NULL;
3382 kmem_cache_free(buf_cache, buf);
3383 mutex_enter(&arc_user_evicts_lock);
3385 mutex_exit(&arc_user_evicts_lock);
3389 arc_flush(spa_t *spa, boolean_t retry)
3394 * If retry is TRUE, a spa must not be specified since we have
3395 * no good way to determine if all of a spa's buffers have been
3396 * evicted from an arc state.
3398 ASSERT(!retry || spa == 0);
3401 guid = spa_load_guid(spa);
3403 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3404 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3406 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3407 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3409 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3410 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3412 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3413 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3415 arc_do_user_evicts();
3416 ASSERT(spa || arc_eviction_list == NULL);
3420 arc_shrink(int64_t to_free)
3422 if (arc_c > arc_c_min) {
3423 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3424 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3425 if (arc_c > arc_c_min + to_free)
3426 atomic_add_64(&arc_c, -to_free);
3430 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3431 if (arc_c > arc_size)
3432 arc_c = MAX(arc_size, arc_c_min);
3434 arc_p = (arc_c >> 1);
3436 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3439 ASSERT(arc_c >= arc_c_min);
3440 ASSERT((int64_t)arc_p >= 0);
3443 if (arc_size > arc_c) {
3444 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3446 (void) arc_adjust();
3450 static long needfree = 0;
3452 typedef enum free_memory_reason_t {
3457 FMR_PAGES_PP_MAXIMUM,
3461 } free_memory_reason_t;
3463 int64_t last_free_memory;
3464 free_memory_reason_t last_free_reason;
3467 * Additional reserve of pages for pp_reserve.
3469 int64_t arc_pages_pp_reserve = 64;
3472 * Additional reserve of pages for swapfs.
3474 int64_t arc_swapfs_reserve = 64;
3477 * Return the amount of memory that can be consumed before reclaim will be
3478 * needed. Positive if there is sufficient free memory, negative indicates
3479 * the amount of memory that needs to be freed up.
3482 arc_available_memory(void)
3484 int64_t lowest = INT64_MAX;
3486 free_memory_reason_t r = FMR_UNKNOWN;
3490 n = PAGESIZE * (-needfree);
3498 * Cooperate with pagedaemon when it's time for it to scan
3499 * and reclaim some pages.
3501 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3509 * check that we're out of range of the pageout scanner. It starts to
3510 * schedule paging if freemem is less than lotsfree and needfree.
3511 * lotsfree is the high-water mark for pageout, and needfree is the
3512 * number of needed free pages. We add extra pages here to make sure
3513 * the scanner doesn't start up while we're freeing memory.
3515 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3522 * check to make sure that swapfs has enough space so that anon
3523 * reservations can still succeed. anon_resvmem() checks that the
3524 * availrmem is greater than swapfs_minfree, and the number of reserved
3525 * swap pages. We also add a bit of extra here just to prevent
3526 * circumstances from getting really dire.
3528 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3529 desfree - arc_swapfs_reserve);
3532 r = FMR_SWAPFS_MINFREE;
3537 * Check that we have enough availrmem that memory locking (e.g., via
3538 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3539 * stores the number of pages that cannot be locked; when availrmem
3540 * drops below pages_pp_maximum, page locking mechanisms such as
3541 * page_pp_lock() will fail.)
3543 n = PAGESIZE * (availrmem - pages_pp_maximum -
3544 arc_pages_pp_reserve);
3547 r = FMR_PAGES_PP_MAXIMUM;
3550 #endif /* illumos */
3551 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3553 * If we're on an i386 platform, it's possible that we'll exhaust the
3554 * kernel heap space before we ever run out of available physical
3555 * memory. Most checks of the size of the heap_area compare against
3556 * tune.t_minarmem, which is the minimum available real memory that we
3557 * can have in the system. However, this is generally fixed at 25 pages
3558 * which is so low that it's useless. In this comparison, we seek to
3559 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3560 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3563 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3564 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3569 #define zio_arena NULL
3571 #define zio_arena heap_arena
3575 * If zio data pages are being allocated out of a separate heap segment,
3576 * then enforce that the size of available vmem for this arena remains
3577 * above about 1/16th free.
3579 * Note: The 1/16th arena free requirement was put in place
3580 * to aggressively evict memory from the arc in order to avoid
3581 * memory fragmentation issues.
3583 if (zio_arena != NULL) {
3584 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3585 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3593 * Above limits know nothing about real level of KVA fragmentation.
3594 * Start aggressive reclamation if too little sequential KVA left.
3597 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3598 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3607 /* Every 100 calls, free a small amount */
3608 if (spa_get_random(100) == 0)
3610 #endif /* _KERNEL */
3612 last_free_memory = lowest;
3613 last_free_reason = r;
3614 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3620 * Determine if the system is under memory pressure and is asking
3621 * to reclaim memory. A return value of TRUE indicates that the system
3622 * is under memory pressure and that the arc should adjust accordingly.
3625 arc_reclaim_needed(void)
3627 return (arc_available_memory() < 0);
3630 extern kmem_cache_t *zio_buf_cache[];
3631 extern kmem_cache_t *zio_data_buf_cache[];
3632 extern kmem_cache_t *range_seg_cache;
3634 static __noinline void
3635 arc_kmem_reap_now(void)
3638 kmem_cache_t *prev_cache = NULL;
3639 kmem_cache_t *prev_data_cache = NULL;
3641 DTRACE_PROBE(arc__kmem_reap_start);
3643 if (arc_meta_used >= arc_meta_limit) {
3645 * We are exceeding our meta-data cache limit.
3646 * Purge some DNLC entries to release holds on meta-data.
3648 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3652 * Reclaim unused memory from all kmem caches.
3658 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3659 if (zio_buf_cache[i] != prev_cache) {
3660 prev_cache = zio_buf_cache[i];
3661 kmem_cache_reap_now(zio_buf_cache[i]);
3663 if (zio_data_buf_cache[i] != prev_data_cache) {
3664 prev_data_cache = zio_data_buf_cache[i];
3665 kmem_cache_reap_now(zio_data_buf_cache[i]);
3668 kmem_cache_reap_now(buf_cache);
3669 kmem_cache_reap_now(hdr_full_cache);
3670 kmem_cache_reap_now(hdr_l2only_cache);
3671 kmem_cache_reap_now(range_seg_cache);
3674 if (zio_arena != NULL) {
3676 * Ask the vmem arena to reclaim unused memory from its
3679 vmem_qcache_reap(zio_arena);
3682 DTRACE_PROBE(arc__kmem_reap_end);
3686 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3687 * enough data and signal them to proceed. When this happens, the threads in
3688 * arc_get_data_buf() are sleeping while holding the hash lock for their
3689 * particular arc header. Thus, we must be careful to never sleep on a
3690 * hash lock in this thread. This is to prevent the following deadlock:
3692 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3693 * waiting for the reclaim thread to signal it.
3695 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3696 * fails, and goes to sleep forever.
3698 * This possible deadlock is avoided by always acquiring a hash lock
3699 * using mutex_tryenter() from arc_reclaim_thread().
3702 arc_reclaim_thread(void *dummy __unused)
3704 hrtime_t growtime = 0;
3707 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3709 mutex_enter(&arc_reclaim_lock);
3710 while (!arc_reclaim_thread_exit) {
3711 int64_t free_memory = arc_available_memory();
3712 uint64_t evicted = 0;
3714 mutex_exit(&arc_reclaim_lock);
3716 if (free_memory < 0) {
3718 arc_no_grow = B_TRUE;
3722 * Wait at least zfs_grow_retry (default 60) seconds
3723 * before considering growing.
3725 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
3727 arc_kmem_reap_now();
3730 * If we are still low on memory, shrink the ARC
3731 * so that we have arc_shrink_min free space.
3733 free_memory = arc_available_memory();
3736 (arc_c >> arc_shrink_shift) - free_memory;
3739 to_free = MAX(to_free, ptob(needfree));
3741 arc_shrink(to_free);
3743 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3744 arc_no_grow = B_TRUE;
3745 } else if (gethrtime() >= growtime) {
3746 arc_no_grow = B_FALSE;
3749 evicted = arc_adjust();
3751 mutex_enter(&arc_reclaim_lock);
3754 * If evicted is zero, we couldn't evict anything via
3755 * arc_adjust(). This could be due to hash lock
3756 * collisions, but more likely due to the majority of
3757 * arc buffers being unevictable. Therefore, even if
3758 * arc_size is above arc_c, another pass is unlikely to
3759 * be helpful and could potentially cause us to enter an
3762 if (arc_size <= arc_c || evicted == 0) {
3767 * We're either no longer overflowing, or we
3768 * can't evict anything more, so we should wake
3769 * up any threads before we go to sleep.
3771 cv_broadcast(&arc_reclaim_waiters_cv);
3774 * Block until signaled, or after one second (we
3775 * might need to perform arc_kmem_reap_now()
3776 * even if we aren't being signalled)
3778 CALLB_CPR_SAFE_BEGIN(&cpr);
3779 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
3780 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
3781 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3785 arc_reclaim_thread_exit = FALSE;
3786 cv_broadcast(&arc_reclaim_thread_cv);
3787 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3792 arc_user_evicts_thread(void *dummy __unused)
3796 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3798 mutex_enter(&arc_user_evicts_lock);
3799 while (!arc_user_evicts_thread_exit) {
3800 mutex_exit(&arc_user_evicts_lock);
3802 arc_do_user_evicts();
3805 * This is necessary in order for the mdb ::arc dcmd to
3806 * show up to date information. Since the ::arc command
3807 * does not call the kstat's update function, without
3808 * this call, the command may show stale stats for the
3809 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3810 * with this change, the data might be up to 1 second
3811 * out of date; but that should suffice. The arc_state_t
3812 * structures can be queried directly if more accurate
3813 * information is needed.
3815 if (arc_ksp != NULL)
3816 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3818 mutex_enter(&arc_user_evicts_lock);
3821 * Block until signaled, or after one second (we need to
3822 * call the arc's kstat update function regularly).
3824 CALLB_CPR_SAFE_BEGIN(&cpr);
3825 (void) cv_timedwait(&arc_user_evicts_cv,
3826 &arc_user_evicts_lock, hz);
3827 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3830 arc_user_evicts_thread_exit = FALSE;
3831 cv_broadcast(&arc_user_evicts_cv);
3832 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3837 * Adapt arc info given the number of bytes we are trying to add and
3838 * the state that we are comming from. This function is only called
3839 * when we are adding new content to the cache.
3842 arc_adapt(int bytes, arc_state_t *state)
3845 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3846 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3847 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3849 if (state == arc_l2c_only)
3854 * Adapt the target size of the MRU list:
3855 * - if we just hit in the MRU ghost list, then increase
3856 * the target size of the MRU list.
3857 * - if we just hit in the MFU ghost list, then increase
3858 * the target size of the MFU list by decreasing the
3859 * target size of the MRU list.
3861 if (state == arc_mru_ghost) {
3862 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3863 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3865 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3866 } else if (state == arc_mfu_ghost) {
3869 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3870 mult = MIN(mult, 10);
3872 delta = MIN(bytes * mult, arc_p);
3873 arc_p = MAX(arc_p_min, arc_p - delta);
3875 ASSERT((int64_t)arc_p >= 0);
3877 if (arc_reclaim_needed()) {
3878 cv_signal(&arc_reclaim_thread_cv);
3885 if (arc_c >= arc_c_max)
3889 * If we're within (2 * maxblocksize) bytes of the target
3890 * cache size, increment the target cache size
3892 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3893 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3894 atomic_add_64(&arc_c, (int64_t)bytes);
3895 if (arc_c > arc_c_max)
3897 else if (state == arc_anon)
3898 atomic_add_64(&arc_p, (int64_t)bytes);
3902 ASSERT((int64_t)arc_p >= 0);
3906 * Check if arc_size has grown past our upper threshold, determined by
3907 * zfs_arc_overflow_shift.
3910 arc_is_overflowing(void)
3912 /* Always allow at least one block of overflow */
3913 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3914 arc_c >> zfs_arc_overflow_shift);
3916 return (arc_size >= arc_c + overflow);
3920 * The buffer, supplied as the first argument, needs a data block. If we
3921 * are hitting the hard limit for the cache size, we must sleep, waiting
3922 * for the eviction thread to catch up. If we're past the target size
3923 * but below the hard limit, we'll only signal the reclaim thread and
3927 arc_get_data_buf(arc_buf_t *buf)
3929 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3930 uint64_t size = buf->b_hdr->b_size;
3931 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3933 arc_adapt(size, state);
3936 * If arc_size is currently overflowing, and has grown past our
3937 * upper limit, we must be adding data faster than the evict
3938 * thread can evict. Thus, to ensure we don't compound the
3939 * problem by adding more data and forcing arc_size to grow even
3940 * further past it's target size, we halt and wait for the
3941 * eviction thread to catch up.
3943 * It's also possible that the reclaim thread is unable to evict
3944 * enough buffers to get arc_size below the overflow limit (e.g.
3945 * due to buffers being un-evictable, or hash lock collisions).
3946 * In this case, we want to proceed regardless if we're
3947 * overflowing; thus we don't use a while loop here.
3949 if (arc_is_overflowing()) {
3950 mutex_enter(&arc_reclaim_lock);
3953 * Now that we've acquired the lock, we may no longer be
3954 * over the overflow limit, lets check.
3956 * We're ignoring the case of spurious wake ups. If that
3957 * were to happen, it'd let this thread consume an ARC
3958 * buffer before it should have (i.e. before we're under
3959 * the overflow limit and were signalled by the reclaim
3960 * thread). As long as that is a rare occurrence, it
3961 * shouldn't cause any harm.
3963 if (arc_is_overflowing()) {
3964 cv_signal(&arc_reclaim_thread_cv);
3965 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3968 mutex_exit(&arc_reclaim_lock);
3971 if (type == ARC_BUFC_METADATA) {
3972 buf->b_data = zio_buf_alloc(size);
3973 arc_space_consume(size, ARC_SPACE_META);
3975 ASSERT(type == ARC_BUFC_DATA);
3976 buf->b_data = zio_data_buf_alloc(size);
3977 arc_space_consume(size, ARC_SPACE_DATA);
3981 * Update the state size. Note that ghost states have a
3982 * "ghost size" and so don't need to be updated.
3984 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3985 arc_buf_hdr_t *hdr = buf->b_hdr;
3986 arc_state_t *state = hdr->b_l1hdr.b_state;
3988 (void) refcount_add_many(&state->arcs_size, size, buf);
3991 * If this is reached via arc_read, the link is
3992 * protected by the hash lock. If reached via
3993 * arc_buf_alloc, the header should not be accessed by
3994 * any other thread. And, if reached via arc_read_done,
3995 * the hash lock will protect it if it's found in the
3996 * hash table; otherwise no other thread should be
3997 * trying to [add|remove]_reference it.
3999 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4000 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4001 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
4005 * If we are growing the cache, and we are adding anonymous
4006 * data, and we have outgrown arc_p, update arc_p
4008 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
4009 (refcount_count(&arc_anon->arcs_size) +
4010 refcount_count(&arc_mru->arcs_size) > arc_p))
4011 arc_p = MIN(arc_c, arc_p + size);
4013 ARCSTAT_BUMP(arcstat_allocated);
4017 * This routine is called whenever a buffer is accessed.
4018 * NOTE: the hash lock is dropped in this function.
4021 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4025 ASSERT(MUTEX_HELD(hash_lock));
4026 ASSERT(HDR_HAS_L1HDR(hdr));
4028 if (hdr->b_l1hdr.b_state == arc_anon) {
4030 * This buffer is not in the cache, and does not
4031 * appear in our "ghost" list. Add the new buffer
4035 ASSERT0(hdr->b_l1hdr.b_arc_access);
4036 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4037 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4038 arc_change_state(arc_mru, hdr, hash_lock);
4040 } else if (hdr->b_l1hdr.b_state == arc_mru) {
4041 now = ddi_get_lbolt();
4044 * If this buffer is here because of a prefetch, then either:
4045 * - clear the flag if this is a "referencing" read
4046 * (any subsequent access will bump this into the MFU state).
4048 * - move the buffer to the head of the list if this is
4049 * another prefetch (to make it less likely to be evicted).
4051 if (HDR_PREFETCH(hdr)) {
4052 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4053 /* link protected by hash lock */
4054 ASSERT(multilist_link_active(
4055 &hdr->b_l1hdr.b_arc_node));
4057 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
4058 ARCSTAT_BUMP(arcstat_mru_hits);
4060 hdr->b_l1hdr.b_arc_access = now;
4065 * This buffer has been "accessed" only once so far,
4066 * but it is still in the cache. Move it to the MFU
4069 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4071 * More than 125ms have passed since we
4072 * instantiated this buffer. Move it to the
4073 * most frequently used state.
4075 hdr->b_l1hdr.b_arc_access = now;
4076 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4077 arc_change_state(arc_mfu, hdr, hash_lock);
4079 ARCSTAT_BUMP(arcstat_mru_hits);
4080 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4081 arc_state_t *new_state;
4083 * This buffer has been "accessed" recently, but
4084 * was evicted from the cache. Move it to the
4088 if (HDR_PREFETCH(hdr)) {
4089 new_state = arc_mru;
4090 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4091 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
4092 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4094 new_state = arc_mfu;
4095 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4098 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4099 arc_change_state(new_state, hdr, hash_lock);
4101 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4102 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
4104 * This buffer has been accessed more than once and is
4105 * still in the cache. Keep it in the MFU state.
4107 * NOTE: an add_reference() that occurred when we did
4108 * the arc_read() will have kicked this off the list.
4109 * If it was a prefetch, we will explicitly move it to
4110 * the head of the list now.
4112 if ((HDR_PREFETCH(hdr)) != 0) {
4113 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4114 /* link protected by hash_lock */
4115 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4117 ARCSTAT_BUMP(arcstat_mfu_hits);
4118 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4119 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4120 arc_state_t *new_state = arc_mfu;
4122 * This buffer has been accessed more than once but has
4123 * been evicted from the cache. Move it back to the
4127 if (HDR_PREFETCH(hdr)) {
4129 * This is a prefetch access...
4130 * move this block back to the MRU state.
4132 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4133 new_state = arc_mru;
4136 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4137 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4138 arc_change_state(new_state, hdr, hash_lock);
4140 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4141 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4143 * This buffer is on the 2nd Level ARC.
4146 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4147 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4148 arc_change_state(arc_mfu, hdr, hash_lock);
4150 ASSERT(!"invalid arc state");
4154 /* a generic arc_done_func_t which you can use */
4157 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4159 if (zio == NULL || zio->io_error == 0)
4160 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4161 VERIFY(arc_buf_remove_ref(buf, arg));
4164 /* a generic arc_done_func_t */
4166 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4168 arc_buf_t **bufp = arg;
4169 if (zio && zio->io_error) {
4170 VERIFY(arc_buf_remove_ref(buf, arg));
4174 ASSERT(buf->b_data);
4179 arc_read_done(zio_t *zio)
4183 arc_buf_t *abuf; /* buffer we're assigning to callback */
4184 kmutex_t *hash_lock = NULL;
4185 arc_callback_t *callback_list, *acb;
4186 int freeable = FALSE;
4188 buf = zio->io_private;
4192 * The hdr was inserted into hash-table and removed from lists
4193 * prior to starting I/O. We should find this header, since
4194 * it's in the hash table, and it should be legit since it's
4195 * not possible to evict it during the I/O. The only possible
4196 * reason for it not to be found is if we were freed during the
4199 if (HDR_IN_HASH_TABLE(hdr)) {
4200 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4201 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4202 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4203 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4204 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4206 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4209 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4210 hash_lock == NULL) ||
4212 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4213 (found == hdr && HDR_L2_READING(hdr)));
4216 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4217 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4218 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4220 /* byteswap if necessary */
4221 callback_list = hdr->b_l1hdr.b_acb;
4222 ASSERT(callback_list != NULL);
4223 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4224 dmu_object_byteswap_t bswap =
4225 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4226 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4227 byteswap_uint64_array :
4228 dmu_ot_byteswap[bswap].ob_func;
4229 func(buf->b_data, hdr->b_size);
4232 arc_cksum_compute(buf, B_FALSE);
4237 if (hash_lock && zio->io_error == 0 &&
4238 hdr->b_l1hdr.b_state == arc_anon) {
4240 * Only call arc_access on anonymous buffers. This is because
4241 * if we've issued an I/O for an evicted buffer, we've already
4242 * called arc_access (to prevent any simultaneous readers from
4243 * getting confused).
4245 arc_access(hdr, hash_lock);
4248 /* create copies of the data buffer for the callers */
4250 for (acb = callback_list; acb; acb = acb->acb_next) {
4251 if (acb->acb_done) {
4253 ARCSTAT_BUMP(arcstat_duplicate_reads);
4254 abuf = arc_buf_clone(buf);
4256 acb->acb_buf = abuf;
4260 hdr->b_l1hdr.b_acb = NULL;
4261 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4262 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4264 ASSERT(buf->b_efunc == NULL);
4265 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4266 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4269 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4270 callback_list != NULL);
4272 if (zio->io_error != 0) {
4273 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4274 if (hdr->b_l1hdr.b_state != arc_anon)
4275 arc_change_state(arc_anon, hdr, hash_lock);
4276 if (HDR_IN_HASH_TABLE(hdr))
4277 buf_hash_remove(hdr);
4278 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4282 * Broadcast before we drop the hash_lock to avoid the possibility
4283 * that the hdr (and hence the cv) might be freed before we get to
4284 * the cv_broadcast().
4286 cv_broadcast(&hdr->b_l1hdr.b_cv);
4288 if (hash_lock != NULL) {
4289 mutex_exit(hash_lock);
4292 * This block was freed while we waited for the read to
4293 * complete. It has been removed from the hash table and
4294 * moved to the anonymous state (so that it won't show up
4297 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4298 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4301 /* execute each callback and free its structure */
4302 while ((acb = callback_list) != NULL) {
4304 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4306 if (acb->acb_zio_dummy != NULL) {
4307 acb->acb_zio_dummy->io_error = zio->io_error;
4308 zio_nowait(acb->acb_zio_dummy);
4311 callback_list = acb->acb_next;
4312 kmem_free(acb, sizeof (arc_callback_t));
4316 arc_hdr_destroy(hdr);
4320 * "Read" the block at the specified DVA (in bp) via the
4321 * cache. If the block is found in the cache, invoke the provided
4322 * callback immediately and return. Note that the `zio' parameter
4323 * in the callback will be NULL in this case, since no IO was
4324 * required. If the block is not in the cache pass the read request
4325 * on to the spa with a substitute callback function, so that the
4326 * requested block will be added to the cache.
4328 * If a read request arrives for a block that has a read in-progress,
4329 * either wait for the in-progress read to complete (and return the
4330 * results); or, if this is a read with a "done" func, add a record
4331 * to the read to invoke the "done" func when the read completes,
4332 * and return; or just return.
4334 * arc_read_done() will invoke all the requested "done" functions
4335 * for readers of this block.
4338 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4339 void *private, zio_priority_t priority, int zio_flags,
4340 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4342 arc_buf_hdr_t *hdr = NULL;
4343 arc_buf_t *buf = NULL;
4344 kmutex_t *hash_lock = NULL;
4346 uint64_t guid = spa_load_guid(spa);
4348 ASSERT(!BP_IS_EMBEDDED(bp) ||
4349 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4352 if (!BP_IS_EMBEDDED(bp)) {
4354 * Embedded BP's have no DVA and require no I/O to "read".
4355 * Create an anonymous arc buf to back it.
4357 hdr = buf_hash_find(guid, bp, &hash_lock);
4360 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4362 *arc_flags |= ARC_FLAG_CACHED;
4364 if (HDR_IO_IN_PROGRESS(hdr)) {
4366 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4367 priority == ZIO_PRIORITY_SYNC_READ) {
4369 * This sync read must wait for an
4370 * in-progress async read (e.g. a predictive
4371 * prefetch). Async reads are queued
4372 * separately at the vdev_queue layer, so
4373 * this is a form of priority inversion.
4374 * Ideally, we would "inherit" the demand
4375 * i/o's priority by moving the i/o from
4376 * the async queue to the synchronous queue,
4377 * but there is currently no mechanism to do
4378 * so. Track this so that we can evaluate
4379 * the magnitude of this potential performance
4382 * Note that if the prefetch i/o is already
4383 * active (has been issued to the device),
4384 * the prefetch improved performance, because
4385 * we issued it sooner than we would have
4386 * without the prefetch.
4388 DTRACE_PROBE1(arc__sync__wait__for__async,
4389 arc_buf_hdr_t *, hdr);
4390 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4392 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4393 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4396 if (*arc_flags & ARC_FLAG_WAIT) {
4397 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4398 mutex_exit(hash_lock);
4401 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4404 arc_callback_t *acb = NULL;
4406 acb = kmem_zalloc(sizeof (arc_callback_t),
4408 acb->acb_done = done;
4409 acb->acb_private = private;
4411 acb->acb_zio_dummy = zio_null(pio,
4412 spa, NULL, NULL, NULL, zio_flags);
4414 ASSERT(acb->acb_done != NULL);
4415 acb->acb_next = hdr->b_l1hdr.b_acb;
4416 hdr->b_l1hdr.b_acb = acb;
4417 add_reference(hdr, hash_lock, private);
4418 mutex_exit(hash_lock);
4421 mutex_exit(hash_lock);
4425 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4426 hdr->b_l1hdr.b_state == arc_mfu);
4429 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4431 * This is a demand read which does not have to
4432 * wait for i/o because we did a predictive
4433 * prefetch i/o for it, which has completed.
4436 arc__demand__hit__predictive__prefetch,
4437 arc_buf_hdr_t *, hdr);
4439 arcstat_demand_hit_predictive_prefetch);
4440 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4442 add_reference(hdr, hash_lock, private);
4444 * If this block is already in use, create a new
4445 * copy of the data so that we will be guaranteed
4446 * that arc_release() will always succeed.
4448 buf = hdr->b_l1hdr.b_buf;
4450 ASSERT(buf->b_data);
4451 if (HDR_BUF_AVAILABLE(hdr)) {
4452 ASSERT(buf->b_efunc == NULL);
4453 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4455 buf = arc_buf_clone(buf);
4458 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4459 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4460 hdr->b_flags |= ARC_FLAG_PREFETCH;
4462 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4463 arc_access(hdr, hash_lock);
4464 if (*arc_flags & ARC_FLAG_L2CACHE)
4465 hdr->b_flags |= ARC_FLAG_L2CACHE;
4466 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4467 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4468 mutex_exit(hash_lock);
4469 ARCSTAT_BUMP(arcstat_hits);
4470 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4471 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4472 data, metadata, hits);
4475 done(NULL, buf, private);
4477 uint64_t size = BP_GET_LSIZE(bp);
4478 arc_callback_t *acb;
4481 boolean_t devw = B_FALSE;
4482 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4483 int32_t b_asize = 0;
4486 /* this block is not in the cache */
4487 arc_buf_hdr_t *exists = NULL;
4488 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4489 buf = arc_buf_alloc(spa, size, private, type);
4491 if (!BP_IS_EMBEDDED(bp)) {
4492 hdr->b_dva = *BP_IDENTITY(bp);
4493 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4494 exists = buf_hash_insert(hdr, &hash_lock);
4496 if (exists != NULL) {
4497 /* somebody beat us to the hash insert */
4498 mutex_exit(hash_lock);
4499 buf_discard_identity(hdr);
4500 (void) arc_buf_remove_ref(buf, private);
4501 goto top; /* restart the IO request */
4505 * If there is a callback, we pass our reference to
4506 * it; otherwise we remove our reference.
4509 (void) remove_reference(hdr, hash_lock,
4512 if (*arc_flags & ARC_FLAG_PREFETCH)
4513 hdr->b_flags |= ARC_FLAG_PREFETCH;
4514 if (*arc_flags & ARC_FLAG_L2CACHE)
4515 hdr->b_flags |= ARC_FLAG_L2CACHE;
4516 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4517 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4518 if (BP_GET_LEVEL(bp) > 0)
4519 hdr->b_flags |= ARC_FLAG_INDIRECT;
4522 * This block is in the ghost cache. If it was L2-only
4523 * (and thus didn't have an L1 hdr), we realloc the
4524 * header to add an L1 hdr.
4526 if (!HDR_HAS_L1HDR(hdr)) {
4527 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4531 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4532 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4533 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4534 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4537 * If there is a callback, we pass a reference to it.
4540 add_reference(hdr, hash_lock, private);
4541 if (*arc_flags & ARC_FLAG_PREFETCH)
4542 hdr->b_flags |= ARC_FLAG_PREFETCH;
4543 if (*arc_flags & ARC_FLAG_L2CACHE)
4544 hdr->b_flags |= ARC_FLAG_L2CACHE;
4545 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4546 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4547 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4550 buf->b_efunc = NULL;
4551 buf->b_private = NULL;
4553 hdr->b_l1hdr.b_buf = buf;
4554 ASSERT0(hdr->b_l1hdr.b_datacnt);
4555 hdr->b_l1hdr.b_datacnt = 1;
4556 arc_get_data_buf(buf);
4557 arc_access(hdr, hash_lock);
4560 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4561 hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
4562 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4564 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4565 acb->acb_done = done;
4566 acb->acb_private = private;
4568 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4569 hdr->b_l1hdr.b_acb = acb;
4570 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4572 if (HDR_HAS_L2HDR(hdr) &&
4573 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4574 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4575 addr = hdr->b_l2hdr.b_daddr;
4576 b_compress = hdr->b_l2hdr.b_compress;
4577 b_asize = hdr->b_l2hdr.b_asize;
4579 * Lock out device removal.
4581 if (vdev_is_dead(vd) ||
4582 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4586 if (hash_lock != NULL)
4587 mutex_exit(hash_lock);
4590 * At this point, we have a level 1 cache miss. Try again in
4591 * L2ARC if possible.
4593 ASSERT3U(hdr->b_size, ==, size);
4594 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4595 uint64_t, size, zbookmark_phys_t *, zb);
4596 ARCSTAT_BUMP(arcstat_misses);
4597 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4598 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4599 data, metadata, misses);
4601 curthread->td_ru.ru_inblock++;
4604 if (priority == ZIO_PRIORITY_ASYNC_READ)
4605 hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4607 hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4609 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4611 * Read from the L2ARC if the following are true:
4612 * 1. The L2ARC vdev was previously cached.
4613 * 2. This buffer still has L2ARC metadata.
4614 * 3. This buffer isn't currently writing to the L2ARC.
4615 * 4. The L2ARC entry wasn't evicted, which may
4616 * also have invalidated the vdev.
4617 * 5. This isn't prefetch and l2arc_noprefetch is set.
4619 if (HDR_HAS_L2HDR(hdr) &&
4620 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4621 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4622 l2arc_read_callback_t *cb;
4625 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4626 ARCSTAT_BUMP(arcstat_l2_hits);
4628 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4630 cb->l2rcb_buf = buf;
4631 cb->l2rcb_spa = spa;
4634 cb->l2rcb_flags = zio_flags;
4635 cb->l2rcb_compress = b_compress;
4636 if (b_asize > hdr->b_size) {
4637 ASSERT3U(b_compress, ==,
4639 b_data = zio_data_buf_alloc(b_asize);
4640 cb->l2rcb_data = b_data;
4642 b_data = buf->b_data;
4645 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4646 addr + size < vd->vdev_psize -
4647 VDEV_LABEL_END_SIZE);
4650 * l2arc read. The SCL_L2ARC lock will be
4651 * released by l2arc_read_done().
4652 * Issue a null zio if the underlying buffer
4653 * was squashed to zero size by compression.
4655 if (b_compress == ZIO_COMPRESS_EMPTY) {
4656 ASSERT3U(b_asize, ==, 0);
4657 rzio = zio_null(pio, spa, vd,
4658 l2arc_read_done, cb,
4659 zio_flags | ZIO_FLAG_DONT_CACHE |
4661 ZIO_FLAG_DONT_PROPAGATE |
4662 ZIO_FLAG_DONT_RETRY);
4664 rzio = zio_read_phys(pio, vd, addr,
4667 l2arc_read_done, cb, priority,
4668 zio_flags | ZIO_FLAG_DONT_CACHE |
4670 ZIO_FLAG_DONT_PROPAGATE |
4671 ZIO_FLAG_DONT_RETRY, B_FALSE);
4673 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4675 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4677 if (*arc_flags & ARC_FLAG_NOWAIT) {
4682 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4683 if (zio_wait(rzio) == 0)
4686 /* l2arc read error; goto zio_read() */
4688 DTRACE_PROBE1(l2arc__miss,
4689 arc_buf_hdr_t *, hdr);
4690 ARCSTAT_BUMP(arcstat_l2_misses);
4691 if (HDR_L2_WRITING(hdr))
4692 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4693 spa_config_exit(spa, SCL_L2ARC, vd);
4697 spa_config_exit(spa, SCL_L2ARC, vd);
4698 if (l2arc_ndev != 0) {
4699 DTRACE_PROBE1(l2arc__miss,
4700 arc_buf_hdr_t *, hdr);
4701 ARCSTAT_BUMP(arcstat_l2_misses);
4705 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4706 arc_read_done, buf, priority, zio_flags, zb);
4708 if (*arc_flags & ARC_FLAG_WAIT)
4709 return (zio_wait(rzio));
4711 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4718 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4720 ASSERT(buf->b_hdr != NULL);
4721 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4722 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4724 ASSERT(buf->b_efunc == NULL);
4725 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4727 buf->b_efunc = func;
4728 buf->b_private = private;
4732 * Notify the arc that a block was freed, and thus will never be used again.
4735 arc_freed(spa_t *spa, const blkptr_t *bp)
4738 kmutex_t *hash_lock;
4739 uint64_t guid = spa_load_guid(spa);
4741 ASSERT(!BP_IS_EMBEDDED(bp));
4743 hdr = buf_hash_find(guid, bp, &hash_lock);
4746 if (HDR_BUF_AVAILABLE(hdr)) {
4747 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4748 add_reference(hdr, hash_lock, FTAG);
4749 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4750 mutex_exit(hash_lock);
4752 arc_release(buf, FTAG);
4753 (void) arc_buf_remove_ref(buf, FTAG);
4755 mutex_exit(hash_lock);
4761 * Clear the user eviction callback set by arc_set_callback(), first calling
4762 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4763 * clearing the callback may result in the arc_buf being destroyed. However,
4764 * it will not result in the *last* arc_buf being destroyed, hence the data
4765 * will remain cached in the ARC. We make a copy of the arc buffer here so
4766 * that we can process the callback without holding any locks.
4768 * It's possible that the callback is already in the process of being cleared
4769 * by another thread. In this case we can not clear the callback.
4771 * Returns B_TRUE if the callback was successfully called and cleared.
4774 arc_clear_callback(arc_buf_t *buf)
4777 kmutex_t *hash_lock;
4778 arc_evict_func_t *efunc = buf->b_efunc;
4779 void *private = buf->b_private;
4781 mutex_enter(&buf->b_evict_lock);
4785 * We are in arc_do_user_evicts().
4787 ASSERT(buf->b_data == NULL);
4788 mutex_exit(&buf->b_evict_lock);
4790 } else if (buf->b_data == NULL) {
4792 * We are on the eviction list; process this buffer now
4793 * but let arc_do_user_evicts() do the reaping.
4795 buf->b_efunc = NULL;
4796 mutex_exit(&buf->b_evict_lock);
4797 VERIFY0(efunc(private));
4800 hash_lock = HDR_LOCK(hdr);
4801 mutex_enter(hash_lock);
4803 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4805 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4806 hdr->b_l1hdr.b_datacnt);
4807 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4808 hdr->b_l1hdr.b_state == arc_mfu);
4810 buf->b_efunc = NULL;
4811 buf->b_private = NULL;
4813 if (hdr->b_l1hdr.b_datacnt > 1) {
4814 mutex_exit(&buf->b_evict_lock);
4815 arc_buf_destroy(buf, TRUE);
4817 ASSERT(buf == hdr->b_l1hdr.b_buf);
4818 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4819 mutex_exit(&buf->b_evict_lock);
4822 mutex_exit(hash_lock);
4823 VERIFY0(efunc(private));
4828 * Release this buffer from the cache, making it an anonymous buffer. This
4829 * must be done after a read and prior to modifying the buffer contents.
4830 * If the buffer has more than one reference, we must make
4831 * a new hdr for the buffer.
4834 arc_release(arc_buf_t *buf, void *tag)
4836 arc_buf_hdr_t *hdr = buf->b_hdr;
4839 * It would be nice to assert that if it's DMU metadata (level >
4840 * 0 || it's the dnode file), then it must be syncing context.
4841 * But we don't know that information at this level.
4844 mutex_enter(&buf->b_evict_lock);
4846 ASSERT(HDR_HAS_L1HDR(hdr));
4849 * We don't grab the hash lock prior to this check, because if
4850 * the buffer's header is in the arc_anon state, it won't be
4851 * linked into the hash table.
4853 if (hdr->b_l1hdr.b_state == arc_anon) {
4854 mutex_exit(&buf->b_evict_lock);
4855 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4856 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4857 ASSERT(!HDR_HAS_L2HDR(hdr));
4858 ASSERT(BUF_EMPTY(hdr));
4859 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4860 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4861 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4863 ASSERT3P(buf->b_efunc, ==, NULL);
4864 ASSERT3P(buf->b_private, ==, NULL);
4866 hdr->b_l1hdr.b_arc_access = 0;
4872 kmutex_t *hash_lock = HDR_LOCK(hdr);
4873 mutex_enter(hash_lock);
4876 * This assignment is only valid as long as the hash_lock is
4877 * held, we must be careful not to reference state or the
4878 * b_state field after dropping the lock.
4880 arc_state_t *state = hdr->b_l1hdr.b_state;
4881 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4882 ASSERT3P(state, !=, arc_anon);
4884 /* this buffer is not on any list */
4885 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4887 if (HDR_HAS_L2HDR(hdr)) {
4888 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4891 * We have to recheck this conditional again now that
4892 * we're holding the l2ad_mtx to prevent a race with
4893 * another thread which might be concurrently calling
4894 * l2arc_evict(). In that case, l2arc_evict() might have
4895 * destroyed the header's L2 portion as we were waiting
4896 * to acquire the l2ad_mtx.
4898 if (HDR_HAS_L2HDR(hdr)) {
4900 arc_hdr_l2hdr_destroy(hdr);
4903 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4907 * Do we have more than one buf?
4909 if (hdr->b_l1hdr.b_datacnt > 1) {
4910 arc_buf_hdr_t *nhdr;
4912 uint64_t blksz = hdr->b_size;
4913 uint64_t spa = hdr->b_spa;
4914 arc_buf_contents_t type = arc_buf_type(hdr);
4915 uint32_t flags = hdr->b_flags;
4917 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4919 * Pull the data off of this hdr and attach it to
4920 * a new anonymous hdr.
4922 (void) remove_reference(hdr, hash_lock, tag);
4923 bufp = &hdr->b_l1hdr.b_buf;
4924 while (*bufp != buf)
4925 bufp = &(*bufp)->b_next;
4926 *bufp = buf->b_next;
4929 ASSERT3P(state, !=, arc_l2c_only);
4931 (void) refcount_remove_many(
4932 &state->arcs_size, hdr->b_size, buf);
4934 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4935 ASSERT3P(state, !=, arc_l2c_only);
4936 uint64_t *size = &state->arcs_lsize[type];
4937 ASSERT3U(*size, >=, hdr->b_size);
4938 atomic_add_64(size, -hdr->b_size);
4942 * We're releasing a duplicate user data buffer, update
4943 * our statistics accordingly.
4945 if (HDR_ISTYPE_DATA(hdr)) {
4946 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4947 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4950 hdr->b_l1hdr.b_datacnt -= 1;
4951 arc_cksum_verify(buf);
4953 arc_buf_unwatch(buf);
4956 mutex_exit(hash_lock);
4958 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4959 nhdr->b_size = blksz;
4962 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4963 nhdr->b_flags |= arc_bufc_to_flags(type);
4964 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4966 nhdr->b_l1hdr.b_buf = buf;
4967 nhdr->b_l1hdr.b_datacnt = 1;
4968 nhdr->b_l1hdr.b_state = arc_anon;
4969 nhdr->b_l1hdr.b_arc_access = 0;
4970 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4971 nhdr->b_freeze_cksum = NULL;
4973 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4975 mutex_exit(&buf->b_evict_lock);
4976 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4978 mutex_exit(&buf->b_evict_lock);
4979 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4980 /* protected by hash lock, or hdr is on arc_anon */
4981 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4982 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4983 arc_change_state(arc_anon, hdr, hash_lock);
4984 hdr->b_l1hdr.b_arc_access = 0;
4985 mutex_exit(hash_lock);
4987 buf_discard_identity(hdr);
4990 buf->b_efunc = NULL;
4991 buf->b_private = NULL;
4995 arc_released(arc_buf_t *buf)
4999 mutex_enter(&buf->b_evict_lock);
5000 released = (buf->b_data != NULL &&
5001 buf->b_hdr->b_l1hdr.b_state == arc_anon);
5002 mutex_exit(&buf->b_evict_lock);
5008 arc_referenced(arc_buf_t *buf)
5012 mutex_enter(&buf->b_evict_lock);
5013 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5014 mutex_exit(&buf->b_evict_lock);
5015 return (referenced);
5020 arc_write_ready(zio_t *zio)
5022 arc_write_callback_t *callback = zio->io_private;
5023 arc_buf_t *buf = callback->awcb_buf;
5024 arc_buf_hdr_t *hdr = buf->b_hdr;
5026 ASSERT(HDR_HAS_L1HDR(hdr));
5027 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5028 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5029 callback->awcb_ready(zio, buf, callback->awcb_private);
5032 * If the IO is already in progress, then this is a re-write
5033 * attempt, so we need to thaw and re-compute the cksum.
5034 * It is the responsibility of the callback to handle the
5035 * accounting for any re-write attempt.
5037 if (HDR_IO_IN_PROGRESS(hdr)) {
5038 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
5039 if (hdr->b_freeze_cksum != NULL) {
5040 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
5041 hdr->b_freeze_cksum = NULL;
5043 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
5045 arc_cksum_compute(buf, B_FALSE);
5046 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
5050 arc_write_children_ready(zio_t *zio)
5052 arc_write_callback_t *callback = zio->io_private;
5053 arc_buf_t *buf = callback->awcb_buf;
5055 callback->awcb_children_ready(zio, buf, callback->awcb_private);
5059 * The SPA calls this callback for each physical write that happens on behalf
5060 * of a logical write. See the comment in dbuf_write_physdone() for details.
5063 arc_write_physdone(zio_t *zio)
5065 arc_write_callback_t *cb = zio->io_private;
5066 if (cb->awcb_physdone != NULL)
5067 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
5071 arc_write_done(zio_t *zio)
5073 arc_write_callback_t *callback = zio->io_private;
5074 arc_buf_t *buf = callback->awcb_buf;
5075 arc_buf_hdr_t *hdr = buf->b_hdr;
5077 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5079 if (zio->io_error == 0) {
5080 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5081 buf_discard_identity(hdr);
5083 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5084 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5087 ASSERT(BUF_EMPTY(hdr));
5091 * If the block to be written was all-zero or compressed enough to be
5092 * embedded in the BP, no write was performed so there will be no
5093 * dva/birth/checksum. The buffer must therefore remain anonymous
5096 if (!BUF_EMPTY(hdr)) {
5097 arc_buf_hdr_t *exists;
5098 kmutex_t *hash_lock;
5100 ASSERT(zio->io_error == 0);
5102 arc_cksum_verify(buf);
5104 exists = buf_hash_insert(hdr, &hash_lock);
5105 if (exists != NULL) {
5107 * This can only happen if we overwrite for
5108 * sync-to-convergence, because we remove
5109 * buffers from the hash table when we arc_free().
5111 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5112 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5113 panic("bad overwrite, hdr=%p exists=%p",
5114 (void *)hdr, (void *)exists);
5115 ASSERT(refcount_is_zero(
5116 &exists->b_l1hdr.b_refcnt));
5117 arc_change_state(arc_anon, exists, hash_lock);
5118 mutex_exit(hash_lock);
5119 arc_hdr_destroy(exists);
5120 exists = buf_hash_insert(hdr, &hash_lock);
5121 ASSERT3P(exists, ==, NULL);
5122 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5124 ASSERT(zio->io_prop.zp_nopwrite);
5125 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5126 panic("bad nopwrite, hdr=%p exists=%p",
5127 (void *)hdr, (void *)exists);
5130 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5131 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5132 ASSERT(BP_GET_DEDUP(zio->io_bp));
5133 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5136 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5137 /* if it's not anon, we are doing a scrub */
5138 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5139 arc_access(hdr, hash_lock);
5140 mutex_exit(hash_lock);
5142 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5145 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5146 callback->awcb_done(zio, buf, callback->awcb_private);
5148 kmem_free(callback, sizeof (arc_write_callback_t));
5152 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
5153 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
5154 const zio_prop_t *zp, arc_done_func_t *ready,
5155 arc_done_func_t *children_ready, arc_done_func_t *physdone,
5156 arc_done_func_t *done, void *private, zio_priority_t priority,
5157 int zio_flags, const zbookmark_phys_t *zb)
5159 arc_buf_hdr_t *hdr = buf->b_hdr;
5160 arc_write_callback_t *callback;
5163 ASSERT(ready != NULL);
5164 ASSERT(done != NULL);
5165 ASSERT(!HDR_IO_ERROR(hdr));
5166 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5167 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5168 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5170 hdr->b_flags |= ARC_FLAG_L2CACHE;
5172 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
5173 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5174 callback->awcb_ready = ready;
5175 callback->awcb_children_ready = children_ready;
5176 callback->awcb_physdone = physdone;
5177 callback->awcb_done = done;
5178 callback->awcb_private = private;
5179 callback->awcb_buf = buf;
5181 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
5183 (children_ready != NULL) ? arc_write_children_ready : NULL,
5184 arc_write_physdone, arc_write_done, callback,
5185 priority, zio_flags, zb);
5191 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5194 uint64_t available_memory = ptob(freemem);
5195 static uint64_t page_load = 0;
5196 static uint64_t last_txg = 0;
5198 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5200 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5203 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5206 if (txg > last_txg) {
5211 * If we are in pageout, we know that memory is already tight,
5212 * the arc is already going to be evicting, so we just want to
5213 * continue to let page writes occur as quickly as possible.
5215 if (curproc == pageproc) {
5216 if (page_load > MAX(ptob(minfree), available_memory) / 4)
5217 return (SET_ERROR(ERESTART));
5218 /* Note: reserve is inflated, so we deflate */
5219 page_load += reserve / 8;
5221 } else if (page_load > 0 && arc_reclaim_needed()) {
5222 /* memory is low, delay before restarting */
5223 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5224 return (SET_ERROR(EAGAIN));
5232 arc_tempreserve_clear(uint64_t reserve)
5234 atomic_add_64(&arc_tempreserve, -reserve);
5235 ASSERT((int64_t)arc_tempreserve >= 0);
5239 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5244 if (reserve > arc_c/4 && !arc_no_grow) {
5245 arc_c = MIN(arc_c_max, reserve * 4);
5246 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5248 if (reserve > arc_c)
5249 return (SET_ERROR(ENOMEM));
5252 * Don't count loaned bufs as in flight dirty data to prevent long
5253 * network delays from blocking transactions that are ready to be
5254 * assigned to a txg.
5256 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5257 arc_loaned_bytes), 0);
5260 * Writes will, almost always, require additional memory allocations
5261 * in order to compress/encrypt/etc the data. We therefore need to
5262 * make sure that there is sufficient available memory for this.
5264 error = arc_memory_throttle(reserve, txg);
5269 * Throttle writes when the amount of dirty data in the cache
5270 * gets too large. We try to keep the cache less than half full
5271 * of dirty blocks so that our sync times don't grow too large.
5272 * Note: if two requests come in concurrently, we might let them
5273 * both succeed, when one of them should fail. Not a huge deal.
5276 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5277 anon_size > arc_c / 4) {
5278 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5279 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5280 arc_tempreserve>>10,
5281 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5282 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5283 reserve>>10, arc_c>>10);
5284 return (SET_ERROR(ERESTART));
5286 atomic_add_64(&arc_tempreserve, reserve);
5291 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5292 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5294 size->value.ui64 = refcount_count(&state->arcs_size);
5295 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5296 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5300 arc_kstat_update(kstat_t *ksp, int rw)
5302 arc_stats_t *as = ksp->ks_data;
5304 if (rw == KSTAT_WRITE) {
5307 arc_kstat_update_state(arc_anon,
5308 &as->arcstat_anon_size,
5309 &as->arcstat_anon_evictable_data,
5310 &as->arcstat_anon_evictable_metadata);
5311 arc_kstat_update_state(arc_mru,
5312 &as->arcstat_mru_size,
5313 &as->arcstat_mru_evictable_data,
5314 &as->arcstat_mru_evictable_metadata);
5315 arc_kstat_update_state(arc_mru_ghost,
5316 &as->arcstat_mru_ghost_size,
5317 &as->arcstat_mru_ghost_evictable_data,
5318 &as->arcstat_mru_ghost_evictable_metadata);
5319 arc_kstat_update_state(arc_mfu,
5320 &as->arcstat_mfu_size,
5321 &as->arcstat_mfu_evictable_data,
5322 &as->arcstat_mfu_evictable_metadata);
5323 arc_kstat_update_state(arc_mfu_ghost,
5324 &as->arcstat_mfu_ghost_size,
5325 &as->arcstat_mfu_ghost_evictable_data,
5326 &as->arcstat_mfu_ghost_evictable_metadata);
5333 * This function *must* return indices evenly distributed between all
5334 * sublists of the multilist. This is needed due to how the ARC eviction
5335 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5336 * distributed between all sublists and uses this assumption when
5337 * deciding which sublist to evict from and how much to evict from it.
5340 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5342 arc_buf_hdr_t *hdr = obj;
5345 * We rely on b_dva to generate evenly distributed index
5346 * numbers using buf_hash below. So, as an added precaution,
5347 * let's make sure we never add empty buffers to the arc lists.
5349 ASSERT(!BUF_EMPTY(hdr));
5352 * The assumption here, is the hash value for a given
5353 * arc_buf_hdr_t will remain constant throughout it's lifetime
5354 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5355 * Thus, we don't need to store the header's sublist index
5356 * on insertion, as this index can be recalculated on removal.
5358 * Also, the low order bits of the hash value are thought to be
5359 * distributed evenly. Otherwise, in the case that the multilist
5360 * has a power of two number of sublists, each sublists' usage
5361 * would not be evenly distributed.
5363 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5364 multilist_get_num_sublists(ml));
5368 static eventhandler_tag arc_event_lowmem = NULL;
5371 arc_lowmem(void *arg __unused, int howto __unused)
5374 mutex_enter(&arc_reclaim_lock);
5375 /* XXX: Memory deficit should be passed as argument. */
5376 needfree = btoc(arc_c >> arc_shrink_shift);
5377 DTRACE_PROBE(arc__needfree);
5378 cv_signal(&arc_reclaim_thread_cv);
5381 * It is unsafe to block here in arbitrary threads, because we can come
5382 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5383 * with ARC reclaim thread.
5385 if (curproc == pageproc)
5386 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5387 mutex_exit(&arc_reclaim_lock);
5394 int i, prefetch_tunable_set = 0;
5396 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5397 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5398 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5400 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5401 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5403 /* Convert seconds to clock ticks */
5404 arc_min_prefetch_lifespan = 1 * hz;
5406 /* Start out with 1/8 of all memory */
5407 arc_c = kmem_size() / 8;
5412 * On architectures where the physical memory can be larger
5413 * than the addressable space (intel in 32-bit mode), we may
5414 * need to limit the cache to 1/8 of VM size.
5416 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5418 #endif /* illumos */
5419 /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
5420 arc_c_min = MAX(arc_c / 4, arc_abs_min);
5421 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5422 if (arc_c * 8 >= 1 << 30)
5423 arc_c_max = (arc_c * 8) - (1 << 30);
5425 arc_c_max = arc_c_min;
5426 arc_c_max = MAX(arc_c * 5, arc_c_max);
5429 * In userland, there's only the memory pressure that we artificially
5430 * create (see arc_available_memory()). Don't let arc_c get too
5431 * small, because it can cause transactions to be larger than
5432 * arc_c, causing arc_tempreserve_space() to fail.
5435 arc_c_min = arc_c_max / 2;
5440 * Allow the tunables to override our calculations if they are
5443 if (zfs_arc_max > arc_abs_min && zfs_arc_max < kmem_size())
5444 arc_c_max = zfs_arc_max;
5445 if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
5446 arc_c_min = zfs_arc_min;
5450 arc_p = (arc_c >> 1);
5452 /* limit meta-data to 1/4 of the arc capacity */
5453 arc_meta_limit = arc_c_max / 4;
5455 /* Allow the tunable to override if it is reasonable */
5456 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5457 arc_meta_limit = zfs_arc_meta_limit;
5459 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5460 arc_c_min = arc_meta_limit / 2;
5462 if (zfs_arc_meta_min > 0) {
5463 arc_meta_min = zfs_arc_meta_min;
5465 arc_meta_min = arc_c_min / 2;
5468 if (zfs_arc_grow_retry > 0)
5469 arc_grow_retry = zfs_arc_grow_retry;
5471 if (zfs_arc_shrink_shift > 0)
5472 arc_shrink_shift = zfs_arc_shrink_shift;
5475 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5477 if (arc_no_grow_shift >= arc_shrink_shift)
5478 arc_no_grow_shift = arc_shrink_shift - 1;
5480 if (zfs_arc_p_min_shift > 0)
5481 arc_p_min_shift = zfs_arc_p_min_shift;
5483 if (zfs_arc_num_sublists_per_state < 1)
5484 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5486 /* if kmem_flags are set, lets try to use less memory */
5487 if (kmem_debugging())
5489 if (arc_c < arc_c_min)
5492 zfs_arc_min = arc_c_min;
5493 zfs_arc_max = arc_c_max;
5495 arc_anon = &ARC_anon;
5497 arc_mru_ghost = &ARC_mru_ghost;
5499 arc_mfu_ghost = &ARC_mfu_ghost;
5500 arc_l2c_only = &ARC_l2c_only;
5503 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5504 sizeof (arc_buf_hdr_t),
5505 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5506 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5507 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5508 sizeof (arc_buf_hdr_t),
5509 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5510 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5511 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5512 sizeof (arc_buf_hdr_t),
5513 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5514 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5515 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5516 sizeof (arc_buf_hdr_t),
5517 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5518 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5519 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5520 sizeof (arc_buf_hdr_t),
5521 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5522 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5523 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5524 sizeof (arc_buf_hdr_t),
5525 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5526 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5527 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5528 sizeof (arc_buf_hdr_t),
5529 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5530 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5531 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5532 sizeof (arc_buf_hdr_t),
5533 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5534 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5535 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5536 sizeof (arc_buf_hdr_t),
5537 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5538 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5539 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5540 sizeof (arc_buf_hdr_t),
5541 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5542 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5544 refcount_create(&arc_anon->arcs_size);
5545 refcount_create(&arc_mru->arcs_size);
5546 refcount_create(&arc_mru_ghost->arcs_size);
5547 refcount_create(&arc_mfu->arcs_size);
5548 refcount_create(&arc_mfu_ghost->arcs_size);
5549 refcount_create(&arc_l2c_only->arcs_size);
5553 arc_reclaim_thread_exit = FALSE;
5554 arc_user_evicts_thread_exit = FALSE;
5555 arc_eviction_list = NULL;
5556 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5558 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5559 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5561 if (arc_ksp != NULL) {
5562 arc_ksp->ks_data = &arc_stats;
5563 arc_ksp->ks_update = arc_kstat_update;
5564 kstat_install(arc_ksp);
5567 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5568 TS_RUN, minclsyspri);
5571 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5572 EVENTHANDLER_PRI_FIRST);
5575 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5576 TS_RUN, minclsyspri);
5582 * Calculate maximum amount of dirty data per pool.
5584 * If it has been set by /etc/system, take that.
5585 * Otherwise, use a percentage of physical memory defined by
5586 * zfs_dirty_data_max_percent (default 10%) with a cap at
5587 * zfs_dirty_data_max_max (default 4GB).
5589 if (zfs_dirty_data_max == 0) {
5590 zfs_dirty_data_max = ptob(physmem) *
5591 zfs_dirty_data_max_percent / 100;
5592 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5593 zfs_dirty_data_max_max);
5597 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5598 prefetch_tunable_set = 1;
5601 if (prefetch_tunable_set == 0) {
5602 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5604 printf(" add \"vfs.zfs.prefetch_disable=0\" "
5605 "to /boot/loader.conf.\n");
5606 zfs_prefetch_disable = 1;
5609 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5610 prefetch_tunable_set == 0) {
5611 printf("ZFS NOTICE: Prefetch is disabled by default if less "
5612 "than 4GB of RAM is present;\n"
5613 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
5614 "to /boot/loader.conf.\n");
5615 zfs_prefetch_disable = 1;
5618 /* Warn about ZFS memory and address space requirements. */
5619 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5620 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5621 "expect unstable behavior.\n");
5623 if (kmem_size() < 512 * (1 << 20)) {
5624 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5625 "expect unstable behavior.\n");
5626 printf(" Consider tuning vm.kmem_size and "
5627 "vm.kmem_size_max\n");
5628 printf(" in /boot/loader.conf.\n");
5636 mutex_enter(&arc_reclaim_lock);
5637 arc_reclaim_thread_exit = TRUE;
5639 * The reclaim thread will set arc_reclaim_thread_exit back to
5640 * FALSE when it is finished exiting; we're waiting for that.
5642 while (arc_reclaim_thread_exit) {
5643 cv_signal(&arc_reclaim_thread_cv);
5644 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5646 mutex_exit(&arc_reclaim_lock);
5648 mutex_enter(&arc_user_evicts_lock);
5649 arc_user_evicts_thread_exit = TRUE;
5651 * The user evicts thread will set arc_user_evicts_thread_exit
5652 * to FALSE when it is finished exiting; we're waiting for that.
5654 while (arc_user_evicts_thread_exit) {
5655 cv_signal(&arc_user_evicts_cv);
5656 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5658 mutex_exit(&arc_user_evicts_lock);
5660 /* Use TRUE to ensure *all* buffers are evicted */
5661 arc_flush(NULL, TRUE);
5665 if (arc_ksp != NULL) {
5666 kstat_delete(arc_ksp);
5670 mutex_destroy(&arc_reclaim_lock);
5671 cv_destroy(&arc_reclaim_thread_cv);
5672 cv_destroy(&arc_reclaim_waiters_cv);
5674 mutex_destroy(&arc_user_evicts_lock);
5675 cv_destroy(&arc_user_evicts_cv);
5677 refcount_destroy(&arc_anon->arcs_size);
5678 refcount_destroy(&arc_mru->arcs_size);
5679 refcount_destroy(&arc_mru_ghost->arcs_size);
5680 refcount_destroy(&arc_mfu->arcs_size);
5681 refcount_destroy(&arc_mfu_ghost->arcs_size);
5682 refcount_destroy(&arc_l2c_only->arcs_size);
5684 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5685 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5686 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5687 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5688 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
5689 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5690 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5691 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5692 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5693 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
5697 ASSERT0(arc_loaned_bytes);
5700 if (arc_event_lowmem != NULL)
5701 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5708 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5709 * It uses dedicated storage devices to hold cached data, which are populated
5710 * using large infrequent writes. The main role of this cache is to boost
5711 * the performance of random read workloads. The intended L2ARC devices
5712 * include short-stroked disks, solid state disks, and other media with
5713 * substantially faster read latency than disk.
5715 * +-----------------------+
5717 * +-----------------------+
5720 * l2arc_feed_thread() arc_read()
5724 * +---------------+ |
5726 * +---------------+ |
5731 * +-------+ +-------+
5733 * | cache | | cache |
5734 * +-------+ +-------+
5735 * +=========+ .-----.
5736 * : L2ARC : |-_____-|
5737 * : devices : | Disks |
5738 * +=========+ `-_____-'
5740 * Read requests are satisfied from the following sources, in order:
5743 * 2) vdev cache of L2ARC devices
5745 * 4) vdev cache of disks
5748 * Some L2ARC device types exhibit extremely slow write performance.
5749 * To accommodate for this there are some significant differences between
5750 * the L2ARC and traditional cache design:
5752 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5753 * the ARC behave as usual, freeing buffers and placing headers on ghost
5754 * lists. The ARC does not send buffers to the L2ARC during eviction as
5755 * this would add inflated write latencies for all ARC memory pressure.
5757 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5758 * It does this by periodically scanning buffers from the eviction-end of
5759 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5760 * not already there. It scans until a headroom of buffers is satisfied,
5761 * which itself is a buffer for ARC eviction. If a compressible buffer is
5762 * found during scanning and selected for writing to an L2ARC device, we
5763 * temporarily boost scanning headroom during the next scan cycle to make
5764 * sure we adapt to compression effects (which might significantly reduce
5765 * the data volume we write to L2ARC). The thread that does this is
5766 * l2arc_feed_thread(), illustrated below; example sizes are included to
5767 * provide a better sense of ratio than this diagram:
5770 * +---------------------+----------+
5771 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5772 * +---------------------+----------+ | o L2ARC eligible
5773 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5774 * +---------------------+----------+ |
5775 * 15.9 Gbytes ^ 32 Mbytes |
5777 * l2arc_feed_thread()
5779 * l2arc write hand <--[oooo]--'
5783 * +==============================+
5784 * L2ARC dev |####|#|###|###| |####| ... |
5785 * +==============================+
5788 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5789 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5790 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5791 * safe to say that this is an uncommon case, since buffers at the end of
5792 * the ARC lists have moved there due to inactivity.
5794 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5795 * then the L2ARC simply misses copying some buffers. This serves as a
5796 * pressure valve to prevent heavy read workloads from both stalling the ARC
5797 * with waits and clogging the L2ARC with writes. This also helps prevent
5798 * the potential for the L2ARC to churn if it attempts to cache content too
5799 * quickly, such as during backups of the entire pool.
5801 * 5. After system boot and before the ARC has filled main memory, there are
5802 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5803 * lists can remain mostly static. Instead of searching from tail of these
5804 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5805 * for eligible buffers, greatly increasing its chance of finding them.
5807 * The L2ARC device write speed is also boosted during this time so that
5808 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5809 * there are no L2ARC reads, and no fear of degrading read performance
5810 * through increased writes.
5812 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5813 * the vdev queue can aggregate them into larger and fewer writes. Each
5814 * device is written to in a rotor fashion, sweeping writes through
5815 * available space then repeating.
5817 * 7. The L2ARC does not store dirty content. It never needs to flush
5818 * write buffers back to disk based storage.
5820 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5821 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5823 * The performance of the L2ARC can be tweaked by a number of tunables, which
5824 * may be necessary for different workloads:
5826 * l2arc_write_max max write bytes per interval
5827 * l2arc_write_boost extra write bytes during device warmup
5828 * l2arc_noprefetch skip caching prefetched buffers
5829 * l2arc_headroom number of max device writes to precache
5830 * l2arc_headroom_boost when we find compressed buffers during ARC
5831 * scanning, we multiply headroom by this
5832 * percentage factor for the next scan cycle,
5833 * since more compressed buffers are likely to
5835 * l2arc_feed_secs seconds between L2ARC writing
5837 * Tunables may be removed or added as future performance improvements are
5838 * integrated, and also may become zpool properties.
5840 * There are three key functions that control how the L2ARC warms up:
5842 * l2arc_write_eligible() check if a buffer is eligible to cache
5843 * l2arc_write_size() calculate how much to write
5844 * l2arc_write_interval() calculate sleep delay between writes
5846 * These three functions determine what to write, how much, and how quickly
5851 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5854 * A buffer is *not* eligible for the L2ARC if it:
5855 * 1. belongs to a different spa.
5856 * 2. is already cached on the L2ARC.
5857 * 3. has an I/O in progress (it may be an incomplete read).
5858 * 4. is flagged not eligible (zfs property).
5860 if (hdr->b_spa != spa_guid) {
5861 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5864 if (HDR_HAS_L2HDR(hdr)) {
5865 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5868 if (HDR_IO_IN_PROGRESS(hdr)) {
5869 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5872 if (!HDR_L2CACHE(hdr)) {
5873 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5881 l2arc_write_size(void)
5886 * Make sure our globals have meaningful values in case the user
5889 size = l2arc_write_max;
5891 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5892 "be greater than zero, resetting it to the default (%d)",
5894 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5897 if (arc_warm == B_FALSE)
5898 size += l2arc_write_boost;
5905 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5907 clock_t interval, next, now;
5910 * If the ARC lists are busy, increase our write rate; if the
5911 * lists are stale, idle back. This is achieved by checking
5912 * how much we previously wrote - if it was more than half of
5913 * what we wanted, schedule the next write much sooner.
5915 if (l2arc_feed_again && wrote > (wanted / 2))
5916 interval = (hz * l2arc_feed_min_ms) / 1000;
5918 interval = hz * l2arc_feed_secs;
5920 now = ddi_get_lbolt();
5921 next = MAX(now, MIN(now + interval, began + interval));
5927 * Cycle through L2ARC devices. This is how L2ARC load balances.
5928 * If a device is returned, this also returns holding the spa config lock.
5930 static l2arc_dev_t *
5931 l2arc_dev_get_next(void)
5933 l2arc_dev_t *first, *next = NULL;
5936 * Lock out the removal of spas (spa_namespace_lock), then removal
5937 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5938 * both locks will be dropped and a spa config lock held instead.
5940 mutex_enter(&spa_namespace_lock);
5941 mutex_enter(&l2arc_dev_mtx);
5943 /* if there are no vdevs, there is nothing to do */
5944 if (l2arc_ndev == 0)
5948 next = l2arc_dev_last;
5950 /* loop around the list looking for a non-faulted vdev */
5952 next = list_head(l2arc_dev_list);
5954 next = list_next(l2arc_dev_list, next);
5956 next = list_head(l2arc_dev_list);
5959 /* if we have come back to the start, bail out */
5962 else if (next == first)
5965 } while (vdev_is_dead(next->l2ad_vdev));
5967 /* if we were unable to find any usable vdevs, return NULL */
5968 if (vdev_is_dead(next->l2ad_vdev))
5971 l2arc_dev_last = next;
5974 mutex_exit(&l2arc_dev_mtx);
5977 * Grab the config lock to prevent the 'next' device from being
5978 * removed while we are writing to it.
5981 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5982 mutex_exit(&spa_namespace_lock);
5988 * Free buffers that were tagged for destruction.
5991 l2arc_do_free_on_write()
5994 l2arc_data_free_t *df, *df_prev;
5996 mutex_enter(&l2arc_free_on_write_mtx);
5997 buflist = l2arc_free_on_write;
5999 for (df = list_tail(buflist); df; df = df_prev) {
6000 df_prev = list_prev(buflist, df);
6001 ASSERT(df->l2df_data != NULL);
6002 ASSERT(df->l2df_func != NULL);
6003 df->l2df_func(df->l2df_data, df->l2df_size);
6004 list_remove(buflist, df);
6005 kmem_free(df, sizeof (l2arc_data_free_t));
6008 mutex_exit(&l2arc_free_on_write_mtx);
6012 * A write to a cache device has completed. Update all headers to allow
6013 * reads from these buffers to begin.
6016 l2arc_write_done(zio_t *zio)
6018 l2arc_write_callback_t *cb;
6021 arc_buf_hdr_t *head, *hdr, *hdr_prev;
6022 kmutex_t *hash_lock;
6023 int64_t bytes_dropped = 0;
6025 cb = zio->io_private;
6027 dev = cb->l2wcb_dev;
6028 ASSERT(dev != NULL);
6029 head = cb->l2wcb_head;
6030 ASSERT(head != NULL);
6031 buflist = &dev->l2ad_buflist;
6032 ASSERT(buflist != NULL);
6033 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6034 l2arc_write_callback_t *, cb);
6036 if (zio->io_error != 0)
6037 ARCSTAT_BUMP(arcstat_l2_writes_error);
6040 * All writes completed, or an error was hit.
6043 mutex_enter(&dev->l2ad_mtx);
6044 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
6045 hdr_prev = list_prev(buflist, hdr);
6047 hash_lock = HDR_LOCK(hdr);
6050 * We cannot use mutex_enter or else we can deadlock
6051 * with l2arc_write_buffers (due to swapping the order
6052 * the hash lock and l2ad_mtx are taken).
6054 if (!mutex_tryenter(hash_lock)) {
6056 * Missed the hash lock. We must retry so we
6057 * don't leave the ARC_FLAG_L2_WRITING bit set.
6059 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6062 * We don't want to rescan the headers we've
6063 * already marked as having been written out, so
6064 * we reinsert the head node so we can pick up
6065 * where we left off.
6067 list_remove(buflist, head);
6068 list_insert_after(buflist, hdr, head);
6070 mutex_exit(&dev->l2ad_mtx);
6073 * We wait for the hash lock to become available
6074 * to try and prevent busy waiting, and increase
6075 * the chance we'll be able to acquire the lock
6076 * the next time around.
6078 mutex_enter(hash_lock);
6079 mutex_exit(hash_lock);
6084 * We could not have been moved into the arc_l2c_only
6085 * state while in-flight due to our ARC_FLAG_L2_WRITING
6086 * bit being set. Let's just ensure that's being enforced.
6088 ASSERT(HDR_HAS_L1HDR(hdr));
6091 * We may have allocated a buffer for L2ARC compression,
6092 * we must release it to avoid leaking this data.
6094 l2arc_release_cdata_buf(hdr);
6096 if (zio->io_error != 0) {
6098 * Error - drop L2ARC entry.
6100 list_remove(buflist, hdr);
6102 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
6104 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
6105 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
6107 bytes_dropped += hdr->b_l2hdr.b_asize;
6108 (void) refcount_remove_many(&dev->l2ad_alloc,
6109 hdr->b_l2hdr.b_asize, hdr);
6113 * Allow ARC to begin reads and ghost list evictions to
6116 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
6118 mutex_exit(hash_lock);
6121 atomic_inc_64(&l2arc_writes_done);
6122 list_remove(buflist, head);
6123 ASSERT(!HDR_HAS_L1HDR(head));
6124 kmem_cache_free(hdr_l2only_cache, head);
6125 mutex_exit(&dev->l2ad_mtx);
6127 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6129 l2arc_do_free_on_write();
6131 kmem_free(cb, sizeof (l2arc_write_callback_t));
6135 * A read to a cache device completed. Validate buffer contents before
6136 * handing over to the regular ARC routines.
6139 l2arc_read_done(zio_t *zio)
6141 l2arc_read_callback_t *cb;
6144 kmutex_t *hash_lock;
6147 ASSERT(zio->io_vd != NULL);
6148 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6150 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6152 cb = zio->io_private;
6154 buf = cb->l2rcb_buf;
6155 ASSERT(buf != NULL);
6157 hash_lock = HDR_LOCK(buf->b_hdr);
6158 mutex_enter(hash_lock);
6160 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6163 * If the data was read into a temporary buffer,
6164 * move it and free the buffer.
6166 if (cb->l2rcb_data != NULL) {
6167 ASSERT3U(hdr->b_size, <, zio->io_size);
6168 ASSERT3U(cb->l2rcb_compress, ==, ZIO_COMPRESS_OFF);
6169 if (zio->io_error == 0)
6170 bcopy(cb->l2rcb_data, buf->b_data, hdr->b_size);
6173 * The following must be done regardless of whether
6174 * there was an error:
6175 * - free the temporary buffer
6176 * - point zio to the real ARC buffer
6177 * - set zio size accordingly
6178 * These are required because zio is either re-used for
6179 * an I/O of the block in the case of the error
6180 * or the zio is passed to arc_read_done() and it
6183 zio_data_buf_free(cb->l2rcb_data, zio->io_size);
6184 zio->io_size = zio->io_orig_size = hdr->b_size;
6185 zio->io_data = zio->io_orig_data = buf->b_data;
6189 * If the buffer was compressed, decompress it first.
6191 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
6192 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6193 ASSERT(zio->io_data != NULL);
6194 ASSERT3U(zio->io_size, ==, hdr->b_size);
6195 ASSERT3U(BP_GET_LSIZE(&cb->l2rcb_bp), ==, hdr->b_size);
6198 * Check this survived the L2ARC journey.
6200 equal = arc_cksum_equal(buf);
6201 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6202 mutex_exit(hash_lock);
6203 zio->io_private = buf;
6204 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6205 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6208 mutex_exit(hash_lock);
6210 * Buffer didn't survive caching. Increment stats and
6211 * reissue to the original storage device.
6213 if (zio->io_error != 0) {
6214 ARCSTAT_BUMP(arcstat_l2_io_error);
6216 zio->io_error = SET_ERROR(EIO);
6219 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6222 * If there's no waiter, issue an async i/o to the primary
6223 * storage now. If there *is* a waiter, the caller must
6224 * issue the i/o in a context where it's OK to block.
6226 if (zio->io_waiter == NULL) {
6227 zio_t *pio = zio_unique_parent(zio);
6229 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6231 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6232 buf->b_data, hdr->b_size, arc_read_done, buf,
6233 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6237 kmem_free(cb, sizeof (l2arc_read_callback_t));
6241 * This is the list priority from which the L2ARC will search for pages to
6242 * cache. This is used within loops (0..3) to cycle through lists in the
6243 * desired order. This order can have a significant effect on cache
6246 * Currently the metadata lists are hit first, MFU then MRU, followed by
6247 * the data lists. This function returns a locked list, and also returns
6250 static multilist_sublist_t *
6251 l2arc_sublist_lock(int list_num)
6253 multilist_t *ml = NULL;
6256 ASSERT(list_num >= 0 && list_num <= 3);
6260 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6263 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6266 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6269 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6274 * Return a randomly-selected sublist. This is acceptable
6275 * because the caller feeds only a little bit of data for each
6276 * call (8MB). Subsequent calls will result in different
6277 * sublists being selected.
6279 idx = multilist_get_random_index(ml);
6280 return (multilist_sublist_lock(ml, idx));
6284 * Evict buffers from the device write hand to the distance specified in
6285 * bytes. This distance may span populated buffers, it may span nothing.
6286 * This is clearing a region on the L2ARC device ready for writing.
6287 * If the 'all' boolean is set, every buffer is evicted.
6290 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6293 arc_buf_hdr_t *hdr, *hdr_prev;
6294 kmutex_t *hash_lock;
6297 buflist = &dev->l2ad_buflist;
6299 if (!all && dev->l2ad_first) {
6301 * This is the first sweep through the device. There is
6307 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6309 * When nearing the end of the device, evict to the end
6310 * before the device write hand jumps to the start.
6312 taddr = dev->l2ad_end;
6314 taddr = dev->l2ad_hand + distance;
6316 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6317 uint64_t, taddr, boolean_t, all);
6320 mutex_enter(&dev->l2ad_mtx);
6321 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6322 hdr_prev = list_prev(buflist, hdr);
6324 hash_lock = HDR_LOCK(hdr);
6327 * We cannot use mutex_enter or else we can deadlock
6328 * with l2arc_write_buffers (due to swapping the order
6329 * the hash lock and l2ad_mtx are taken).
6331 if (!mutex_tryenter(hash_lock)) {
6333 * Missed the hash lock. Retry.
6335 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6336 mutex_exit(&dev->l2ad_mtx);
6337 mutex_enter(hash_lock);
6338 mutex_exit(hash_lock);
6342 if (HDR_L2_WRITE_HEAD(hdr)) {
6344 * We hit a write head node. Leave it for
6345 * l2arc_write_done().
6347 list_remove(buflist, hdr);
6348 mutex_exit(hash_lock);
6352 if (!all && HDR_HAS_L2HDR(hdr) &&
6353 (hdr->b_l2hdr.b_daddr > taddr ||
6354 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6356 * We've evicted to the target address,
6357 * or the end of the device.
6359 mutex_exit(hash_lock);
6363 ASSERT(HDR_HAS_L2HDR(hdr));
6364 if (!HDR_HAS_L1HDR(hdr)) {
6365 ASSERT(!HDR_L2_READING(hdr));
6367 * This doesn't exist in the ARC. Destroy.
6368 * arc_hdr_destroy() will call list_remove()
6369 * and decrement arcstat_l2_size.
6371 arc_change_state(arc_anon, hdr, hash_lock);
6372 arc_hdr_destroy(hdr);
6374 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6375 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6377 * Invalidate issued or about to be issued
6378 * reads, since we may be about to write
6379 * over this location.
6381 if (HDR_L2_READING(hdr)) {
6382 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6383 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6386 /* Ensure this header has finished being written */
6387 ASSERT(!HDR_L2_WRITING(hdr));
6388 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6390 arc_hdr_l2hdr_destroy(hdr);
6392 mutex_exit(hash_lock);
6394 mutex_exit(&dev->l2ad_mtx);
6398 * Find and write ARC buffers to the L2ARC device.
6400 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6401 * for reading until they have completed writing.
6402 * The headroom_boost is an in-out parameter used to maintain headroom boost
6403 * state between calls to this function.
6405 * Returns the number of bytes actually written (which may be smaller than
6406 * the delta by which the device hand has changed due to alignment).
6409 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6410 boolean_t *headroom_boost)
6412 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6413 uint64_t write_asize, write_sz, headroom,
6417 l2arc_write_callback_t *cb;
6419 uint64_t guid = spa_load_guid(spa);
6420 const boolean_t do_headroom_boost = *headroom_boost;
6423 ASSERT(dev->l2ad_vdev != NULL);
6425 /* Lower the flag now, we might want to raise it again later. */
6426 *headroom_boost = B_FALSE;
6429 write_sz = write_asize = 0;
6431 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6432 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6433 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6435 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6437 * We will want to try to compress buffers that are at least 2x the
6438 * device sector size.
6440 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6443 * Copy buffers for L2ARC writing.
6445 for (try = 0; try <= 3; try++) {
6446 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6447 uint64_t passed_sz = 0;
6449 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6452 * L2ARC fast warmup.
6454 * Until the ARC is warm and starts to evict, read from the
6455 * head of the ARC lists rather than the tail.
6457 if (arc_warm == B_FALSE)
6458 hdr = multilist_sublist_head(mls);
6460 hdr = multilist_sublist_tail(mls);
6462 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6464 headroom = target_sz * l2arc_headroom;
6465 if (do_headroom_boost)
6466 headroom = (headroom * l2arc_headroom_boost) / 100;
6468 for (; hdr; hdr = hdr_prev) {
6469 kmutex_t *hash_lock;
6474 if (arc_warm == B_FALSE)
6475 hdr_prev = multilist_sublist_next(mls, hdr);
6477 hdr_prev = multilist_sublist_prev(mls, hdr);
6478 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6480 hash_lock = HDR_LOCK(hdr);
6481 if (!mutex_tryenter(hash_lock)) {
6482 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6484 * Skip this buffer rather than waiting.
6489 passed_sz += hdr->b_size;
6490 if (passed_sz > headroom) {
6494 mutex_exit(hash_lock);
6495 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6499 if (!l2arc_write_eligible(guid, hdr)) {
6500 mutex_exit(hash_lock);
6505 * Assume that the buffer is not going to be compressed
6506 * and could take more space on disk because of a larger
6509 buf_sz = hdr->b_size;
6510 align = (size_t)1 << dev->l2ad_vdev->vdev_ashift;
6511 buf_a_sz = P2ROUNDUP(buf_sz, align);
6513 if ((write_asize + buf_a_sz) > target_sz) {
6515 mutex_exit(hash_lock);
6516 ARCSTAT_BUMP(arcstat_l2_write_full);
6522 * Insert a dummy header on the buflist so
6523 * l2arc_write_done() can find where the
6524 * write buffers begin without searching.
6526 mutex_enter(&dev->l2ad_mtx);
6527 list_insert_head(&dev->l2ad_buflist, head);
6528 mutex_exit(&dev->l2ad_mtx);
6531 sizeof (l2arc_write_callback_t), KM_SLEEP);
6532 cb->l2wcb_dev = dev;
6533 cb->l2wcb_head = head;
6534 pio = zio_root(spa, l2arc_write_done, cb,
6536 ARCSTAT_BUMP(arcstat_l2_write_pios);
6540 * Create and add a new L2ARC header.
6542 hdr->b_l2hdr.b_dev = dev;
6543 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6545 * Temporarily stash the data buffer in b_tmp_cdata.
6546 * The subsequent write step will pick it up from
6547 * there. This is because can't access b_l1hdr.b_buf
6548 * without holding the hash_lock, which we in turn
6549 * can't access without holding the ARC list locks
6550 * (which we want to avoid during compression/writing).
6552 hdr->b_l2hdr.b_compress = ZIO_COMPRESS_OFF;
6553 hdr->b_l2hdr.b_asize = hdr->b_size;
6554 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6557 * Explicitly set the b_daddr field to a known
6558 * value which means "invalid address". This
6559 * enables us to differentiate which stage of
6560 * l2arc_write_buffers() the particular header
6561 * is in (e.g. this loop, or the one below).
6562 * ARC_FLAG_L2_WRITING is not enough to make
6563 * this distinction, and we need to know in
6564 * order to do proper l2arc vdev accounting in
6565 * arc_release() and arc_hdr_destroy().
6567 * Note, we can't use a new flag to distinguish
6568 * the two stages because we don't hold the
6569 * header's hash_lock below, in the second stage
6570 * of this function. Thus, we can't simply
6571 * change the b_flags field to denote that the
6572 * IO has been sent. We can change the b_daddr
6573 * field of the L2 portion, though, since we'll
6574 * be holding the l2ad_mtx; which is why we're
6575 * using it to denote the header's state change.
6577 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6579 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6581 mutex_enter(&dev->l2ad_mtx);
6582 list_insert_head(&dev->l2ad_buflist, hdr);
6583 mutex_exit(&dev->l2ad_mtx);
6586 * Compute and store the buffer cksum before
6587 * writing. On debug the cksum is verified first.
6589 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6590 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6592 mutex_exit(hash_lock);
6595 write_asize += buf_a_sz;
6598 multilist_sublist_unlock(mls);
6604 /* No buffers selected for writing? */
6607 ASSERT(!HDR_HAS_L1HDR(head));
6608 kmem_cache_free(hdr_l2only_cache, head);
6612 mutex_enter(&dev->l2ad_mtx);
6615 * Now start writing the buffers. We're starting at the write head
6616 * and work backwards, retracing the course of the buffer selector
6620 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6621 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6626 * We rely on the L1 portion of the header below, so
6627 * it's invalid for this header to have been evicted out
6628 * of the ghost cache, prior to being written out. The
6629 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6631 ASSERT(HDR_HAS_L1HDR(hdr));
6634 * We shouldn't need to lock the buffer here, since we flagged
6635 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6636 * take care to only access its L2 cache parameters. In
6637 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6640 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6643 * Save a pointer to the original buffer data we had previously
6646 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6648 compress = HDR_L2COMPRESS(hdr) &&
6649 hdr->b_l2hdr.b_asize >= buf_compress_minsz;
6650 if (l2arc_transform_buf(hdr, compress)) {
6652 * If compression succeeded, enable headroom
6653 * boost on the next scan cycle.
6655 *headroom_boost = B_TRUE;
6659 * Get the new buffer size that accounts for compression
6662 buf_sz = hdr->b_l2hdr.b_asize;
6665 * We need to do this regardless if buf_sz is zero or
6666 * not, otherwise, when this l2hdr is evicted we'll
6667 * remove a reference that was never added.
6669 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6671 /* Compression may have squashed the buffer to zero length. */
6674 * If the data was padded or compressed, then it
6675 * it is in a new buffer.
6677 if (hdr->b_l1hdr.b_tmp_cdata != NULL)
6678 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6679 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6680 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6681 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6682 ZIO_FLAG_CANFAIL, B_FALSE);
6684 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6686 (void) zio_nowait(wzio);
6688 write_asize += buf_sz;
6689 dev->l2ad_hand += buf_sz;
6693 mutex_exit(&dev->l2ad_mtx);
6695 ASSERT3U(write_asize, <=, target_sz);
6696 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6697 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6698 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6699 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6700 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6703 * Bump device hand to the device start if it is approaching the end.
6704 * l2arc_evict() will already have evicted ahead for this case.
6706 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6707 dev->l2ad_hand = dev->l2ad_start;
6708 dev->l2ad_first = B_FALSE;
6711 dev->l2ad_writing = B_TRUE;
6712 (void) zio_wait(pio);
6713 dev->l2ad_writing = B_FALSE;
6715 return (write_asize);
6719 * Transforms, possibly compresses and pads, an L2ARC buffer.
6720 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6721 * size in l2hdr->b_asize. This routine tries to compress the data and
6722 * depending on the compression result there are three possible outcomes:
6723 * *) The buffer was incompressible. The buffer size was already ashift aligned.
6724 * The original hdr contents were left untouched except for b_tmp_cdata,
6725 * which is reset to NULL. The caller must keep a pointer to the original
6727 * *) The buffer was incompressible. The buffer size was not ashift aligned.
6728 * b_tmp_cdata was replaced with a temporary data buffer which holds a padded
6729 * (aligned) copy of the data. Once writing is done, invoke
6730 * l2arc_release_cdata_buf on this hdr to free the temporary buffer.
6731 * *) The buffer was all-zeros, so there is no need to write it to an L2
6732 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6733 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6734 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6735 * data buffer which holds the compressed data to be written, and b_asize
6736 * tells us how much data there is. b_compress is set to the appropriate
6737 * compression algorithm. Once writing is done, invoke
6738 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6740 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6741 * buffer was incompressible).
6744 l2arc_transform_buf(arc_buf_hdr_t *hdr, boolean_t compress)
6747 size_t align, asize, csize, len, rounded;
6749 ASSERT(HDR_HAS_L2HDR(hdr));
6750 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6752 ASSERT(HDR_HAS_L1HDR(hdr));
6753 ASSERT3S(l2hdr->b_compress, ==, ZIO_COMPRESS_OFF);
6754 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6756 len = l2hdr->b_asize;
6757 align = (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift;
6758 asize = P2ROUNDUP(len, align);
6759 cdata = zio_data_buf_alloc(asize);
6760 ASSERT3P(cdata, !=, NULL);
6762 csize = zio_compress_data(ZIO_COMPRESS_LZ4,
6763 hdr->b_l1hdr.b_tmp_cdata, cdata, len);
6768 /* zero block, indicate that there's nothing to write */
6769 zio_data_buf_free(cdata, asize);
6770 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
6772 hdr->b_l1hdr.b_tmp_cdata = NULL;
6773 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6777 rounded = P2ROUNDUP(csize, align);
6778 ASSERT3U(rounded, <=, asize);
6779 if (rounded < len) {
6781 * Compression succeeded, we'll keep the cdata around for
6782 * writing and release it afterwards.
6784 if (rounded > csize) {
6785 bzero((char *)cdata + csize, rounded - csize);
6788 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
6789 l2hdr->b_asize = csize;
6790 hdr->b_l1hdr.b_tmp_cdata = cdata;
6791 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6795 * Compression did not save space.
6797 if (P2PHASE(len, align) != 0) {
6799 * Use compression buffer for a copy of data padded to
6800 * the proper size. Compression algorithm remains set
6801 * to ZIO_COMPRESS_OFF.
6803 ASSERT3U(len, <, asize);
6804 bcopy(hdr->b_l1hdr.b_tmp_cdata, cdata, len);
6805 bzero((char *)cdata + len, asize - len);
6806 l2hdr->b_asize = asize;
6807 hdr->b_l1hdr.b_tmp_cdata = cdata;
6808 ARCSTAT_BUMP(arcstat_l2_padding_needed);
6810 ASSERT3U(len, ==, asize);
6812 * The original buffer is good as is,
6813 * release the compressed buffer.
6814 * l2hdr will be left unmodified except for b_tmp_cdata.
6816 zio_data_buf_free(cdata, asize);
6817 hdr->b_l1hdr.b_tmp_cdata = NULL;
6820 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6826 * Decompresses a zio read back from an l2arc device. On success, the
6827 * underlying zio's io_data buffer is overwritten by the uncompressed
6828 * version. On decompression error (corrupt compressed stream), the
6829 * zio->io_error value is set to signal an I/O error.
6831 * Please note that the compressed data stream is not checksummed, so
6832 * if the underlying device is experiencing data corruption, we may feed
6833 * corrupt data to the decompressor, so the decompressor needs to be
6834 * able to handle this situation (LZ4 does).
6837 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6839 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6841 if (zio->io_error != 0) {
6843 * An io error has occured, just restore the original io
6844 * size in preparation for a main pool read.
6846 zio->io_orig_size = zio->io_size = hdr->b_size;
6850 if (c == ZIO_COMPRESS_EMPTY) {
6852 * An empty buffer results in a null zio, which means we
6853 * need to fill its io_data after we're done restoring the
6854 * buffer's contents.
6856 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6857 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6858 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6860 ASSERT(zio->io_data != NULL);
6862 * We copy the compressed data from the start of the arc buffer
6863 * (the zio_read will have pulled in only what we need, the
6864 * rest is garbage which we will overwrite at decompression)
6865 * and then decompress back to the ARC data buffer. This way we
6866 * can minimize copying by simply decompressing back over the
6867 * original compressed data (rather than decompressing to an
6868 * aux buffer and then copying back the uncompressed buffer,
6869 * which is likely to be much larger).
6874 csize = zio->io_size;
6875 cdata = zio_data_buf_alloc(csize);
6876 bcopy(zio->io_data, cdata, csize);
6877 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6879 zio->io_error = EIO;
6880 zio_data_buf_free(cdata, csize);
6883 /* Restore the expected uncompressed IO size. */
6884 zio->io_orig_size = zio->io_size = hdr->b_size;
6888 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6889 * This buffer serves as a temporary holder of compressed or padded data while
6890 * the buffer entry is being written to an l2arc device. Once that is
6891 * done, we can dispose of it.
6894 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6896 size_t align, asize, len;
6897 enum zio_compress comp = hdr->b_l2hdr.b_compress;
6899 ASSERT(HDR_HAS_L2HDR(hdr));
6900 ASSERT(HDR_HAS_L1HDR(hdr));
6901 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6903 if (hdr->b_l1hdr.b_tmp_cdata != NULL) {
6904 ASSERT(comp != ZIO_COMPRESS_EMPTY);
6906 align = (size_t)1 << hdr->b_l2hdr.b_dev->l2ad_vdev->vdev_ashift;
6907 asize = P2ROUNDUP(len, align);
6908 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata, asize);
6909 hdr->b_l1hdr.b_tmp_cdata = NULL;
6911 ASSERT(comp == ZIO_COMPRESS_OFF || comp == ZIO_COMPRESS_EMPTY);
6916 * This thread feeds the L2ARC at regular intervals. This is the beating
6917 * heart of the L2ARC.
6920 l2arc_feed_thread(void *dummy __unused)
6925 uint64_t size, wrote;
6926 clock_t begin, next = ddi_get_lbolt();
6927 boolean_t headroom_boost = B_FALSE;
6929 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6931 mutex_enter(&l2arc_feed_thr_lock);
6933 while (l2arc_thread_exit == 0) {
6934 CALLB_CPR_SAFE_BEGIN(&cpr);
6935 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6936 next - ddi_get_lbolt());
6937 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6938 next = ddi_get_lbolt() + hz;
6941 * Quick check for L2ARC devices.
6943 mutex_enter(&l2arc_dev_mtx);
6944 if (l2arc_ndev == 0) {
6945 mutex_exit(&l2arc_dev_mtx);
6948 mutex_exit(&l2arc_dev_mtx);
6949 begin = ddi_get_lbolt();
6952 * This selects the next l2arc device to write to, and in
6953 * doing so the next spa to feed from: dev->l2ad_spa. This
6954 * will return NULL if there are now no l2arc devices or if
6955 * they are all faulted.
6957 * If a device is returned, its spa's config lock is also
6958 * held to prevent device removal. l2arc_dev_get_next()
6959 * will grab and release l2arc_dev_mtx.
6961 if ((dev = l2arc_dev_get_next()) == NULL)
6964 spa = dev->l2ad_spa;
6965 ASSERT(spa != NULL);
6968 * If the pool is read-only then force the feed thread to
6969 * sleep a little longer.
6971 if (!spa_writeable(spa)) {
6972 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6973 spa_config_exit(spa, SCL_L2ARC, dev);
6978 * Avoid contributing to memory pressure.
6980 if (arc_reclaim_needed()) {
6981 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6982 spa_config_exit(spa, SCL_L2ARC, dev);
6986 ARCSTAT_BUMP(arcstat_l2_feeds);
6988 size = l2arc_write_size();
6991 * Evict L2ARC buffers that will be overwritten.
6993 l2arc_evict(dev, size, B_FALSE);
6996 * Write ARC buffers.
6998 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
7001 * Calculate interval between writes.
7003 next = l2arc_write_interval(begin, size, wrote);
7004 spa_config_exit(spa, SCL_L2ARC, dev);
7007 l2arc_thread_exit = 0;
7008 cv_broadcast(&l2arc_feed_thr_cv);
7009 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
7014 l2arc_vdev_present(vdev_t *vd)
7018 mutex_enter(&l2arc_dev_mtx);
7019 for (dev = list_head(l2arc_dev_list); dev != NULL;
7020 dev = list_next(l2arc_dev_list, dev)) {
7021 if (dev->l2ad_vdev == vd)
7024 mutex_exit(&l2arc_dev_mtx);
7026 return (dev != NULL);
7030 * Add a vdev for use by the L2ARC. By this point the spa has already
7031 * validated the vdev and opened it.
7034 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7036 l2arc_dev_t *adddev;
7038 ASSERT(!l2arc_vdev_present(vd));
7040 vdev_ashift_optimize(vd);
7043 * Create a new l2arc device entry.
7045 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7046 adddev->l2ad_spa = spa;
7047 adddev->l2ad_vdev = vd;
7048 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7049 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7050 adddev->l2ad_hand = adddev->l2ad_start;
7051 adddev->l2ad_first = B_TRUE;
7052 adddev->l2ad_writing = B_FALSE;
7054 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7056 * This is a list of all ARC buffers that are still valid on the
7059 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7060 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7062 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7063 refcount_create(&adddev->l2ad_alloc);
7066 * Add device to global list
7068 mutex_enter(&l2arc_dev_mtx);
7069 list_insert_head(l2arc_dev_list, adddev);
7070 atomic_inc_64(&l2arc_ndev);
7071 mutex_exit(&l2arc_dev_mtx);
7075 * Remove a vdev from the L2ARC.
7078 l2arc_remove_vdev(vdev_t *vd)
7080 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7083 * Find the device by vdev
7085 mutex_enter(&l2arc_dev_mtx);
7086 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7087 nextdev = list_next(l2arc_dev_list, dev);
7088 if (vd == dev->l2ad_vdev) {
7093 ASSERT(remdev != NULL);
7096 * Remove device from global list
7098 list_remove(l2arc_dev_list, remdev);
7099 l2arc_dev_last = NULL; /* may have been invalidated */
7100 atomic_dec_64(&l2arc_ndev);
7101 mutex_exit(&l2arc_dev_mtx);
7104 * Clear all buflists and ARC references. L2ARC device flush.
7106 l2arc_evict(remdev, 0, B_TRUE);
7107 list_destroy(&remdev->l2ad_buflist);
7108 mutex_destroy(&remdev->l2ad_mtx);
7109 refcount_destroy(&remdev->l2ad_alloc);
7110 kmem_free(remdev, sizeof (l2arc_dev_t));
7116 l2arc_thread_exit = 0;
7118 l2arc_writes_sent = 0;
7119 l2arc_writes_done = 0;
7121 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7122 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7123 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7124 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7126 l2arc_dev_list = &L2ARC_dev_list;
7127 l2arc_free_on_write = &L2ARC_free_on_write;
7128 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7129 offsetof(l2arc_dev_t, l2ad_node));
7130 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7131 offsetof(l2arc_data_free_t, l2df_list_node));
7138 * This is called from dmu_fini(), which is called from spa_fini();
7139 * Because of this, we can assume that all l2arc devices have
7140 * already been removed when the pools themselves were removed.
7143 l2arc_do_free_on_write();
7145 mutex_destroy(&l2arc_feed_thr_lock);
7146 cv_destroy(&l2arc_feed_thr_cv);
7147 mutex_destroy(&l2arc_dev_mtx);
7148 mutex_destroy(&l2arc_free_on_write_mtx);
7150 list_destroy(l2arc_dev_list);
7151 list_destroy(l2arc_free_on_write);
7157 if (!(spa_mode_global & FWRITE))
7160 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7161 TS_RUN, minclsyspri);
7167 if (!(spa_mode_global & FWRITE))
7170 mutex_enter(&l2arc_feed_thr_lock);
7171 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7172 l2arc_thread_exit = 1;
7173 while (l2arc_thread_exit != 0)
7174 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7175 mutex_exit(&l2arc_feed_thr_lock);