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, 2015 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>
135 #include <sys/racct.h>
137 #include <sys/callb.h>
138 #include <sys/kstat.h>
139 #include <sys/trim_map.h>
140 #include <zfs_fletcher.h>
143 #include <vm/vm_pageout.h>
144 #include <machine/vmparam.h>
148 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
149 boolean_t arc_watch = B_FALSE;
154 static kmutex_t arc_reclaim_lock;
155 static kcondvar_t arc_reclaim_thread_cv;
156 static boolean_t arc_reclaim_thread_exit;
157 static kcondvar_t arc_reclaim_waiters_cv;
159 static kmutex_t arc_user_evicts_lock;
160 static kcondvar_t arc_user_evicts_cv;
161 static boolean_t arc_user_evicts_thread_exit;
163 uint_t arc_reduce_dnlc_percent = 3;
166 * The number of headers to evict in arc_evict_state_impl() before
167 * dropping the sublist lock and evicting from another sublist. A lower
168 * value means we're more likely to evict the "correct" header (i.e. the
169 * oldest header in the arc state), but comes with higher overhead
170 * (i.e. more invocations of arc_evict_state_impl()).
172 int zfs_arc_evict_batch_limit = 10;
175 * The number of sublists used for each of the arc state lists. If this
176 * is not set to a suitable value by the user, it will be configured to
177 * the number of CPUs on the system in arc_init().
179 int zfs_arc_num_sublists_per_state = 0;
181 /* number of seconds before growing cache again */
182 static int arc_grow_retry = 60;
184 /* shift of arc_c for calculating overflow limit in arc_get_data_buf */
185 int zfs_arc_overflow_shift = 8;
187 /* shift of arc_c for calculating both min and max arc_p */
188 static int arc_p_min_shift = 4;
190 /* log2(fraction of arc to reclaim) */
191 static int arc_shrink_shift = 7;
194 * log2(fraction of ARC which must be free to allow growing).
195 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
196 * when reading a new block into the ARC, we will evict an equal-sized block
199 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
200 * we will still not allow it to grow.
202 int arc_no_grow_shift = 5;
206 * minimum lifespan of a prefetch block in clock ticks
207 * (initialized in arc_init())
209 static int arc_min_prefetch_lifespan;
212 * If this percent of memory is free, don't throttle.
214 int arc_lotsfree_percent = 10;
217 extern boolean_t zfs_prefetch_disable;
220 * The arc has filled available memory and has now warmed up.
222 static boolean_t arc_warm;
225 * These tunables are for performance analysis.
227 uint64_t zfs_arc_max;
228 uint64_t zfs_arc_min;
229 uint64_t zfs_arc_meta_limit = 0;
230 uint64_t zfs_arc_meta_min = 0;
231 int zfs_arc_grow_retry = 0;
232 int zfs_arc_shrink_shift = 0;
233 int zfs_arc_p_min_shift = 0;
234 int zfs_disable_dup_eviction = 0;
235 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
236 u_int zfs_arc_free_target = 0;
238 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
239 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
243 arc_free_target_init(void *unused __unused)
246 zfs_arc_free_target = vm_pageout_wakeup_thresh;
248 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
249 arc_free_target_init, NULL);
251 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
252 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
253 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
254 SYSCTL_DECL(_vfs_zfs);
255 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
257 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
259 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
260 &zfs_arc_average_blocksize, 0,
261 "ARC average blocksize");
262 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
263 &arc_shrink_shift, 0,
264 "log2(fraction of arc to reclaim)");
267 * We don't have a tunable for arc_free_target due to the dependency on
268 * pagedaemon initialisation.
270 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
271 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
272 sysctl_vfs_zfs_arc_free_target, "IU",
273 "Desired number of free pages below which ARC triggers reclaim");
276 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
281 val = zfs_arc_free_target;
282 err = sysctl_handle_int(oidp, &val, 0, req);
283 if (err != 0 || req->newptr == NULL)
288 if (val > vm_cnt.v_page_count)
291 zfs_arc_free_target = val;
297 * Must be declared here, before the definition of corresponding kstat
298 * macro which uses the same names will confuse the compiler.
300 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
301 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
302 sysctl_vfs_zfs_arc_meta_limit, "QU",
303 "ARC metadata limit");
307 * Note that buffers can be in one of 6 states:
308 * ARC_anon - anonymous (discussed below)
309 * ARC_mru - recently used, currently cached
310 * ARC_mru_ghost - recentely used, no longer in cache
311 * ARC_mfu - frequently used, currently cached
312 * ARC_mfu_ghost - frequently used, no longer in cache
313 * ARC_l2c_only - exists in L2ARC but not other states
314 * When there are no active references to the buffer, they are
315 * are linked onto a list in one of these arc states. These are
316 * the only buffers that can be evicted or deleted. Within each
317 * state there are multiple lists, one for meta-data and one for
318 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
319 * etc.) is tracked separately so that it can be managed more
320 * explicitly: favored over data, limited explicitly.
322 * Anonymous buffers are buffers that are not associated with
323 * a DVA. These are buffers that hold dirty block copies
324 * before they are written to stable storage. By definition,
325 * they are "ref'd" and are considered part of arc_mru
326 * that cannot be freed. Generally, they will aquire a DVA
327 * as they are written and migrate onto the arc_mru list.
329 * The ARC_l2c_only state is for buffers that are in the second
330 * level ARC but no longer in any of the ARC_m* lists. The second
331 * level ARC itself may also contain buffers that are in any of
332 * the ARC_m* states - meaning that a buffer can exist in two
333 * places. The reason for the ARC_l2c_only state is to keep the
334 * buffer header in the hash table, so that reads that hit the
335 * second level ARC benefit from these fast lookups.
338 typedef struct arc_state {
340 * list of evictable buffers
342 multilist_t arcs_list[ARC_BUFC_NUMTYPES];
344 * total amount of evictable data in this state
346 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];
348 * total amount of data in this state; this includes: evictable,
349 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
351 refcount_t arcs_size;
355 static arc_state_t ARC_anon;
356 static arc_state_t ARC_mru;
357 static arc_state_t ARC_mru_ghost;
358 static arc_state_t ARC_mfu;
359 static arc_state_t ARC_mfu_ghost;
360 static arc_state_t ARC_l2c_only;
362 typedef struct arc_stats {
363 kstat_named_t arcstat_hits;
364 kstat_named_t arcstat_misses;
365 kstat_named_t arcstat_demand_data_hits;
366 kstat_named_t arcstat_demand_data_misses;
367 kstat_named_t arcstat_demand_metadata_hits;
368 kstat_named_t arcstat_demand_metadata_misses;
369 kstat_named_t arcstat_prefetch_data_hits;
370 kstat_named_t arcstat_prefetch_data_misses;
371 kstat_named_t arcstat_prefetch_metadata_hits;
372 kstat_named_t arcstat_prefetch_metadata_misses;
373 kstat_named_t arcstat_mru_hits;
374 kstat_named_t arcstat_mru_ghost_hits;
375 kstat_named_t arcstat_mfu_hits;
376 kstat_named_t arcstat_mfu_ghost_hits;
377 kstat_named_t arcstat_allocated;
378 kstat_named_t arcstat_deleted;
380 * Number of buffers that could not be evicted because the hash lock
381 * was held by another thread. The lock may not necessarily be held
382 * by something using the same buffer, since hash locks are shared
383 * by multiple buffers.
385 kstat_named_t arcstat_mutex_miss;
387 * Number of buffers skipped because they have I/O in progress, are
388 * indrect prefetch buffers that have not lived long enough, or are
389 * not from the spa we're trying to evict from.
391 kstat_named_t arcstat_evict_skip;
393 * Number of times arc_evict_state() was unable to evict enough
394 * buffers to reach it's target amount.
396 kstat_named_t arcstat_evict_not_enough;
397 kstat_named_t arcstat_evict_l2_cached;
398 kstat_named_t arcstat_evict_l2_eligible;
399 kstat_named_t arcstat_evict_l2_ineligible;
400 kstat_named_t arcstat_evict_l2_skip;
401 kstat_named_t arcstat_hash_elements;
402 kstat_named_t arcstat_hash_elements_max;
403 kstat_named_t arcstat_hash_collisions;
404 kstat_named_t arcstat_hash_chains;
405 kstat_named_t arcstat_hash_chain_max;
406 kstat_named_t arcstat_p;
407 kstat_named_t arcstat_c;
408 kstat_named_t arcstat_c_min;
409 kstat_named_t arcstat_c_max;
410 kstat_named_t arcstat_size;
412 * Number of bytes consumed by internal ARC structures necessary
413 * for tracking purposes; these structures are not actually
414 * backed by ARC buffers. This includes arc_buf_hdr_t structures
415 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
416 * caches), and arc_buf_t structures (allocated via arc_buf_t
419 kstat_named_t arcstat_hdr_size;
421 * Number of bytes consumed by ARC buffers of type equal to
422 * ARC_BUFC_DATA. This is generally consumed by buffers backing
423 * on disk user data (e.g. plain file contents).
425 kstat_named_t arcstat_data_size;
427 * Number of bytes consumed by ARC buffers of type equal to
428 * ARC_BUFC_METADATA. This is generally consumed by buffers
429 * backing on disk data that is used for internal ZFS
430 * structures (e.g. ZAP, dnode, indirect blocks, etc).
432 kstat_named_t arcstat_metadata_size;
434 * Number of bytes consumed by various buffers and structures
435 * not actually backed with ARC buffers. This includes bonus
436 * buffers (allocated directly via zio_buf_* functions),
437 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
438 * cache), and dnode_t structures (allocated via dnode_t cache).
440 kstat_named_t arcstat_other_size;
442 * Total number of bytes consumed by ARC buffers residing in the
443 * arc_anon state. This includes *all* buffers in the arc_anon
444 * state; e.g. data, metadata, evictable, and unevictable buffers
445 * are all included in this value.
447 kstat_named_t arcstat_anon_size;
449 * Number of bytes consumed by ARC buffers that meet the
450 * following criteria: backing buffers of type ARC_BUFC_DATA,
451 * residing in the arc_anon state, and are eligible for eviction
452 * (e.g. have no outstanding holds on the buffer).
454 kstat_named_t arcstat_anon_evictable_data;
456 * Number of bytes consumed by ARC buffers that meet the
457 * following criteria: backing buffers of type ARC_BUFC_METADATA,
458 * residing in the arc_anon state, and are eligible for eviction
459 * (e.g. have no outstanding holds on the buffer).
461 kstat_named_t arcstat_anon_evictable_metadata;
463 * Total number of bytes consumed by ARC buffers residing in the
464 * arc_mru state. This includes *all* buffers in the arc_mru
465 * state; e.g. data, metadata, evictable, and unevictable buffers
466 * are all included in this value.
468 kstat_named_t arcstat_mru_size;
470 * Number of bytes consumed by ARC buffers that meet the
471 * following criteria: backing buffers of type ARC_BUFC_DATA,
472 * residing in the arc_mru state, and are eligible for eviction
473 * (e.g. have no outstanding holds on the buffer).
475 kstat_named_t arcstat_mru_evictable_data;
477 * Number of bytes consumed by ARC buffers that meet the
478 * following criteria: backing buffers of type ARC_BUFC_METADATA,
479 * residing in the arc_mru state, and are eligible for eviction
480 * (e.g. have no outstanding holds on the buffer).
482 kstat_named_t arcstat_mru_evictable_metadata;
484 * Total number of bytes that *would have been* consumed by ARC
485 * buffers in the arc_mru_ghost state. The key thing to note
486 * here, is the fact that this size doesn't actually indicate
487 * RAM consumption. The ghost lists only consist of headers and
488 * don't actually have ARC buffers linked off of these headers.
489 * Thus, *if* the headers had associated ARC buffers, these
490 * buffers *would have* consumed this number of bytes.
492 kstat_named_t arcstat_mru_ghost_size;
494 * Number of bytes that *would have been* consumed by ARC
495 * buffers that are eligible for eviction, of type
496 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
498 kstat_named_t arcstat_mru_ghost_evictable_data;
500 * Number of bytes that *would have been* consumed by ARC
501 * buffers that are eligible for eviction, of type
502 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
504 kstat_named_t arcstat_mru_ghost_evictable_metadata;
506 * Total number of bytes consumed by ARC buffers residing in the
507 * arc_mfu state. This includes *all* buffers in the arc_mfu
508 * state; e.g. data, metadata, evictable, and unevictable buffers
509 * are all included in this value.
511 kstat_named_t arcstat_mfu_size;
513 * Number of bytes consumed by ARC buffers that are eligible for
514 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
517 kstat_named_t arcstat_mfu_evictable_data;
519 * Number of bytes consumed by ARC buffers that are eligible for
520 * eviction, of type ARC_BUFC_METADATA, and reside in the
523 kstat_named_t arcstat_mfu_evictable_metadata;
525 * Total number of bytes that *would have been* consumed by ARC
526 * buffers in the arc_mfu_ghost state. See the comment above
527 * arcstat_mru_ghost_size for more details.
529 kstat_named_t arcstat_mfu_ghost_size;
531 * Number of bytes that *would have been* consumed by ARC
532 * buffers that are eligible for eviction, of type
533 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
535 kstat_named_t arcstat_mfu_ghost_evictable_data;
537 * Number of bytes that *would have been* consumed by ARC
538 * buffers that are eligible for eviction, of type
539 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
541 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
542 kstat_named_t arcstat_l2_hits;
543 kstat_named_t arcstat_l2_misses;
544 kstat_named_t arcstat_l2_feeds;
545 kstat_named_t arcstat_l2_rw_clash;
546 kstat_named_t arcstat_l2_read_bytes;
547 kstat_named_t arcstat_l2_write_bytes;
548 kstat_named_t arcstat_l2_writes_sent;
549 kstat_named_t arcstat_l2_writes_done;
550 kstat_named_t arcstat_l2_writes_error;
551 kstat_named_t arcstat_l2_writes_lock_retry;
552 kstat_named_t arcstat_l2_evict_lock_retry;
553 kstat_named_t arcstat_l2_evict_reading;
554 kstat_named_t arcstat_l2_evict_l1cached;
555 kstat_named_t arcstat_l2_free_on_write;
556 kstat_named_t arcstat_l2_cdata_free_on_write;
557 kstat_named_t arcstat_l2_abort_lowmem;
558 kstat_named_t arcstat_l2_cksum_bad;
559 kstat_named_t arcstat_l2_io_error;
560 kstat_named_t arcstat_l2_size;
561 kstat_named_t arcstat_l2_asize;
562 kstat_named_t arcstat_l2_hdr_size;
563 kstat_named_t arcstat_l2_compress_successes;
564 kstat_named_t arcstat_l2_compress_zeros;
565 kstat_named_t arcstat_l2_compress_failures;
566 kstat_named_t arcstat_l2_padding_needed;
567 kstat_named_t arcstat_l2_write_trylock_fail;
568 kstat_named_t arcstat_l2_write_passed_headroom;
569 kstat_named_t arcstat_l2_write_spa_mismatch;
570 kstat_named_t arcstat_l2_write_in_l2;
571 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
572 kstat_named_t arcstat_l2_write_not_cacheable;
573 kstat_named_t arcstat_l2_write_full;
574 kstat_named_t arcstat_l2_write_buffer_iter;
575 kstat_named_t arcstat_l2_write_pios;
576 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
577 kstat_named_t arcstat_l2_write_buffer_list_iter;
578 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
579 kstat_named_t arcstat_memory_throttle_count;
580 kstat_named_t arcstat_duplicate_buffers;
581 kstat_named_t arcstat_duplicate_buffers_size;
582 kstat_named_t arcstat_duplicate_reads;
583 kstat_named_t arcstat_meta_used;
584 kstat_named_t arcstat_meta_limit;
585 kstat_named_t arcstat_meta_max;
586 kstat_named_t arcstat_meta_min;
587 kstat_named_t arcstat_sync_wait_for_async;
588 kstat_named_t arcstat_demand_hit_predictive_prefetch;
591 static arc_stats_t arc_stats = {
592 { "hits", KSTAT_DATA_UINT64 },
593 { "misses", KSTAT_DATA_UINT64 },
594 { "demand_data_hits", KSTAT_DATA_UINT64 },
595 { "demand_data_misses", KSTAT_DATA_UINT64 },
596 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
597 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
598 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
599 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
600 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
601 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
602 { "mru_hits", KSTAT_DATA_UINT64 },
603 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
604 { "mfu_hits", KSTAT_DATA_UINT64 },
605 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
606 { "allocated", KSTAT_DATA_UINT64 },
607 { "deleted", KSTAT_DATA_UINT64 },
608 { "mutex_miss", KSTAT_DATA_UINT64 },
609 { "evict_skip", KSTAT_DATA_UINT64 },
610 { "evict_not_enough", KSTAT_DATA_UINT64 },
611 { "evict_l2_cached", KSTAT_DATA_UINT64 },
612 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
613 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
614 { "evict_l2_skip", KSTAT_DATA_UINT64 },
615 { "hash_elements", KSTAT_DATA_UINT64 },
616 { "hash_elements_max", KSTAT_DATA_UINT64 },
617 { "hash_collisions", KSTAT_DATA_UINT64 },
618 { "hash_chains", KSTAT_DATA_UINT64 },
619 { "hash_chain_max", KSTAT_DATA_UINT64 },
620 { "p", KSTAT_DATA_UINT64 },
621 { "c", KSTAT_DATA_UINT64 },
622 { "c_min", KSTAT_DATA_UINT64 },
623 { "c_max", KSTAT_DATA_UINT64 },
624 { "size", KSTAT_DATA_UINT64 },
625 { "hdr_size", KSTAT_DATA_UINT64 },
626 { "data_size", KSTAT_DATA_UINT64 },
627 { "metadata_size", KSTAT_DATA_UINT64 },
628 { "other_size", KSTAT_DATA_UINT64 },
629 { "anon_size", KSTAT_DATA_UINT64 },
630 { "anon_evictable_data", KSTAT_DATA_UINT64 },
631 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
632 { "mru_size", KSTAT_DATA_UINT64 },
633 { "mru_evictable_data", KSTAT_DATA_UINT64 },
634 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
635 { "mru_ghost_size", KSTAT_DATA_UINT64 },
636 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
637 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
638 { "mfu_size", KSTAT_DATA_UINT64 },
639 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
640 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
641 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
642 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
643 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
644 { "l2_hits", KSTAT_DATA_UINT64 },
645 { "l2_misses", KSTAT_DATA_UINT64 },
646 { "l2_feeds", KSTAT_DATA_UINT64 },
647 { "l2_rw_clash", KSTAT_DATA_UINT64 },
648 { "l2_read_bytes", KSTAT_DATA_UINT64 },
649 { "l2_write_bytes", KSTAT_DATA_UINT64 },
650 { "l2_writes_sent", KSTAT_DATA_UINT64 },
651 { "l2_writes_done", KSTAT_DATA_UINT64 },
652 { "l2_writes_error", KSTAT_DATA_UINT64 },
653 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
654 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
655 { "l2_evict_reading", KSTAT_DATA_UINT64 },
656 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
657 { "l2_free_on_write", KSTAT_DATA_UINT64 },
658 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
659 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
660 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
661 { "l2_io_error", KSTAT_DATA_UINT64 },
662 { "l2_size", KSTAT_DATA_UINT64 },
663 { "l2_asize", KSTAT_DATA_UINT64 },
664 { "l2_hdr_size", KSTAT_DATA_UINT64 },
665 { "l2_compress_successes", KSTAT_DATA_UINT64 },
666 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
667 { "l2_compress_failures", KSTAT_DATA_UINT64 },
668 { "l2_padding_needed", KSTAT_DATA_UINT64 },
669 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
670 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
671 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
672 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
673 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
674 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
675 { "l2_write_full", KSTAT_DATA_UINT64 },
676 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
677 { "l2_write_pios", KSTAT_DATA_UINT64 },
678 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
679 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
680 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
681 { "memory_throttle_count", KSTAT_DATA_UINT64 },
682 { "duplicate_buffers", KSTAT_DATA_UINT64 },
683 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
684 { "duplicate_reads", KSTAT_DATA_UINT64 },
685 { "arc_meta_used", KSTAT_DATA_UINT64 },
686 { "arc_meta_limit", KSTAT_DATA_UINT64 },
687 { "arc_meta_max", KSTAT_DATA_UINT64 },
688 { "arc_meta_min", KSTAT_DATA_UINT64 },
689 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
690 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
693 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
695 #define ARCSTAT_INCR(stat, val) \
696 atomic_add_64(&arc_stats.stat.value.ui64, (val))
698 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
699 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
701 #define ARCSTAT_MAX(stat, val) { \
703 while ((val) > (m = arc_stats.stat.value.ui64) && \
704 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
708 #define ARCSTAT_MAXSTAT(stat) \
709 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
712 * We define a macro to allow ARC hits/misses to be easily broken down by
713 * two separate conditions, giving a total of four different subtypes for
714 * each of hits and misses (so eight statistics total).
716 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
719 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
721 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
725 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
727 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
732 static arc_state_t *arc_anon;
733 static arc_state_t *arc_mru;
734 static arc_state_t *arc_mru_ghost;
735 static arc_state_t *arc_mfu;
736 static arc_state_t *arc_mfu_ghost;
737 static arc_state_t *arc_l2c_only;
740 * There are several ARC variables that are critical to export as kstats --
741 * but we don't want to have to grovel around in the kstat whenever we wish to
742 * manipulate them. For these variables, we therefore define them to be in
743 * terms of the statistic variable. This assures that we are not introducing
744 * the possibility of inconsistency by having shadow copies of the variables,
745 * while still allowing the code to be readable.
747 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
748 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
749 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
750 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
751 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
752 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
753 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
754 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
755 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
757 #define L2ARC_IS_VALID_COMPRESS(_c_) \
758 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
760 static int arc_no_grow; /* Don't try to grow cache size */
761 static uint64_t arc_tempreserve;
762 static uint64_t arc_loaned_bytes;
764 typedef struct arc_callback arc_callback_t;
766 struct arc_callback {
768 arc_done_func_t *acb_done;
770 zio_t *acb_zio_dummy;
771 arc_callback_t *acb_next;
774 typedef struct arc_write_callback arc_write_callback_t;
776 struct arc_write_callback {
778 arc_done_func_t *awcb_ready;
779 arc_done_func_t *awcb_physdone;
780 arc_done_func_t *awcb_done;
785 * ARC buffers are separated into multiple structs as a memory saving measure:
786 * - Common fields struct, always defined, and embedded within it:
787 * - L2-only fields, always allocated but undefined when not in L2ARC
788 * - L1-only fields, only allocated when in L1ARC
790 * Buffer in L1 Buffer only in L2
791 * +------------------------+ +------------------------+
792 * | arc_buf_hdr_t | | arc_buf_hdr_t |
796 * +------------------------+ +------------------------+
797 * | l2arc_buf_hdr_t | | l2arc_buf_hdr_t |
798 * | (undefined if L1-only) | | |
799 * +------------------------+ +------------------------+
800 * | l1arc_buf_hdr_t |
805 * +------------------------+
807 * Because it's possible for the L2ARC to become extremely large, we can wind
808 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
809 * is minimized by only allocating the fields necessary for an L1-cached buffer
810 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
811 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
812 * words in pointers. arc_hdr_realloc() is used to switch a header between
813 * these two allocation states.
815 typedef struct l1arc_buf_hdr {
816 kmutex_t b_freeze_lock;
819 * used for debugging wtih kmem_flags - by allocating and freeing
820 * b_thawed when the buffer is thawed, we get a record of the stack
821 * trace that thawed it.
828 /* for waiting on writes to complete */
831 /* protected by arc state mutex */
832 arc_state_t *b_state;
833 multilist_node_t b_arc_node;
835 /* updated atomically */
836 clock_t b_arc_access;
838 /* self protecting */
841 arc_callback_t *b_acb;
842 /* temporary buffer holder for in-flight compressed or padded data */
846 typedef struct l2arc_dev l2arc_dev_t;
848 typedef struct l2arc_buf_hdr {
849 /* protected by arc_buf_hdr mutex */
850 l2arc_dev_t *b_dev; /* L2ARC device */
851 uint64_t b_daddr; /* disk address, offset byte */
852 /* real alloc'd buffer size depending on b_compress applied */
856 list_node_t b_l2node;
860 /* protected by hash lock */
864 * Even though this checksum is only set/verified when a buffer is in
865 * the L1 cache, it needs to be in the set of common fields because it
866 * must be preserved from the time before a buffer is written out to
867 * L2ARC until after it is read back in.
869 zio_cksum_t *b_freeze_cksum;
871 arc_buf_hdr_t *b_hash_next;
878 /* L2ARC fields. Undefined when not in L2ARC. */
879 l2arc_buf_hdr_t b_l2hdr;
880 /* L1ARC fields. Undefined when in l2arc_only state */
881 l1arc_buf_hdr_t b_l1hdr;
886 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
891 val = arc_meta_limit;
892 err = sysctl_handle_64(oidp, &val, 0, req);
893 if (err != 0 || req->newptr == NULL)
896 if (val <= 0 || val > arc_c_max)
899 arc_meta_limit = val;
904 static arc_buf_t *arc_eviction_list;
905 static arc_buf_hdr_t arc_eviction_hdr;
907 #define GHOST_STATE(state) \
908 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
909 (state) == arc_l2c_only)
911 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
912 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
913 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
914 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
915 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
916 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
918 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
919 #define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
920 #define HDR_L2_READING(hdr) \
921 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
922 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
923 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
924 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
925 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
927 #define HDR_ISTYPE_METADATA(hdr) \
928 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
929 #define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
931 #define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
932 #define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
938 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
939 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
942 * Hash table routines
945 #define HT_LOCK_PAD CACHE_LINE_SIZE
950 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
954 #define BUF_LOCKS 256
955 typedef struct buf_hash_table {
957 arc_buf_hdr_t **ht_table;
958 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
961 static buf_hash_table_t buf_hash_table;
963 #define BUF_HASH_INDEX(spa, dva, birth) \
964 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
965 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
966 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
967 #define HDR_LOCK(hdr) \
968 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
970 uint64_t zfs_crc64_table[256];
976 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
977 #define L2ARC_HEADROOM 2 /* num of writes */
979 * If we discover during ARC scan any buffers to be compressed, we boost
980 * our headroom for the next scanning cycle by this percentage multiple.
982 #define L2ARC_HEADROOM_BOOST 200
983 #define L2ARC_FEED_SECS 1 /* caching interval secs */
984 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
987 * Used to distinguish headers that are being process by
988 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
989 * address. This can happen when the header is added to the l2arc's list
990 * of buffers to write in the first stage of l2arc_write_buffers(), but
991 * has not yet been written out which happens in the second stage of
992 * l2arc_write_buffers().
994 #define L2ARC_ADDR_UNSET ((uint64_t)(-1))
996 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
997 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
999 /* L2ARC Performance Tunables */
1000 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
1001 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
1002 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
1003 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1004 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
1005 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1006 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
1007 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
1008 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
1010 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1011 &l2arc_write_max, 0, "max write size");
1012 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1013 &l2arc_write_boost, 0, "extra write during warmup");
1014 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1015 &l2arc_headroom, 0, "number of dev writes");
1016 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1017 &l2arc_feed_secs, 0, "interval seconds");
1018 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1019 &l2arc_feed_min_ms, 0, "min interval milliseconds");
1021 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1022 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1023 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1024 &l2arc_feed_again, 0, "turbo warmup");
1025 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1026 &l2arc_norw, 0, "no reads during writes");
1028 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1029 &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1030 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1031 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1032 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1033 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1035 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1036 &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1037 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1038 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1039 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1040 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1042 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1043 &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1044 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1045 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1046 "size of metadata in mru ghost state");
1047 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1048 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1049 "size of data in mru ghost state");
1051 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1052 &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1053 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1054 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1055 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1056 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1058 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1059 &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1060 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1061 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1062 "size of metadata in mfu ghost state");
1063 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1064 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1065 "size of data in mfu ghost state");
1067 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1068 &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1074 vdev_t *l2ad_vdev; /* vdev */
1075 spa_t *l2ad_spa; /* spa */
1076 uint64_t l2ad_hand; /* next write location */
1077 uint64_t l2ad_start; /* first addr on device */
1078 uint64_t l2ad_end; /* last addr on device */
1079 boolean_t l2ad_first; /* first sweep through */
1080 boolean_t l2ad_writing; /* currently writing */
1081 kmutex_t l2ad_mtx; /* lock for buffer list */
1082 list_t l2ad_buflist; /* buffer list */
1083 list_node_t l2ad_node; /* device list node */
1084 refcount_t l2ad_alloc; /* allocated bytes */
1087 static list_t L2ARC_dev_list; /* device list */
1088 static list_t *l2arc_dev_list; /* device list pointer */
1089 static kmutex_t l2arc_dev_mtx; /* device list mutex */
1090 static l2arc_dev_t *l2arc_dev_last; /* last device used */
1091 static list_t L2ARC_free_on_write; /* free after write buf list */
1092 static list_t *l2arc_free_on_write; /* free after write list ptr */
1093 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
1094 static uint64_t l2arc_ndev; /* number of devices */
1096 typedef struct l2arc_read_callback {
1097 arc_buf_t *l2rcb_buf; /* read buffer */
1098 spa_t *l2rcb_spa; /* spa */
1099 blkptr_t l2rcb_bp; /* original blkptr */
1100 zbookmark_phys_t l2rcb_zb; /* original bookmark */
1101 int l2rcb_flags; /* original flags */
1102 enum zio_compress l2rcb_compress; /* applied compress */
1103 void *l2rcb_data; /* temporary buffer */
1104 } l2arc_read_callback_t;
1106 typedef struct l2arc_write_callback {
1107 l2arc_dev_t *l2wcb_dev; /* device info */
1108 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
1109 } l2arc_write_callback_t;
1111 typedef struct l2arc_data_free {
1112 /* protected by l2arc_free_on_write_mtx */
1115 void (*l2df_func)(void *, size_t);
1116 list_node_t l2df_list_node;
1117 } l2arc_data_free_t;
1119 static kmutex_t l2arc_feed_thr_lock;
1120 static kcondvar_t l2arc_feed_thr_cv;
1121 static uint8_t l2arc_thread_exit;
1123 static void arc_get_data_buf(arc_buf_t *);
1124 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1125 static boolean_t arc_is_overflowing();
1126 static void arc_buf_watch(arc_buf_t *);
1128 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1129 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1131 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1132 static void l2arc_read_done(zio_t *);
1134 static boolean_t l2arc_transform_buf(arc_buf_hdr_t *, boolean_t);
1135 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1136 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1139 l2arc_trim(const arc_buf_hdr_t *hdr)
1141 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1143 ASSERT(HDR_HAS_L2HDR(hdr));
1144 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1146 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET)
1148 if (hdr->b_l2hdr.b_asize != 0) {
1149 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1150 hdr->b_l2hdr.b_asize, 0);
1152 ASSERT3U(hdr->b_l2hdr.b_compress, ==, ZIO_COMPRESS_EMPTY);
1157 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1159 uint8_t *vdva = (uint8_t *)dva;
1160 uint64_t crc = -1ULL;
1163 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1165 for (i = 0; i < sizeof (dva_t); i++)
1166 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1168 crc ^= (spa>>8) ^ birth;
1173 #define BUF_EMPTY(buf) \
1174 ((buf)->b_dva.dva_word[0] == 0 && \
1175 (buf)->b_dva.dva_word[1] == 0)
1177 #define BUF_EQUAL(spa, dva, birth, buf) \
1178 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
1179 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
1180 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1183 buf_discard_identity(arc_buf_hdr_t *hdr)
1185 hdr->b_dva.dva_word[0] = 0;
1186 hdr->b_dva.dva_word[1] = 0;
1190 static arc_buf_hdr_t *
1191 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1193 const dva_t *dva = BP_IDENTITY(bp);
1194 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1195 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1196 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1199 mutex_enter(hash_lock);
1200 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1201 hdr = hdr->b_hash_next) {
1202 if (BUF_EQUAL(spa, dva, birth, hdr)) {
1207 mutex_exit(hash_lock);
1213 * Insert an entry into the hash table. If there is already an element
1214 * equal to elem in the hash table, then the already existing element
1215 * will be returned and the new element will not be inserted.
1216 * Otherwise returns NULL.
1217 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1219 static arc_buf_hdr_t *
1220 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1222 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1223 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1224 arc_buf_hdr_t *fhdr;
1227 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1228 ASSERT(hdr->b_birth != 0);
1229 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1231 if (lockp != NULL) {
1233 mutex_enter(hash_lock);
1235 ASSERT(MUTEX_HELD(hash_lock));
1238 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1239 fhdr = fhdr->b_hash_next, i++) {
1240 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1244 hdr->b_hash_next = buf_hash_table.ht_table[idx];
1245 buf_hash_table.ht_table[idx] = hdr;
1246 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1248 /* collect some hash table performance data */
1250 ARCSTAT_BUMP(arcstat_hash_collisions);
1252 ARCSTAT_BUMP(arcstat_hash_chains);
1254 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1257 ARCSTAT_BUMP(arcstat_hash_elements);
1258 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1264 buf_hash_remove(arc_buf_hdr_t *hdr)
1266 arc_buf_hdr_t *fhdr, **hdrp;
1267 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1269 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1270 ASSERT(HDR_IN_HASH_TABLE(hdr));
1272 hdrp = &buf_hash_table.ht_table[idx];
1273 while ((fhdr = *hdrp) != hdr) {
1274 ASSERT(fhdr != NULL);
1275 hdrp = &fhdr->b_hash_next;
1277 *hdrp = hdr->b_hash_next;
1278 hdr->b_hash_next = NULL;
1279 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1281 /* collect some hash table performance data */
1282 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1284 if (buf_hash_table.ht_table[idx] &&
1285 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1286 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1290 * Global data structures and functions for the buf kmem cache.
1292 static kmem_cache_t *hdr_full_cache;
1293 static kmem_cache_t *hdr_l2only_cache;
1294 static kmem_cache_t *buf_cache;
1301 kmem_free(buf_hash_table.ht_table,
1302 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1303 for (i = 0; i < BUF_LOCKS; i++)
1304 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1305 kmem_cache_destroy(hdr_full_cache);
1306 kmem_cache_destroy(hdr_l2only_cache);
1307 kmem_cache_destroy(buf_cache);
1311 * Constructor callback - called when the cache is empty
1312 * and a new buf is requested.
1316 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1318 arc_buf_hdr_t *hdr = vbuf;
1320 bzero(hdr, HDR_FULL_SIZE);
1321 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1322 refcount_create(&hdr->b_l1hdr.b_refcnt);
1323 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1324 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1325 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1332 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1334 arc_buf_hdr_t *hdr = vbuf;
1336 bzero(hdr, HDR_L2ONLY_SIZE);
1337 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1344 buf_cons(void *vbuf, void *unused, int kmflag)
1346 arc_buf_t *buf = vbuf;
1348 bzero(buf, sizeof (arc_buf_t));
1349 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1350 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1356 * Destructor callback - called when a cached buf is
1357 * no longer required.
1361 hdr_full_dest(void *vbuf, void *unused)
1363 arc_buf_hdr_t *hdr = vbuf;
1365 ASSERT(BUF_EMPTY(hdr));
1366 cv_destroy(&hdr->b_l1hdr.b_cv);
1367 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1368 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1369 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1370 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1375 hdr_l2only_dest(void *vbuf, void *unused)
1377 arc_buf_hdr_t *hdr = vbuf;
1379 ASSERT(BUF_EMPTY(hdr));
1380 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1385 buf_dest(void *vbuf, void *unused)
1387 arc_buf_t *buf = vbuf;
1389 mutex_destroy(&buf->b_evict_lock);
1390 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1394 * Reclaim callback -- invoked when memory is low.
1398 hdr_recl(void *unused)
1400 dprintf("hdr_recl called\n");
1402 * umem calls the reclaim func when we destroy the buf cache,
1403 * which is after we do arc_fini().
1406 cv_signal(&arc_reclaim_thread_cv);
1413 uint64_t hsize = 1ULL << 12;
1417 * The hash table is big enough to fill all of physical memory
1418 * with an average block size of zfs_arc_average_blocksize (default 8K).
1419 * By default, the table will take up
1420 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1422 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1425 buf_hash_table.ht_mask = hsize - 1;
1426 buf_hash_table.ht_table =
1427 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1428 if (buf_hash_table.ht_table == NULL) {
1429 ASSERT(hsize > (1ULL << 8));
1434 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1435 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1436 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1437 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1439 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1440 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1442 for (i = 0; i < 256; i++)
1443 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1444 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1446 for (i = 0; i < BUF_LOCKS; i++) {
1447 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1448 NULL, MUTEX_DEFAULT, NULL);
1453 * Transition between the two allocation states for the arc_buf_hdr struct.
1454 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1455 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1456 * version is used when a cache buffer is only in the L2ARC in order to reduce
1459 static arc_buf_hdr_t *
1460 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1462 ASSERT(HDR_HAS_L2HDR(hdr));
1464 arc_buf_hdr_t *nhdr;
1465 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1467 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1468 (old == hdr_l2only_cache && new == hdr_full_cache));
1470 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1472 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1473 buf_hash_remove(hdr);
1475 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1477 if (new == hdr_full_cache) {
1478 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1480 * arc_access and arc_change_state need to be aware that a
1481 * header has just come out of L2ARC, so we set its state to
1482 * l2c_only even though it's about to change.
1484 nhdr->b_l1hdr.b_state = arc_l2c_only;
1486 /* Verify previous threads set to NULL before freeing */
1487 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1489 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1490 ASSERT0(hdr->b_l1hdr.b_datacnt);
1493 * If we've reached here, We must have been called from
1494 * arc_evict_hdr(), as such we should have already been
1495 * removed from any ghost list we were previously on
1496 * (which protects us from racing with arc_evict_state),
1497 * thus no locking is needed during this check.
1499 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1502 * A buffer must not be moved into the arc_l2c_only
1503 * state if it's not finished being written out to the
1504 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1505 * might try to be accessed, even though it was removed.
1507 VERIFY(!HDR_L2_WRITING(hdr));
1508 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1511 if (hdr->b_l1hdr.b_thawed != NULL) {
1512 kmem_free(hdr->b_l1hdr.b_thawed, 1);
1513 hdr->b_l1hdr.b_thawed = NULL;
1517 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1520 * The header has been reallocated so we need to re-insert it into any
1523 (void) buf_hash_insert(nhdr, NULL);
1525 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1527 mutex_enter(&dev->l2ad_mtx);
1530 * We must place the realloc'ed header back into the list at
1531 * the same spot. Otherwise, if it's placed earlier in the list,
1532 * l2arc_write_buffers() could find it during the function's
1533 * write phase, and try to write it out to the l2arc.
1535 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1536 list_remove(&dev->l2ad_buflist, hdr);
1538 mutex_exit(&dev->l2ad_mtx);
1541 * Since we're using the pointer address as the tag when
1542 * incrementing and decrementing the l2ad_alloc refcount, we
1543 * must remove the old pointer (that we're about to destroy) and
1544 * add the new pointer to the refcount. Otherwise we'd remove
1545 * the wrong pointer address when calling arc_hdr_destroy() later.
1548 (void) refcount_remove_many(&dev->l2ad_alloc,
1549 hdr->b_l2hdr.b_asize, hdr);
1551 (void) refcount_add_many(&dev->l2ad_alloc,
1552 nhdr->b_l2hdr.b_asize, nhdr);
1554 buf_discard_identity(hdr);
1555 hdr->b_freeze_cksum = NULL;
1556 kmem_cache_free(old, hdr);
1562 #define ARC_MINTIME (hz>>4) /* 62 ms */
1565 arc_cksum_verify(arc_buf_t *buf)
1569 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1572 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1573 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1574 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1577 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1578 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1579 panic("buffer modified while frozen!");
1580 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1584 arc_cksum_equal(arc_buf_t *buf)
1589 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1590 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, NULL, &zc);
1591 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1592 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1598 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1600 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1603 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1604 if (buf->b_hdr->b_freeze_cksum != NULL) {
1605 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1608 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1609 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1610 NULL, buf->b_hdr->b_freeze_cksum);
1611 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1619 typedef struct procctl {
1627 arc_buf_unwatch(arc_buf_t *buf)
1634 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1635 ctl.prwatch.pr_size = 0;
1636 ctl.prwatch.pr_wflags = 0;
1637 result = write(arc_procfd, &ctl, sizeof (ctl));
1638 ASSERT3U(result, ==, sizeof (ctl));
1645 arc_buf_watch(arc_buf_t *buf)
1652 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1653 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1654 ctl.prwatch.pr_wflags = WA_WRITE;
1655 result = write(arc_procfd, &ctl, sizeof (ctl));
1656 ASSERT3U(result, ==, sizeof (ctl));
1660 #endif /* illumos */
1662 static arc_buf_contents_t
1663 arc_buf_type(arc_buf_hdr_t *hdr)
1665 if (HDR_ISTYPE_METADATA(hdr)) {
1666 return (ARC_BUFC_METADATA);
1668 return (ARC_BUFC_DATA);
1673 arc_bufc_to_flags(arc_buf_contents_t type)
1677 /* metadata field is 0 if buffer contains normal data */
1679 case ARC_BUFC_METADATA:
1680 return (ARC_FLAG_BUFC_METADATA);
1684 panic("undefined ARC buffer type!");
1685 return ((uint32_t)-1);
1689 arc_buf_thaw(arc_buf_t *buf)
1691 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1692 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1693 panic("modifying non-anon buffer!");
1694 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1695 panic("modifying buffer while i/o in progress!");
1696 arc_cksum_verify(buf);
1699 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1700 if (buf->b_hdr->b_freeze_cksum != NULL) {
1701 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1702 buf->b_hdr->b_freeze_cksum = NULL;
1706 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1707 if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1708 kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1709 buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1713 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1716 arc_buf_unwatch(buf);
1721 arc_buf_freeze(arc_buf_t *buf)
1723 kmutex_t *hash_lock;
1725 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1728 hash_lock = HDR_LOCK(buf->b_hdr);
1729 mutex_enter(hash_lock);
1731 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1732 buf->b_hdr->b_l1hdr.b_state == arc_anon);
1733 arc_cksum_compute(buf, B_FALSE);
1734 mutex_exit(hash_lock);
1739 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1741 ASSERT(HDR_HAS_L1HDR(hdr));
1742 ASSERT(MUTEX_HELD(hash_lock));
1743 arc_state_t *state = hdr->b_l1hdr.b_state;
1745 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1746 (state != arc_anon)) {
1747 /* We don't use the L2-only state list. */
1748 if (state != arc_l2c_only) {
1749 arc_buf_contents_t type = arc_buf_type(hdr);
1750 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1751 multilist_t *list = &state->arcs_list[type];
1752 uint64_t *size = &state->arcs_lsize[type];
1754 multilist_remove(list, hdr);
1756 if (GHOST_STATE(state)) {
1757 ASSERT0(hdr->b_l1hdr.b_datacnt);
1758 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1759 delta = hdr->b_size;
1762 ASSERT3U(*size, >=, delta);
1763 atomic_add_64(size, -delta);
1765 /* remove the prefetch flag if we get a reference */
1766 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1771 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1774 arc_state_t *state = hdr->b_l1hdr.b_state;
1776 ASSERT(HDR_HAS_L1HDR(hdr));
1777 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1778 ASSERT(!GHOST_STATE(state));
1781 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1782 * check to prevent usage of the arc_l2c_only list.
1784 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1785 (state != arc_anon)) {
1786 arc_buf_contents_t type = arc_buf_type(hdr);
1787 multilist_t *list = &state->arcs_list[type];
1788 uint64_t *size = &state->arcs_lsize[type];
1790 multilist_insert(list, hdr);
1792 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1793 atomic_add_64(size, hdr->b_size *
1794 hdr->b_l1hdr.b_datacnt);
1800 * Move the supplied buffer to the indicated state. The hash lock
1801 * for the buffer must be held by the caller.
1804 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1805 kmutex_t *hash_lock)
1807 arc_state_t *old_state;
1810 uint64_t from_delta, to_delta;
1811 arc_buf_contents_t buftype = arc_buf_type(hdr);
1814 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1815 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1816 * L1 hdr doesn't always exist when we change state to arc_anon before
1817 * destroying a header, in which case reallocating to add the L1 hdr is
1820 if (HDR_HAS_L1HDR(hdr)) {
1821 old_state = hdr->b_l1hdr.b_state;
1822 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1823 datacnt = hdr->b_l1hdr.b_datacnt;
1825 old_state = arc_l2c_only;
1830 ASSERT(MUTEX_HELD(hash_lock));
1831 ASSERT3P(new_state, !=, old_state);
1832 ASSERT(refcnt == 0 || datacnt > 0);
1833 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1834 ASSERT(old_state != arc_anon || datacnt <= 1);
1836 from_delta = to_delta = datacnt * hdr->b_size;
1839 * If this buffer is evictable, transfer it from the
1840 * old state list to the new state list.
1843 if (old_state != arc_anon && old_state != arc_l2c_only) {
1844 uint64_t *size = &old_state->arcs_lsize[buftype];
1846 ASSERT(HDR_HAS_L1HDR(hdr));
1847 multilist_remove(&old_state->arcs_list[buftype], hdr);
1850 * If prefetching out of the ghost cache,
1851 * we will have a non-zero datacnt.
1853 if (GHOST_STATE(old_state) && datacnt == 0) {
1854 /* ghost elements have a ghost size */
1855 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1856 from_delta = hdr->b_size;
1858 ASSERT3U(*size, >=, from_delta);
1859 atomic_add_64(size, -from_delta);
1861 if (new_state != arc_anon && new_state != arc_l2c_only) {
1862 uint64_t *size = &new_state->arcs_lsize[buftype];
1865 * An L1 header always exists here, since if we're
1866 * moving to some L1-cached state (i.e. not l2c_only or
1867 * anonymous), we realloc the header to add an L1hdr
1870 ASSERT(HDR_HAS_L1HDR(hdr));
1871 multilist_insert(&new_state->arcs_list[buftype], hdr);
1873 /* ghost elements have a ghost size */
1874 if (GHOST_STATE(new_state)) {
1876 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1877 to_delta = hdr->b_size;
1879 atomic_add_64(size, to_delta);
1883 ASSERT(!BUF_EMPTY(hdr));
1884 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1885 buf_hash_remove(hdr);
1887 /* adjust state sizes (ignore arc_l2c_only) */
1889 if (to_delta && new_state != arc_l2c_only) {
1890 ASSERT(HDR_HAS_L1HDR(hdr));
1891 if (GHOST_STATE(new_state)) {
1895 * We moving a header to a ghost state, we first
1896 * remove all arc buffers. Thus, we'll have a
1897 * datacnt of zero, and no arc buffer to use for
1898 * the reference. As a result, we use the arc
1899 * header pointer for the reference.
1901 (void) refcount_add_many(&new_state->arcs_size,
1904 ASSERT3U(datacnt, !=, 0);
1907 * Each individual buffer holds a unique reference,
1908 * thus we must remove each of these references one
1911 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1912 buf = buf->b_next) {
1913 (void) refcount_add_many(&new_state->arcs_size,
1919 if (from_delta && old_state != arc_l2c_only) {
1920 ASSERT(HDR_HAS_L1HDR(hdr));
1921 if (GHOST_STATE(old_state)) {
1923 * When moving a header off of a ghost state,
1924 * there's the possibility for datacnt to be
1925 * non-zero. This is because we first add the
1926 * arc buffer to the header prior to changing
1927 * the header's state. Since we used the header
1928 * for the reference when putting the header on
1929 * the ghost state, we must balance that and use
1930 * the header when removing off the ghost state
1931 * (even though datacnt is non zero).
1934 IMPLY(datacnt == 0, new_state == arc_anon ||
1935 new_state == arc_l2c_only);
1937 (void) refcount_remove_many(&old_state->arcs_size,
1940 ASSERT3P(datacnt, !=, 0);
1943 * Each individual buffer holds a unique reference,
1944 * thus we must remove each of these references one
1947 for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
1948 buf = buf->b_next) {
1949 (void) refcount_remove_many(
1950 &old_state->arcs_size, hdr->b_size, buf);
1955 if (HDR_HAS_L1HDR(hdr))
1956 hdr->b_l1hdr.b_state = new_state;
1959 * L2 headers should never be on the L2 state list since they don't
1960 * have L1 headers allocated.
1962 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1963 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1967 arc_space_consume(uint64_t space, arc_space_type_t type)
1969 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1972 case ARC_SPACE_DATA:
1973 ARCSTAT_INCR(arcstat_data_size, space);
1975 case ARC_SPACE_META:
1976 ARCSTAT_INCR(arcstat_metadata_size, space);
1978 case ARC_SPACE_OTHER:
1979 ARCSTAT_INCR(arcstat_other_size, space);
1981 case ARC_SPACE_HDRS:
1982 ARCSTAT_INCR(arcstat_hdr_size, space);
1984 case ARC_SPACE_L2HDRS:
1985 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1989 if (type != ARC_SPACE_DATA)
1990 ARCSTAT_INCR(arcstat_meta_used, space);
1992 atomic_add_64(&arc_size, space);
1996 arc_space_return(uint64_t space, arc_space_type_t type)
1998 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2001 case ARC_SPACE_DATA:
2002 ARCSTAT_INCR(arcstat_data_size, -space);
2004 case ARC_SPACE_META:
2005 ARCSTAT_INCR(arcstat_metadata_size, -space);
2007 case ARC_SPACE_OTHER:
2008 ARCSTAT_INCR(arcstat_other_size, -space);
2010 case ARC_SPACE_HDRS:
2011 ARCSTAT_INCR(arcstat_hdr_size, -space);
2013 case ARC_SPACE_L2HDRS:
2014 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
2018 if (type != ARC_SPACE_DATA) {
2019 ASSERT(arc_meta_used >= space);
2020 if (arc_meta_max < arc_meta_used)
2021 arc_meta_max = arc_meta_used;
2022 ARCSTAT_INCR(arcstat_meta_used, -space);
2025 ASSERT(arc_size >= space);
2026 atomic_add_64(&arc_size, -space);
2030 arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
2035 ASSERT3U(size, >, 0);
2036 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2037 ASSERT(BUF_EMPTY(hdr));
2038 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
2040 hdr->b_spa = spa_load_guid(spa);
2042 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2045 buf->b_efunc = NULL;
2046 buf->b_private = NULL;
2049 hdr->b_flags = arc_bufc_to_flags(type);
2050 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
2052 hdr->b_l1hdr.b_buf = buf;
2053 hdr->b_l1hdr.b_state = arc_anon;
2054 hdr->b_l1hdr.b_arc_access = 0;
2055 hdr->b_l1hdr.b_datacnt = 1;
2056 hdr->b_l1hdr.b_tmp_cdata = NULL;
2058 arc_get_data_buf(buf);
2059 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2060 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2065 static char *arc_onloan_tag = "onloan";
2068 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2069 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2070 * buffers must be returned to the arc before they can be used by the DMU or
2074 arc_loan_buf(spa_t *spa, int size)
2078 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2080 atomic_add_64(&arc_loaned_bytes, size);
2085 * Return a loaned arc buffer to the arc.
2088 arc_return_buf(arc_buf_t *buf, void *tag)
2090 arc_buf_hdr_t *hdr = buf->b_hdr;
2092 ASSERT(buf->b_data != NULL);
2093 ASSERT(HDR_HAS_L1HDR(hdr));
2094 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2095 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2097 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2100 /* Detach an arc_buf from a dbuf (tag) */
2102 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2104 arc_buf_hdr_t *hdr = buf->b_hdr;
2106 ASSERT(buf->b_data != NULL);
2107 ASSERT(HDR_HAS_L1HDR(hdr));
2108 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2109 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2110 buf->b_efunc = NULL;
2111 buf->b_private = NULL;
2113 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2117 arc_buf_clone(arc_buf_t *from)
2120 arc_buf_hdr_t *hdr = from->b_hdr;
2121 uint64_t size = hdr->b_size;
2123 ASSERT(HDR_HAS_L1HDR(hdr));
2124 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2126 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2129 buf->b_efunc = NULL;
2130 buf->b_private = NULL;
2131 buf->b_next = hdr->b_l1hdr.b_buf;
2132 hdr->b_l1hdr.b_buf = buf;
2133 arc_get_data_buf(buf);
2134 bcopy(from->b_data, buf->b_data, size);
2137 * This buffer already exists in the arc so create a duplicate
2138 * copy for the caller. If the buffer is associated with user data
2139 * then track the size and number of duplicates. These stats will be
2140 * updated as duplicate buffers are created and destroyed.
2142 if (HDR_ISTYPE_DATA(hdr)) {
2143 ARCSTAT_BUMP(arcstat_duplicate_buffers);
2144 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2146 hdr->b_l1hdr.b_datacnt += 1;
2151 arc_buf_add_ref(arc_buf_t *buf, void* tag)
2154 kmutex_t *hash_lock;
2157 * Check to see if this buffer is evicted. Callers
2158 * must verify b_data != NULL to know if the add_ref
2161 mutex_enter(&buf->b_evict_lock);
2162 if (buf->b_data == NULL) {
2163 mutex_exit(&buf->b_evict_lock);
2166 hash_lock = HDR_LOCK(buf->b_hdr);
2167 mutex_enter(hash_lock);
2169 ASSERT(HDR_HAS_L1HDR(hdr));
2170 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2171 mutex_exit(&buf->b_evict_lock);
2173 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2174 hdr->b_l1hdr.b_state == arc_mfu);
2176 add_reference(hdr, hash_lock, tag);
2177 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2178 arc_access(hdr, hash_lock);
2179 mutex_exit(hash_lock);
2180 ARCSTAT_BUMP(arcstat_hits);
2181 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2182 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2183 data, metadata, hits);
2187 arc_buf_free_on_write(void *data, size_t size,
2188 void (*free_func)(void *, size_t))
2190 l2arc_data_free_t *df;
2192 df = kmem_alloc(sizeof (*df), KM_SLEEP);
2193 df->l2df_data = data;
2194 df->l2df_size = size;
2195 df->l2df_func = free_func;
2196 mutex_enter(&l2arc_free_on_write_mtx);
2197 list_insert_head(l2arc_free_on_write, df);
2198 mutex_exit(&l2arc_free_on_write_mtx);
2202 * Free the arc data buffer. If it is an l2arc write in progress,
2203 * the buffer is placed on l2arc_free_on_write to be freed later.
2206 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2208 arc_buf_hdr_t *hdr = buf->b_hdr;
2210 if (HDR_L2_WRITING(hdr)) {
2211 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2212 ARCSTAT_BUMP(arcstat_l2_free_on_write);
2214 free_func(buf->b_data, hdr->b_size);
2219 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2221 size_t align, asize, len;
2223 ASSERT(HDR_HAS_L2HDR(hdr));
2224 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2227 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2228 * that doesn't exist, the header is in the arc_l2c_only state,
2229 * and there isn't anything to free (it's already been freed).
2231 if (!HDR_HAS_L1HDR(hdr))
2235 * The header isn't being written to the l2arc device, thus it
2236 * shouldn't have a b_tmp_cdata to free.
2238 if (!HDR_L2_WRITING(hdr)) {
2239 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2244 * The bufer has been chosen for writing to L2ARC, but it's
2245 * not being written just yet. In other words,
2246 * b_tmp_cdata points to exactly the same buffer as b_data,
2247 * l2arc_transform_buf hasn't been called.
2249 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET) {
2250 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==,
2251 hdr->b_l1hdr.b_buf->b_data);
2252 ASSERT3U(hdr->b_l2hdr.b_compress, ==, ZIO_COMPRESS_OFF);
2257 * There's nothing to free since the buffer was all zero's and
2258 * compressed to a zero length buffer.
2260 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_EMPTY) {
2261 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
2266 * Nothing to do if the temporary buffer was not required.
2268 if (hdr->b_l1hdr.b_tmp_cdata == NULL)
2271 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2273 align = (size_t)1 << hdr->b_l2hdr.b_dev->l2ad_vdev->vdev_ashift;
2274 asize = P2ROUNDUP(len, align);
2275 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata, asize,
2277 hdr->b_l1hdr.b_tmp_cdata = NULL;
2281 * Free up buf->b_data and if 'remove' is set, then pull the
2282 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2285 arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
2289 /* free up data associated with the buf */
2290 if (buf->b_data != NULL) {
2291 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2292 uint64_t size = buf->b_hdr->b_size;
2293 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2295 arc_cksum_verify(buf);
2297 arc_buf_unwatch(buf);
2300 if (type == ARC_BUFC_METADATA) {
2301 arc_buf_data_free(buf, zio_buf_free);
2302 arc_space_return(size, ARC_SPACE_META);
2304 ASSERT(type == ARC_BUFC_DATA);
2305 arc_buf_data_free(buf, zio_data_buf_free);
2306 arc_space_return(size, ARC_SPACE_DATA);
2309 /* protected by hash lock, if in the hash table */
2310 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2311 uint64_t *cnt = &state->arcs_lsize[type];
2313 ASSERT(refcount_is_zero(
2314 &buf->b_hdr->b_l1hdr.b_refcnt));
2315 ASSERT(state != arc_anon && state != arc_l2c_only);
2317 ASSERT3U(*cnt, >=, size);
2318 atomic_add_64(cnt, -size);
2321 (void) refcount_remove_many(&state->arcs_size, size, buf);
2325 * If we're destroying a duplicate buffer make sure
2326 * that the appropriate statistics are updated.
2328 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2329 HDR_ISTYPE_DATA(buf->b_hdr)) {
2330 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2331 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2333 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2334 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2337 /* only remove the buf if requested */
2341 /* remove the buf from the hdr list */
2342 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2343 bufp = &(*bufp)->b_next)
2345 *bufp = buf->b_next;
2348 ASSERT(buf->b_efunc == NULL);
2350 /* clean up the buf */
2352 kmem_cache_free(buf_cache, buf);
2356 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2358 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2359 l2arc_dev_t *dev = l2hdr->b_dev;
2361 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2362 ASSERT(HDR_HAS_L2HDR(hdr));
2364 list_remove(&dev->l2ad_buflist, hdr);
2367 * We don't want to leak the b_tmp_cdata buffer that was
2368 * allocated in l2arc_write_buffers()
2370 arc_buf_l2_cdata_free(hdr);
2373 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2374 * this header is being processed by l2arc_write_buffers() (i.e.
2375 * it's in the first stage of l2arc_write_buffers()).
2376 * Re-affirming that truth here, just to serve as a reminder. If
2377 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2378 * may not have its HDR_L2_WRITING flag set. (the write may have
2379 * completed, in which case HDR_L2_WRITING will be false and the
2380 * b_daddr field will point to the address of the buffer on disk).
2382 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2385 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2386 * l2arc_write_buffers(). Since we've just removed this header
2387 * from the l2arc buffer list, this header will never reach the
2388 * second stage of l2arc_write_buffers(), which increments the
2389 * accounting stats for this header. Thus, we must be careful
2390 * not to decrement them for this header either.
2392 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2393 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2394 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2396 vdev_space_update(dev->l2ad_vdev,
2397 -l2hdr->b_asize, 0, 0);
2399 (void) refcount_remove_many(&dev->l2ad_alloc,
2400 l2hdr->b_asize, hdr);
2403 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2407 arc_hdr_destroy(arc_buf_hdr_t *hdr)
2409 if (HDR_HAS_L1HDR(hdr)) {
2410 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2411 hdr->b_l1hdr.b_datacnt > 0);
2412 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2413 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2415 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2416 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2418 if (HDR_HAS_L2HDR(hdr)) {
2419 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2420 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2423 mutex_enter(&dev->l2ad_mtx);
2426 * Even though we checked this conditional above, we
2427 * need to check this again now that we have the
2428 * l2ad_mtx. This is because we could be racing with
2429 * another thread calling l2arc_evict() which might have
2430 * destroyed this header's L2 portion as we were waiting
2431 * to acquire the l2ad_mtx. If that happens, we don't
2432 * want to re-destroy the header's L2 portion.
2434 if (HDR_HAS_L2HDR(hdr)) {
2436 arc_hdr_l2hdr_destroy(hdr);
2440 mutex_exit(&dev->l2ad_mtx);
2443 if (!BUF_EMPTY(hdr))
2444 buf_discard_identity(hdr);
2446 if (hdr->b_freeze_cksum != NULL) {
2447 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2448 hdr->b_freeze_cksum = NULL;
2451 if (HDR_HAS_L1HDR(hdr)) {
2452 while (hdr->b_l1hdr.b_buf) {
2453 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2455 if (buf->b_efunc != NULL) {
2456 mutex_enter(&arc_user_evicts_lock);
2457 mutex_enter(&buf->b_evict_lock);
2458 ASSERT(buf->b_hdr != NULL);
2459 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
2460 hdr->b_l1hdr.b_buf = buf->b_next;
2461 buf->b_hdr = &arc_eviction_hdr;
2462 buf->b_next = arc_eviction_list;
2463 arc_eviction_list = buf;
2464 mutex_exit(&buf->b_evict_lock);
2465 cv_signal(&arc_user_evicts_cv);
2466 mutex_exit(&arc_user_evicts_lock);
2468 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
2472 if (hdr->b_l1hdr.b_thawed != NULL) {
2473 kmem_free(hdr->b_l1hdr.b_thawed, 1);
2474 hdr->b_l1hdr.b_thawed = NULL;
2479 ASSERT3P(hdr->b_hash_next, ==, NULL);
2480 if (HDR_HAS_L1HDR(hdr)) {
2481 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
2482 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2483 kmem_cache_free(hdr_full_cache, hdr);
2485 kmem_cache_free(hdr_l2only_cache, hdr);
2490 arc_buf_free(arc_buf_t *buf, void *tag)
2492 arc_buf_hdr_t *hdr = buf->b_hdr;
2493 int hashed = hdr->b_l1hdr.b_state != arc_anon;
2495 ASSERT(buf->b_efunc == NULL);
2496 ASSERT(buf->b_data != NULL);
2499 kmutex_t *hash_lock = HDR_LOCK(hdr);
2501 mutex_enter(hash_lock);
2503 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2505 (void) remove_reference(hdr, hash_lock, tag);
2506 if (hdr->b_l1hdr.b_datacnt > 1) {
2507 arc_buf_destroy(buf, TRUE);
2509 ASSERT(buf == hdr->b_l1hdr.b_buf);
2510 ASSERT(buf->b_efunc == NULL);
2511 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2513 mutex_exit(hash_lock);
2514 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2517 * We are in the middle of an async write. Don't destroy
2518 * this buffer unless the write completes before we finish
2519 * decrementing the reference count.
2521 mutex_enter(&arc_user_evicts_lock);
2522 (void) remove_reference(hdr, NULL, tag);
2523 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2524 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2525 mutex_exit(&arc_user_evicts_lock);
2527 arc_hdr_destroy(hdr);
2529 if (remove_reference(hdr, NULL, tag) > 0)
2530 arc_buf_destroy(buf, TRUE);
2532 arc_hdr_destroy(hdr);
2537 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2539 arc_buf_hdr_t *hdr = buf->b_hdr;
2540 kmutex_t *hash_lock = HDR_LOCK(hdr);
2541 boolean_t no_callback = (buf->b_efunc == NULL);
2543 if (hdr->b_l1hdr.b_state == arc_anon) {
2544 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2545 arc_buf_free(buf, tag);
2546 return (no_callback);
2549 mutex_enter(hash_lock);
2551 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2552 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2553 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2554 ASSERT(buf->b_data != NULL);
2556 (void) remove_reference(hdr, hash_lock, tag);
2557 if (hdr->b_l1hdr.b_datacnt > 1) {
2559 arc_buf_destroy(buf, TRUE);
2560 } else if (no_callback) {
2561 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2562 ASSERT(buf->b_efunc == NULL);
2563 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2565 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2566 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2567 mutex_exit(hash_lock);
2568 return (no_callback);
2572 arc_buf_size(arc_buf_t *buf)
2574 return (buf->b_hdr->b_size);
2578 * Called from the DMU to determine if the current buffer should be
2579 * evicted. In order to ensure proper locking, the eviction must be initiated
2580 * from the DMU. Return true if the buffer is associated with user data and
2581 * duplicate buffers still exist.
2584 arc_buf_eviction_needed(arc_buf_t *buf)
2587 boolean_t evict_needed = B_FALSE;
2589 if (zfs_disable_dup_eviction)
2592 mutex_enter(&buf->b_evict_lock);
2596 * We are in arc_do_user_evicts(); let that function
2597 * perform the eviction.
2599 ASSERT(buf->b_data == NULL);
2600 mutex_exit(&buf->b_evict_lock);
2602 } else if (buf->b_data == NULL) {
2604 * We have already been added to the arc eviction list;
2605 * recommend eviction.
2607 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2608 mutex_exit(&buf->b_evict_lock);
2612 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2613 evict_needed = B_TRUE;
2615 mutex_exit(&buf->b_evict_lock);
2616 return (evict_needed);
2620 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2621 * state of the header is dependent on it's state prior to entering this
2622 * function. The following transitions are possible:
2624 * - arc_mru -> arc_mru_ghost
2625 * - arc_mfu -> arc_mfu_ghost
2626 * - arc_mru_ghost -> arc_l2c_only
2627 * - arc_mru_ghost -> deleted
2628 * - arc_mfu_ghost -> arc_l2c_only
2629 * - arc_mfu_ghost -> deleted
2632 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2634 arc_state_t *evicted_state, *state;
2635 int64_t bytes_evicted = 0;
2637 ASSERT(MUTEX_HELD(hash_lock));
2638 ASSERT(HDR_HAS_L1HDR(hdr));
2640 state = hdr->b_l1hdr.b_state;
2641 if (GHOST_STATE(state)) {
2642 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2643 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2646 * l2arc_write_buffers() relies on a header's L1 portion
2647 * (i.e. it's b_tmp_cdata field) during it's write phase.
2648 * Thus, we cannot push a header onto the arc_l2c_only
2649 * state (removing it's L1 piece) until the header is
2650 * done being written to the l2arc.
2652 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2653 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2654 return (bytes_evicted);
2657 ARCSTAT_BUMP(arcstat_deleted);
2658 bytes_evicted += hdr->b_size;
2660 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2662 if (HDR_HAS_L2HDR(hdr)) {
2664 * This buffer is cached on the 2nd Level ARC;
2665 * don't destroy the header.
2667 arc_change_state(arc_l2c_only, hdr, hash_lock);
2669 * dropping from L1+L2 cached to L2-only,
2670 * realloc to remove the L1 header.
2672 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2675 arc_change_state(arc_anon, hdr, hash_lock);
2676 arc_hdr_destroy(hdr);
2678 return (bytes_evicted);
2681 ASSERT(state == arc_mru || state == arc_mfu);
2682 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2684 /* prefetch buffers have a minimum lifespan */
2685 if (HDR_IO_IN_PROGRESS(hdr) ||
2686 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2687 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2688 arc_min_prefetch_lifespan)) {
2689 ARCSTAT_BUMP(arcstat_evict_skip);
2690 return (bytes_evicted);
2693 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2694 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2695 while (hdr->b_l1hdr.b_buf) {
2696 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2697 if (!mutex_tryenter(&buf->b_evict_lock)) {
2698 ARCSTAT_BUMP(arcstat_mutex_miss);
2701 if (buf->b_data != NULL)
2702 bytes_evicted += hdr->b_size;
2703 if (buf->b_efunc != NULL) {
2704 mutex_enter(&arc_user_evicts_lock);
2705 arc_buf_destroy(buf, FALSE);
2706 hdr->b_l1hdr.b_buf = buf->b_next;
2707 buf->b_hdr = &arc_eviction_hdr;
2708 buf->b_next = arc_eviction_list;
2709 arc_eviction_list = buf;
2710 cv_signal(&arc_user_evicts_cv);
2711 mutex_exit(&arc_user_evicts_lock);
2712 mutex_exit(&buf->b_evict_lock);
2714 mutex_exit(&buf->b_evict_lock);
2715 arc_buf_destroy(buf, TRUE);
2719 if (HDR_HAS_L2HDR(hdr)) {
2720 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2722 if (l2arc_write_eligible(hdr->b_spa, hdr))
2723 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2725 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2728 if (hdr->b_l1hdr.b_datacnt == 0) {
2729 arc_change_state(evicted_state, hdr, hash_lock);
2730 ASSERT(HDR_IN_HASH_TABLE(hdr));
2731 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2732 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2733 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2736 return (bytes_evicted);
2740 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2741 uint64_t spa, int64_t bytes)
2743 multilist_sublist_t *mls;
2744 uint64_t bytes_evicted = 0;
2746 kmutex_t *hash_lock;
2747 int evict_count = 0;
2749 ASSERT3P(marker, !=, NULL);
2750 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2752 mls = multilist_sublist_lock(ml, idx);
2754 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2755 hdr = multilist_sublist_prev(mls, marker)) {
2756 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2757 (evict_count >= zfs_arc_evict_batch_limit))
2761 * To keep our iteration location, move the marker
2762 * forward. Since we're not holding hdr's hash lock, we
2763 * must be very careful and not remove 'hdr' from the
2764 * sublist. Otherwise, other consumers might mistake the
2765 * 'hdr' as not being on a sublist when they call the
2766 * multilist_link_active() function (they all rely on
2767 * the hash lock protecting concurrent insertions and
2768 * removals). multilist_sublist_move_forward() was
2769 * specifically implemented to ensure this is the case
2770 * (only 'marker' will be removed and re-inserted).
2772 multilist_sublist_move_forward(mls, marker);
2775 * The only case where the b_spa field should ever be
2776 * zero, is the marker headers inserted by
2777 * arc_evict_state(). It's possible for multiple threads
2778 * to be calling arc_evict_state() concurrently (e.g.
2779 * dsl_pool_close() and zio_inject_fault()), so we must
2780 * skip any markers we see from these other threads.
2782 if (hdr->b_spa == 0)
2785 /* we're only interested in evicting buffers of a certain spa */
2786 if (spa != 0 && hdr->b_spa != spa) {
2787 ARCSTAT_BUMP(arcstat_evict_skip);
2791 hash_lock = HDR_LOCK(hdr);
2794 * We aren't calling this function from any code path
2795 * that would already be holding a hash lock, so we're
2796 * asserting on this assumption to be defensive in case
2797 * this ever changes. Without this check, it would be
2798 * possible to incorrectly increment arcstat_mutex_miss
2799 * below (e.g. if the code changed such that we called
2800 * this function with a hash lock held).
2802 ASSERT(!MUTEX_HELD(hash_lock));
2804 if (mutex_tryenter(hash_lock)) {
2805 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2806 mutex_exit(hash_lock);
2808 bytes_evicted += evicted;
2811 * If evicted is zero, arc_evict_hdr() must have
2812 * decided to skip this header, don't increment
2813 * evict_count in this case.
2819 * If arc_size isn't overflowing, signal any
2820 * threads that might happen to be waiting.
2822 * For each header evicted, we wake up a single
2823 * thread. If we used cv_broadcast, we could
2824 * wake up "too many" threads causing arc_size
2825 * to significantly overflow arc_c; since
2826 * arc_get_data_buf() doesn't check for overflow
2827 * when it's woken up (it doesn't because it's
2828 * possible for the ARC to be overflowing while
2829 * full of un-evictable buffers, and the
2830 * function should proceed in this case).
2832 * If threads are left sleeping, due to not
2833 * using cv_broadcast, they will be woken up
2834 * just before arc_reclaim_thread() sleeps.
2836 mutex_enter(&arc_reclaim_lock);
2837 if (!arc_is_overflowing())
2838 cv_signal(&arc_reclaim_waiters_cv);
2839 mutex_exit(&arc_reclaim_lock);
2841 ARCSTAT_BUMP(arcstat_mutex_miss);
2845 multilist_sublist_unlock(mls);
2847 return (bytes_evicted);
2851 * Evict buffers from the given arc state, until we've removed the
2852 * specified number of bytes. Move the removed buffers to the
2853 * appropriate evict state.
2855 * This function makes a "best effort". It skips over any buffers
2856 * it can't get a hash_lock on, and so, may not catch all candidates.
2857 * It may also return without evicting as much space as requested.
2859 * If bytes is specified using the special value ARC_EVICT_ALL, this
2860 * will evict all available (i.e. unlocked and evictable) buffers from
2861 * the given arc state; which is used by arc_flush().
2864 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2865 arc_buf_contents_t type)
2867 uint64_t total_evicted = 0;
2868 multilist_t *ml = &state->arcs_list[type];
2870 arc_buf_hdr_t **markers;
2872 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
2874 num_sublists = multilist_get_num_sublists(ml);
2877 * If we've tried to evict from each sublist, made some
2878 * progress, but still have not hit the target number of bytes
2879 * to evict, we want to keep trying. The markers allow us to
2880 * pick up where we left off for each individual sublist, rather
2881 * than starting from the tail each time.
2883 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2884 for (int i = 0; i < num_sublists; i++) {
2885 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2888 * A b_spa of 0 is used to indicate that this header is
2889 * a marker. This fact is used in arc_adjust_type() and
2890 * arc_evict_state_impl().
2892 markers[i]->b_spa = 0;
2894 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2895 multilist_sublist_insert_tail(mls, markers[i]);
2896 multilist_sublist_unlock(mls);
2900 * While we haven't hit our target number of bytes to evict, or
2901 * we're evicting all available buffers.
2903 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2905 * Start eviction using a randomly selected sublist,
2906 * this is to try and evenly balance eviction across all
2907 * sublists. Always starting at the same sublist
2908 * (e.g. index 0) would cause evictions to favor certain
2909 * sublists over others.
2911 int sublist_idx = multilist_get_random_index(ml);
2912 uint64_t scan_evicted = 0;
2914 for (int i = 0; i < num_sublists; i++) {
2915 uint64_t bytes_remaining;
2916 uint64_t bytes_evicted;
2918 if (bytes == ARC_EVICT_ALL)
2919 bytes_remaining = ARC_EVICT_ALL;
2920 else if (total_evicted < bytes)
2921 bytes_remaining = bytes - total_evicted;
2925 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2926 markers[sublist_idx], spa, bytes_remaining);
2928 scan_evicted += bytes_evicted;
2929 total_evicted += bytes_evicted;
2931 /* we've reached the end, wrap to the beginning */
2932 if (++sublist_idx >= num_sublists)
2937 * If we didn't evict anything during this scan, we have
2938 * no reason to believe we'll evict more during another
2939 * scan, so break the loop.
2941 if (scan_evicted == 0) {
2942 /* This isn't possible, let's make that obvious */
2943 ASSERT3S(bytes, !=, 0);
2946 * When bytes is ARC_EVICT_ALL, the only way to
2947 * break the loop is when scan_evicted is zero.
2948 * In that case, we actually have evicted enough,
2949 * so we don't want to increment the kstat.
2951 if (bytes != ARC_EVICT_ALL) {
2952 ASSERT3S(total_evicted, <, bytes);
2953 ARCSTAT_BUMP(arcstat_evict_not_enough);
2960 for (int i = 0; i < num_sublists; i++) {
2961 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2962 multilist_sublist_remove(mls, markers[i]);
2963 multilist_sublist_unlock(mls);
2965 kmem_cache_free(hdr_full_cache, markers[i]);
2967 kmem_free(markers, sizeof (*markers) * num_sublists);
2969 return (total_evicted);
2973 * Flush all "evictable" data of the given type from the arc state
2974 * specified. This will not evict any "active" buffers (i.e. referenced).
2976 * When 'retry' is set to FALSE, the function will make a single pass
2977 * over the state and evict any buffers that it can. Since it doesn't
2978 * continually retry the eviction, it might end up leaving some buffers
2979 * in the ARC due to lock misses.
2981 * When 'retry' is set to TRUE, the function will continually retry the
2982 * eviction until *all* evictable buffers have been removed from the
2983 * state. As a result, if concurrent insertions into the state are
2984 * allowed (e.g. if the ARC isn't shutting down), this function might
2985 * wind up in an infinite loop, continually trying to evict buffers.
2988 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2991 uint64_t evicted = 0;
2993 while (state->arcs_lsize[type] != 0) {
2994 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3004 * Evict the specified number of bytes from the state specified,
3005 * restricting eviction to the spa and type given. This function
3006 * prevents us from trying to evict more from a state's list than
3007 * is "evictable", and to skip evicting altogether when passed a
3008 * negative value for "bytes". In contrast, arc_evict_state() will
3009 * evict everything it can, when passed a negative value for "bytes".
3012 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3013 arc_buf_contents_t type)
3017 if (bytes > 0 && state->arcs_lsize[type] > 0) {
3018 delta = MIN(state->arcs_lsize[type], bytes);
3019 return (arc_evict_state(state, spa, delta, type));
3026 * Evict metadata buffers from the cache, such that arc_meta_used is
3027 * capped by the arc_meta_limit tunable.
3030 arc_adjust_meta(void)
3032 uint64_t total_evicted = 0;
3036 * If we're over the meta limit, we want to evict enough
3037 * metadata to get back under the meta limit. We don't want to
3038 * evict so much that we drop the MRU below arc_p, though. If
3039 * we're over the meta limit more than we're over arc_p, we
3040 * evict some from the MRU here, and some from the MFU below.
3042 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3043 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3044 refcount_count(&arc_mru->arcs_size) - arc_p));
3046 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3049 * Similar to the above, we want to evict enough bytes to get us
3050 * below the meta limit, but not so much as to drop us below the
3051 * space alloted to the MFU (which is defined as arc_c - arc_p).
3053 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
3054 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
3056 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3058 return (total_evicted);
3062 * Return the type of the oldest buffer in the given arc state
3064 * This function will select a random sublist of type ARC_BUFC_DATA and
3065 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3066 * is compared, and the type which contains the "older" buffer will be
3069 static arc_buf_contents_t
3070 arc_adjust_type(arc_state_t *state)
3072 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
3073 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
3074 int data_idx = multilist_get_random_index(data_ml);
3075 int meta_idx = multilist_get_random_index(meta_ml);
3076 multilist_sublist_t *data_mls;
3077 multilist_sublist_t *meta_mls;
3078 arc_buf_contents_t type;
3079 arc_buf_hdr_t *data_hdr;
3080 arc_buf_hdr_t *meta_hdr;
3083 * We keep the sublist lock until we're finished, to prevent
3084 * the headers from being destroyed via arc_evict_state().
3086 data_mls = multilist_sublist_lock(data_ml, data_idx);
3087 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3090 * These two loops are to ensure we skip any markers that
3091 * might be at the tail of the lists due to arc_evict_state().
3094 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3095 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3096 if (data_hdr->b_spa != 0)
3100 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3101 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3102 if (meta_hdr->b_spa != 0)
3106 if (data_hdr == NULL && meta_hdr == NULL) {
3107 type = ARC_BUFC_DATA;
3108 } else if (data_hdr == NULL) {
3109 ASSERT3P(meta_hdr, !=, NULL);
3110 type = ARC_BUFC_METADATA;
3111 } else if (meta_hdr == NULL) {
3112 ASSERT3P(data_hdr, !=, NULL);
3113 type = ARC_BUFC_DATA;
3115 ASSERT3P(data_hdr, !=, NULL);
3116 ASSERT3P(meta_hdr, !=, NULL);
3118 /* The headers can't be on the sublist without an L1 header */
3119 ASSERT(HDR_HAS_L1HDR(data_hdr));
3120 ASSERT(HDR_HAS_L1HDR(meta_hdr));
3122 if (data_hdr->b_l1hdr.b_arc_access <
3123 meta_hdr->b_l1hdr.b_arc_access) {
3124 type = ARC_BUFC_DATA;
3126 type = ARC_BUFC_METADATA;
3130 multilist_sublist_unlock(meta_mls);
3131 multilist_sublist_unlock(data_mls);
3137 * Evict buffers from the cache, such that arc_size is capped by arc_c.
3142 uint64_t total_evicted = 0;
3147 * If we're over arc_meta_limit, we want to correct that before
3148 * potentially evicting data buffers below.
3150 total_evicted += arc_adjust_meta();
3155 * If we're over the target cache size, we want to evict enough
3156 * from the list to get back to our target size. We don't want
3157 * to evict too much from the MRU, such that it drops below
3158 * arc_p. So, if we're over our target cache size more than
3159 * the MRU is over arc_p, we'll evict enough to get back to
3160 * arc_p here, and then evict more from the MFU below.
3162 target = MIN((int64_t)(arc_size - arc_c),
3163 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3164 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
3167 * If we're below arc_meta_min, always prefer to evict data.
3168 * Otherwise, try to satisfy the requested number of bytes to
3169 * evict from the type which contains older buffers; in an
3170 * effort to keep newer buffers in the cache regardless of their
3171 * type. If we cannot satisfy the number of bytes from this
3172 * type, spill over into the next type.
3174 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3175 arc_meta_used > arc_meta_min) {
3176 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3177 total_evicted += bytes;
3180 * If we couldn't evict our target number of bytes from
3181 * metadata, we try to get the rest from data.
3186 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3188 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3189 total_evicted += bytes;
3192 * If we couldn't evict our target number of bytes from
3193 * data, we try to get the rest from metadata.
3198 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3204 * Now that we've tried to evict enough from the MRU to get its
3205 * size back to arc_p, if we're still above the target cache
3206 * size, we evict the rest from the MFU.
3208 target = arc_size - arc_c;
3210 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3211 arc_meta_used > arc_meta_min) {
3212 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3213 total_evicted += bytes;
3216 * If we couldn't evict our target number of bytes from
3217 * metadata, we try to get the rest from data.
3222 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3224 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3225 total_evicted += bytes;
3228 * If we couldn't evict our target number of bytes from
3229 * data, we try to get the rest from data.
3234 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3238 * Adjust ghost lists
3240 * In addition to the above, the ARC also defines target values
3241 * for the ghost lists. The sum of the mru list and mru ghost
3242 * list should never exceed the target size of the cache, and
3243 * the sum of the mru list, mfu list, mru ghost list, and mfu
3244 * ghost list should never exceed twice the target size of the
3245 * cache. The following logic enforces these limits on the ghost
3246 * caches, and evicts from them as needed.
3248 target = refcount_count(&arc_mru->arcs_size) +
3249 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3251 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3252 total_evicted += bytes;
3257 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3260 * We assume the sum of the mru list and mfu list is less than
3261 * or equal to arc_c (we enforced this above), which means we
3262 * can use the simpler of the two equations below:
3264 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3265 * mru ghost + mfu ghost <= arc_c
3267 target = refcount_count(&arc_mru_ghost->arcs_size) +
3268 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3270 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3271 total_evicted += bytes;
3276 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3278 return (total_evicted);
3282 arc_do_user_evicts(void)
3284 mutex_enter(&arc_user_evicts_lock);
3285 while (arc_eviction_list != NULL) {
3286 arc_buf_t *buf = arc_eviction_list;
3287 arc_eviction_list = buf->b_next;
3288 mutex_enter(&buf->b_evict_lock);
3290 mutex_exit(&buf->b_evict_lock);
3291 mutex_exit(&arc_user_evicts_lock);
3293 if (buf->b_efunc != NULL)
3294 VERIFY0(buf->b_efunc(buf->b_private));
3296 buf->b_efunc = NULL;
3297 buf->b_private = NULL;
3298 kmem_cache_free(buf_cache, buf);
3299 mutex_enter(&arc_user_evicts_lock);
3301 mutex_exit(&arc_user_evicts_lock);
3305 arc_flush(spa_t *spa, boolean_t retry)
3310 * If retry is TRUE, a spa must not be specified since we have
3311 * no good way to determine if all of a spa's buffers have been
3312 * evicted from an arc state.
3314 ASSERT(!retry || spa == 0);
3317 guid = spa_load_guid(spa);
3319 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3320 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3322 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3323 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3325 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3326 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3328 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3329 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3331 arc_do_user_evicts();
3332 ASSERT(spa || arc_eviction_list == NULL);
3336 arc_shrink(int64_t to_free)
3338 if (arc_c > arc_c_min) {
3339 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3340 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3341 if (arc_c > arc_c_min + to_free)
3342 atomic_add_64(&arc_c, -to_free);
3346 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3347 if (arc_c > arc_size)
3348 arc_c = MAX(arc_size, arc_c_min);
3350 arc_p = (arc_c >> 1);
3352 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3355 ASSERT(arc_c >= arc_c_min);
3356 ASSERT((int64_t)arc_p >= 0);
3359 if (arc_size > arc_c) {
3360 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3362 (void) arc_adjust();
3366 static long needfree = 0;
3368 typedef enum free_memory_reason_t {
3373 FMR_PAGES_PP_MAXIMUM,
3377 } free_memory_reason_t;
3379 int64_t last_free_memory;
3380 free_memory_reason_t last_free_reason;
3383 * Additional reserve of pages for pp_reserve.
3385 int64_t arc_pages_pp_reserve = 64;
3388 * Additional reserve of pages for swapfs.
3390 int64_t arc_swapfs_reserve = 64;
3393 * Return the amount of memory that can be consumed before reclaim will be
3394 * needed. Positive if there is sufficient free memory, negative indicates
3395 * the amount of memory that needs to be freed up.
3398 arc_available_memory(void)
3400 int64_t lowest = INT64_MAX;
3402 free_memory_reason_t r = FMR_UNKNOWN;
3406 n = PAGESIZE * (-needfree);
3414 * Cooperate with pagedaemon when it's time for it to scan
3415 * and reclaim some pages.
3417 n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3425 * check that we're out of range of the pageout scanner. It starts to
3426 * schedule paging if freemem is less than lotsfree and needfree.
3427 * lotsfree is the high-water mark for pageout, and needfree is the
3428 * number of needed free pages. We add extra pages here to make sure
3429 * the scanner doesn't start up while we're freeing memory.
3431 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3438 * check to make sure that swapfs has enough space so that anon
3439 * reservations can still succeed. anon_resvmem() checks that the
3440 * availrmem is greater than swapfs_minfree, and the number of reserved
3441 * swap pages. We also add a bit of extra here just to prevent
3442 * circumstances from getting really dire.
3444 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3445 desfree - arc_swapfs_reserve);
3448 r = FMR_SWAPFS_MINFREE;
3453 * Check that we have enough availrmem that memory locking (e.g., via
3454 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3455 * stores the number of pages that cannot be locked; when availrmem
3456 * drops below pages_pp_maximum, page locking mechanisms such as
3457 * page_pp_lock() will fail.)
3459 n = PAGESIZE * (availrmem - pages_pp_maximum -
3460 arc_pages_pp_reserve);
3463 r = FMR_PAGES_PP_MAXIMUM;
3466 #endif /* illumos */
3467 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3469 * If we're on an i386 platform, it's possible that we'll exhaust the
3470 * kernel heap space before we ever run out of available physical
3471 * memory. Most checks of the size of the heap_area compare against
3472 * tune.t_minarmem, which is the minimum available real memory that we
3473 * can have in the system. However, this is generally fixed at 25 pages
3474 * which is so low that it's useless. In this comparison, we seek to
3475 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3476 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3479 n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3480 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3485 #define zio_arena NULL
3487 #define zio_arena heap_arena
3491 * If zio data pages are being allocated out of a separate heap segment,
3492 * then enforce that the size of available vmem for this arena remains
3493 * above about 1/16th free.
3495 * Note: The 1/16th arena free requirement was put in place
3496 * to aggressively evict memory from the arc in order to avoid
3497 * memory fragmentation issues.
3499 if (zio_arena != NULL) {
3500 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3501 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3509 * Above limits know nothing about real level of KVA fragmentation.
3510 * Start aggressive reclamation if too little sequential KVA left.
3513 n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3514 -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3523 /* Every 100 calls, free a small amount */
3524 if (spa_get_random(100) == 0)
3526 #endif /* _KERNEL */
3528 last_free_memory = lowest;
3529 last_free_reason = r;
3530 DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3536 * Determine if the system is under memory pressure and is asking
3537 * to reclaim memory. A return value of TRUE indicates that the system
3538 * is under memory pressure and that the arc should adjust accordingly.
3541 arc_reclaim_needed(void)
3543 return (arc_available_memory() < 0);
3546 extern kmem_cache_t *zio_buf_cache[];
3547 extern kmem_cache_t *zio_data_buf_cache[];
3548 extern kmem_cache_t *range_seg_cache;
3550 static __noinline void
3551 arc_kmem_reap_now(void)
3554 kmem_cache_t *prev_cache = NULL;
3555 kmem_cache_t *prev_data_cache = NULL;
3557 DTRACE_PROBE(arc__kmem_reap_start);
3559 if (arc_meta_used >= arc_meta_limit) {
3561 * We are exceeding our meta-data cache limit.
3562 * Purge some DNLC entries to release holds on meta-data.
3564 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3568 * Reclaim unused memory from all kmem caches.
3574 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3575 if (zio_buf_cache[i] != prev_cache) {
3576 prev_cache = zio_buf_cache[i];
3577 kmem_cache_reap_now(zio_buf_cache[i]);
3579 if (zio_data_buf_cache[i] != prev_data_cache) {
3580 prev_data_cache = zio_data_buf_cache[i];
3581 kmem_cache_reap_now(zio_data_buf_cache[i]);
3584 kmem_cache_reap_now(buf_cache);
3585 kmem_cache_reap_now(hdr_full_cache);
3586 kmem_cache_reap_now(hdr_l2only_cache);
3587 kmem_cache_reap_now(range_seg_cache);
3590 if (zio_arena != NULL) {
3592 * Ask the vmem arena to reclaim unused memory from its
3595 vmem_qcache_reap(zio_arena);
3598 DTRACE_PROBE(arc__kmem_reap_end);
3602 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3603 * enough data and signal them to proceed. When this happens, the threads in
3604 * arc_get_data_buf() are sleeping while holding the hash lock for their
3605 * particular arc header. Thus, we must be careful to never sleep on a
3606 * hash lock in this thread. This is to prevent the following deadlock:
3608 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3609 * waiting for the reclaim thread to signal it.
3611 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3612 * fails, and goes to sleep forever.
3614 * This possible deadlock is avoided by always acquiring a hash lock
3615 * using mutex_tryenter() from arc_reclaim_thread().
3618 arc_reclaim_thread(void *dummy __unused)
3620 hrtime_t growtime = 0;
3623 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
3625 mutex_enter(&arc_reclaim_lock);
3626 while (!arc_reclaim_thread_exit) {
3627 int64_t free_memory = arc_available_memory();
3628 uint64_t evicted = 0;
3630 mutex_exit(&arc_reclaim_lock);
3632 if (free_memory < 0) {
3634 arc_no_grow = B_TRUE;
3638 * Wait at least zfs_grow_retry (default 60) seconds
3639 * before considering growing.
3641 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
3643 arc_kmem_reap_now();
3646 * If we are still low on memory, shrink the ARC
3647 * so that we have arc_shrink_min free space.
3649 free_memory = arc_available_memory();
3652 (arc_c >> arc_shrink_shift) - free_memory;
3655 to_free = MAX(to_free, ptob(needfree));
3657 arc_shrink(to_free);
3659 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3660 arc_no_grow = B_TRUE;
3661 } else if (gethrtime() >= growtime) {
3662 arc_no_grow = B_FALSE;
3665 evicted = arc_adjust();
3667 mutex_enter(&arc_reclaim_lock);
3670 * If evicted is zero, we couldn't evict anything via
3671 * arc_adjust(). This could be due to hash lock
3672 * collisions, but more likely due to the majority of
3673 * arc buffers being unevictable. Therefore, even if
3674 * arc_size is above arc_c, another pass is unlikely to
3675 * be helpful and could potentially cause us to enter an
3678 if (arc_size <= arc_c || evicted == 0) {
3683 * We're either no longer overflowing, or we
3684 * can't evict anything more, so we should wake
3685 * up any threads before we go to sleep.
3687 cv_broadcast(&arc_reclaim_waiters_cv);
3690 * Block until signaled, or after one second (we
3691 * might need to perform arc_kmem_reap_now()
3692 * even if we aren't being signalled)
3694 CALLB_CPR_SAFE_BEGIN(&cpr);
3695 (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
3696 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
3697 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3701 arc_reclaim_thread_exit = FALSE;
3702 cv_broadcast(&arc_reclaim_thread_cv);
3703 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3708 arc_user_evicts_thread(void *dummy __unused)
3712 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
3714 mutex_enter(&arc_user_evicts_lock);
3715 while (!arc_user_evicts_thread_exit) {
3716 mutex_exit(&arc_user_evicts_lock);
3718 arc_do_user_evicts();
3721 * This is necessary in order for the mdb ::arc dcmd to
3722 * show up to date information. Since the ::arc command
3723 * does not call the kstat's update function, without
3724 * this call, the command may show stale stats for the
3725 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3726 * with this change, the data might be up to 1 second
3727 * out of date; but that should suffice. The arc_state_t
3728 * structures can be queried directly if more accurate
3729 * information is needed.
3731 if (arc_ksp != NULL)
3732 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3734 mutex_enter(&arc_user_evicts_lock);
3737 * Block until signaled, or after one second (we need to
3738 * call the arc's kstat update function regularly).
3740 CALLB_CPR_SAFE_BEGIN(&cpr);
3741 (void) cv_timedwait(&arc_user_evicts_cv,
3742 &arc_user_evicts_lock, hz);
3743 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
3746 arc_user_evicts_thread_exit = FALSE;
3747 cv_broadcast(&arc_user_evicts_cv);
3748 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
3753 * Adapt arc info given the number of bytes we are trying to add and
3754 * the state that we are comming from. This function is only called
3755 * when we are adding new content to the cache.
3758 arc_adapt(int bytes, arc_state_t *state)
3761 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3762 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3763 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
3765 if (state == arc_l2c_only)
3770 * Adapt the target size of the MRU list:
3771 * - if we just hit in the MRU ghost list, then increase
3772 * the target size of the MRU list.
3773 * - if we just hit in the MFU ghost list, then increase
3774 * the target size of the MFU list by decreasing the
3775 * target size of the MRU list.
3777 if (state == arc_mru_ghost) {
3778 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
3779 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3781 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3782 } else if (state == arc_mfu_ghost) {
3785 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
3786 mult = MIN(mult, 10);
3788 delta = MIN(bytes * mult, arc_p);
3789 arc_p = MAX(arc_p_min, arc_p - delta);
3791 ASSERT((int64_t)arc_p >= 0);
3793 if (arc_reclaim_needed()) {
3794 cv_signal(&arc_reclaim_thread_cv);
3801 if (arc_c >= arc_c_max)
3805 * If we're within (2 * maxblocksize) bytes of the target
3806 * cache size, increment the target cache size
3808 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3809 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3810 atomic_add_64(&arc_c, (int64_t)bytes);
3811 if (arc_c > arc_c_max)
3813 else if (state == arc_anon)
3814 atomic_add_64(&arc_p, (int64_t)bytes);
3818 ASSERT((int64_t)arc_p >= 0);
3822 * Check if arc_size has grown past our upper threshold, determined by
3823 * zfs_arc_overflow_shift.
3826 arc_is_overflowing(void)
3828 /* Always allow at least one block of overflow */
3829 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3830 arc_c >> zfs_arc_overflow_shift);
3832 return (arc_size >= arc_c + overflow);
3836 * The buffer, supplied as the first argument, needs a data block. If we
3837 * are hitting the hard limit for the cache size, we must sleep, waiting
3838 * for the eviction thread to catch up. If we're past the target size
3839 * but below the hard limit, we'll only signal the reclaim thread and
3843 arc_get_data_buf(arc_buf_t *buf)
3845 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
3846 uint64_t size = buf->b_hdr->b_size;
3847 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
3849 arc_adapt(size, state);
3852 * If arc_size is currently overflowing, and has grown past our
3853 * upper limit, we must be adding data faster than the evict
3854 * thread can evict. Thus, to ensure we don't compound the
3855 * problem by adding more data and forcing arc_size to grow even
3856 * further past it's target size, we halt and wait for the
3857 * eviction thread to catch up.
3859 * It's also possible that the reclaim thread is unable to evict
3860 * enough buffers to get arc_size below the overflow limit (e.g.
3861 * due to buffers being un-evictable, or hash lock collisions).
3862 * In this case, we want to proceed regardless if we're
3863 * overflowing; thus we don't use a while loop here.
3865 if (arc_is_overflowing()) {
3866 mutex_enter(&arc_reclaim_lock);
3869 * Now that we've acquired the lock, we may no longer be
3870 * over the overflow limit, lets check.
3872 * We're ignoring the case of spurious wake ups. If that
3873 * were to happen, it'd let this thread consume an ARC
3874 * buffer before it should have (i.e. before we're under
3875 * the overflow limit and were signalled by the reclaim
3876 * thread). As long as that is a rare occurrence, it
3877 * shouldn't cause any harm.
3879 if (arc_is_overflowing()) {
3880 cv_signal(&arc_reclaim_thread_cv);
3881 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
3884 mutex_exit(&arc_reclaim_lock);
3887 if (type == ARC_BUFC_METADATA) {
3888 buf->b_data = zio_buf_alloc(size);
3889 arc_space_consume(size, ARC_SPACE_META);
3891 ASSERT(type == ARC_BUFC_DATA);
3892 buf->b_data = zio_data_buf_alloc(size);
3893 arc_space_consume(size, ARC_SPACE_DATA);
3897 * Update the state size. Note that ghost states have a
3898 * "ghost size" and so don't need to be updated.
3900 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3901 arc_buf_hdr_t *hdr = buf->b_hdr;
3902 arc_state_t *state = hdr->b_l1hdr.b_state;
3904 (void) refcount_add_many(&state->arcs_size, size, buf);
3907 * If this is reached via arc_read, the link is
3908 * protected by the hash lock. If reached via
3909 * arc_buf_alloc, the header should not be accessed by
3910 * any other thread. And, if reached via arc_read_done,
3911 * the hash lock will protect it if it's found in the
3912 * hash table; otherwise no other thread should be
3913 * trying to [add|remove]_reference it.
3915 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3916 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3917 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3921 * If we are growing the cache, and we are adding anonymous
3922 * data, and we have outgrown arc_p, update arc_p
3924 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3925 (refcount_count(&arc_anon->arcs_size) +
3926 refcount_count(&arc_mru->arcs_size) > arc_p))
3927 arc_p = MIN(arc_c, arc_p + size);
3929 ARCSTAT_BUMP(arcstat_allocated);
3933 * This routine is called whenever a buffer is accessed.
3934 * NOTE: the hash lock is dropped in this function.
3937 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3941 ASSERT(MUTEX_HELD(hash_lock));
3942 ASSERT(HDR_HAS_L1HDR(hdr));
3944 if (hdr->b_l1hdr.b_state == arc_anon) {
3946 * This buffer is not in the cache, and does not
3947 * appear in our "ghost" list. Add the new buffer
3951 ASSERT0(hdr->b_l1hdr.b_arc_access);
3952 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3953 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3954 arc_change_state(arc_mru, hdr, hash_lock);
3956 } else if (hdr->b_l1hdr.b_state == arc_mru) {
3957 now = ddi_get_lbolt();
3960 * If this buffer is here because of a prefetch, then either:
3961 * - clear the flag if this is a "referencing" read
3962 * (any subsequent access will bump this into the MFU state).
3964 * - move the buffer to the head of the list if this is
3965 * another prefetch (to make it less likely to be evicted).
3967 if (HDR_PREFETCH(hdr)) {
3968 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3969 /* link protected by hash lock */
3970 ASSERT(multilist_link_active(
3971 &hdr->b_l1hdr.b_arc_node));
3973 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3974 ARCSTAT_BUMP(arcstat_mru_hits);
3976 hdr->b_l1hdr.b_arc_access = now;
3981 * This buffer has been "accessed" only once so far,
3982 * but it is still in the cache. Move it to the MFU
3985 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3987 * More than 125ms have passed since we
3988 * instantiated this buffer. Move it to the
3989 * most frequently used state.
3991 hdr->b_l1hdr.b_arc_access = now;
3992 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3993 arc_change_state(arc_mfu, hdr, hash_lock);
3995 ARCSTAT_BUMP(arcstat_mru_hits);
3996 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3997 arc_state_t *new_state;
3999 * This buffer has been "accessed" recently, but
4000 * was evicted from the cache. Move it to the
4004 if (HDR_PREFETCH(hdr)) {
4005 new_state = arc_mru;
4006 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4007 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
4008 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4010 new_state = arc_mfu;
4011 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4014 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4015 arc_change_state(new_state, hdr, hash_lock);
4017 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4018 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
4020 * This buffer has been accessed more than once and is
4021 * still in the cache. Keep it in the MFU state.
4023 * NOTE: an add_reference() that occurred when we did
4024 * the arc_read() will have kicked this off the list.
4025 * If it was a prefetch, we will explicitly move it to
4026 * the head of the list now.
4028 if ((HDR_PREFETCH(hdr)) != 0) {
4029 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4030 /* link protected by hash_lock */
4031 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4033 ARCSTAT_BUMP(arcstat_mfu_hits);
4034 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4035 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4036 arc_state_t *new_state = arc_mfu;
4038 * This buffer has been accessed more than once but has
4039 * been evicted from the cache. Move it back to the
4043 if (HDR_PREFETCH(hdr)) {
4045 * This is a prefetch access...
4046 * move this block back to the MRU state.
4048 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
4049 new_state = arc_mru;
4052 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4053 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4054 arc_change_state(new_state, hdr, hash_lock);
4056 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4057 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4059 * This buffer is on the 2nd Level ARC.
4062 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4063 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4064 arc_change_state(arc_mfu, hdr, hash_lock);
4066 ASSERT(!"invalid arc state");
4070 /* a generic arc_done_func_t which you can use */
4073 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4075 if (zio == NULL || zio->io_error == 0)
4076 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
4077 VERIFY(arc_buf_remove_ref(buf, arg));
4080 /* a generic arc_done_func_t */
4082 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4084 arc_buf_t **bufp = arg;
4085 if (zio && zio->io_error) {
4086 VERIFY(arc_buf_remove_ref(buf, arg));
4090 ASSERT(buf->b_data);
4095 arc_read_done(zio_t *zio)
4099 arc_buf_t *abuf; /* buffer we're assigning to callback */
4100 kmutex_t *hash_lock = NULL;
4101 arc_callback_t *callback_list, *acb;
4102 int freeable = FALSE;
4104 buf = zio->io_private;
4108 * The hdr was inserted into hash-table and removed from lists
4109 * prior to starting I/O. We should find this header, since
4110 * it's in the hash table, and it should be legit since it's
4111 * not possible to evict it during the I/O. The only possible
4112 * reason for it not to be found is if we were freed during the
4115 if (HDR_IN_HASH_TABLE(hdr)) {
4116 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4117 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4118 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4119 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4120 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4122 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4125 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4126 hash_lock == NULL) ||
4128 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4129 (found == hdr && HDR_L2_READING(hdr)));
4132 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
4133 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4134 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
4136 /* byteswap if necessary */
4137 callback_list = hdr->b_l1hdr.b_acb;
4138 ASSERT(callback_list != NULL);
4139 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
4140 dmu_object_byteswap_t bswap =
4141 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4142 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
4143 byteswap_uint64_array :
4144 dmu_ot_byteswap[bswap].ob_func;
4145 func(buf->b_data, hdr->b_size);
4148 arc_cksum_compute(buf, B_FALSE);
4153 if (hash_lock && zio->io_error == 0 &&
4154 hdr->b_l1hdr.b_state == arc_anon) {
4156 * Only call arc_access on anonymous buffers. This is because
4157 * if we've issued an I/O for an evicted buffer, we've already
4158 * called arc_access (to prevent any simultaneous readers from
4159 * getting confused).
4161 arc_access(hdr, hash_lock);
4164 /* create copies of the data buffer for the callers */
4166 for (acb = callback_list; acb; acb = acb->acb_next) {
4167 if (acb->acb_done) {
4169 ARCSTAT_BUMP(arcstat_duplicate_reads);
4170 abuf = arc_buf_clone(buf);
4172 acb->acb_buf = abuf;
4176 hdr->b_l1hdr.b_acb = NULL;
4177 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4178 ASSERT(!HDR_BUF_AVAILABLE(hdr));
4180 ASSERT(buf->b_efunc == NULL);
4181 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4182 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4185 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4186 callback_list != NULL);
4188 if (zio->io_error != 0) {
4189 hdr->b_flags |= ARC_FLAG_IO_ERROR;
4190 if (hdr->b_l1hdr.b_state != arc_anon)
4191 arc_change_state(arc_anon, hdr, hash_lock);
4192 if (HDR_IN_HASH_TABLE(hdr))
4193 buf_hash_remove(hdr);
4194 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4198 * Broadcast before we drop the hash_lock to avoid the possibility
4199 * that the hdr (and hence the cv) might be freed before we get to
4200 * the cv_broadcast().
4202 cv_broadcast(&hdr->b_l1hdr.b_cv);
4204 if (hash_lock != NULL) {
4205 mutex_exit(hash_lock);
4208 * This block was freed while we waited for the read to
4209 * complete. It has been removed from the hash table and
4210 * moved to the anonymous state (so that it won't show up
4213 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4214 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4217 /* execute each callback and free its structure */
4218 while ((acb = callback_list) != NULL) {
4220 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4222 if (acb->acb_zio_dummy != NULL) {
4223 acb->acb_zio_dummy->io_error = zio->io_error;
4224 zio_nowait(acb->acb_zio_dummy);
4227 callback_list = acb->acb_next;
4228 kmem_free(acb, sizeof (arc_callback_t));
4232 arc_hdr_destroy(hdr);
4236 * "Read" the block at the specified DVA (in bp) via the
4237 * cache. If the block is found in the cache, invoke the provided
4238 * callback immediately and return. Note that the `zio' parameter
4239 * in the callback will be NULL in this case, since no IO was
4240 * required. If the block is not in the cache pass the read request
4241 * on to the spa with a substitute callback function, so that the
4242 * requested block will be added to the cache.
4244 * If a read request arrives for a block that has a read in-progress,
4245 * either wait for the in-progress read to complete (and return the
4246 * results); or, if this is a read with a "done" func, add a record
4247 * to the read to invoke the "done" func when the read completes,
4248 * and return; or just return.
4250 * arc_read_done() will invoke all the requested "done" functions
4251 * for readers of this block.
4254 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4255 void *private, zio_priority_t priority, int zio_flags,
4256 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4258 arc_buf_hdr_t *hdr = NULL;
4259 arc_buf_t *buf = NULL;
4260 kmutex_t *hash_lock = NULL;
4262 uint64_t guid = spa_load_guid(spa);
4264 ASSERT(!BP_IS_EMBEDDED(bp) ||
4265 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4268 if (!BP_IS_EMBEDDED(bp)) {
4270 * Embedded BP's have no DVA and require no I/O to "read".
4271 * Create an anonymous arc buf to back it.
4273 hdr = buf_hash_find(guid, bp, &hash_lock);
4276 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
4278 *arc_flags |= ARC_FLAG_CACHED;
4280 if (HDR_IO_IN_PROGRESS(hdr)) {
4282 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4283 priority == ZIO_PRIORITY_SYNC_READ) {
4285 * This sync read must wait for an
4286 * in-progress async read (e.g. a predictive
4287 * prefetch). Async reads are queued
4288 * separately at the vdev_queue layer, so
4289 * this is a form of priority inversion.
4290 * Ideally, we would "inherit" the demand
4291 * i/o's priority by moving the i/o from
4292 * the async queue to the synchronous queue,
4293 * but there is currently no mechanism to do
4294 * so. Track this so that we can evaluate
4295 * the magnitude of this potential performance
4298 * Note that if the prefetch i/o is already
4299 * active (has been issued to the device),
4300 * the prefetch improved performance, because
4301 * we issued it sooner than we would have
4302 * without the prefetch.
4304 DTRACE_PROBE1(arc__sync__wait__for__async,
4305 arc_buf_hdr_t *, hdr);
4306 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4308 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4309 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4312 if (*arc_flags & ARC_FLAG_WAIT) {
4313 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
4314 mutex_exit(hash_lock);
4317 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4320 arc_callback_t *acb = NULL;
4322 acb = kmem_zalloc(sizeof (arc_callback_t),
4324 acb->acb_done = done;
4325 acb->acb_private = private;
4327 acb->acb_zio_dummy = zio_null(pio,
4328 spa, NULL, NULL, NULL, zio_flags);
4330 ASSERT(acb->acb_done != NULL);
4331 acb->acb_next = hdr->b_l1hdr.b_acb;
4332 hdr->b_l1hdr.b_acb = acb;
4333 add_reference(hdr, hash_lock, private);
4334 mutex_exit(hash_lock);
4337 mutex_exit(hash_lock);
4341 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4342 hdr->b_l1hdr.b_state == arc_mfu);
4345 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4347 * This is a demand read which does not have to
4348 * wait for i/o because we did a predictive
4349 * prefetch i/o for it, which has completed.
4352 arc__demand__hit__predictive__prefetch,
4353 arc_buf_hdr_t *, hdr);
4355 arcstat_demand_hit_predictive_prefetch);
4356 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4358 add_reference(hdr, hash_lock, private);
4360 * If this block is already in use, create a new
4361 * copy of the data so that we will be guaranteed
4362 * that arc_release() will always succeed.
4364 buf = hdr->b_l1hdr.b_buf;
4366 ASSERT(buf->b_data);
4367 if (HDR_BUF_AVAILABLE(hdr)) {
4368 ASSERT(buf->b_efunc == NULL);
4369 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4371 buf = arc_buf_clone(buf);
4374 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
4375 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4376 hdr->b_flags |= ARC_FLAG_PREFETCH;
4378 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4379 arc_access(hdr, hash_lock);
4380 if (*arc_flags & ARC_FLAG_L2CACHE)
4381 hdr->b_flags |= ARC_FLAG_L2CACHE;
4382 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4383 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4384 mutex_exit(hash_lock);
4385 ARCSTAT_BUMP(arcstat_hits);
4386 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4387 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4388 data, metadata, hits);
4391 done(NULL, buf, private);
4393 uint64_t size = BP_GET_LSIZE(bp);
4394 arc_callback_t *acb;
4397 boolean_t devw = B_FALSE;
4398 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4399 int32_t b_asize = 0;
4402 /* this block is not in the cache */
4403 arc_buf_hdr_t *exists = NULL;
4404 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4405 buf = arc_buf_alloc(spa, size, private, type);
4407 if (!BP_IS_EMBEDDED(bp)) {
4408 hdr->b_dva = *BP_IDENTITY(bp);
4409 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4410 exists = buf_hash_insert(hdr, &hash_lock);
4412 if (exists != NULL) {
4413 /* somebody beat us to the hash insert */
4414 mutex_exit(hash_lock);
4415 buf_discard_identity(hdr);
4416 (void) arc_buf_remove_ref(buf, private);
4417 goto top; /* restart the IO request */
4421 * If there is a callback, we pass our reference to
4422 * it; otherwise we remove our reference.
4425 (void) remove_reference(hdr, hash_lock,
4428 if (*arc_flags & ARC_FLAG_PREFETCH)
4429 hdr->b_flags |= ARC_FLAG_PREFETCH;
4430 if (*arc_flags & ARC_FLAG_L2CACHE)
4431 hdr->b_flags |= ARC_FLAG_L2CACHE;
4432 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4433 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4434 if (BP_GET_LEVEL(bp) > 0)
4435 hdr->b_flags |= ARC_FLAG_INDIRECT;
4438 * This block is in the ghost cache. If it was L2-only
4439 * (and thus didn't have an L1 hdr), we realloc the
4440 * header to add an L1 hdr.
4442 if (!HDR_HAS_L1HDR(hdr)) {
4443 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4447 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4448 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4449 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4450 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
4453 * If there is a callback, we pass a reference to it.
4456 add_reference(hdr, hash_lock, private);
4457 if (*arc_flags & ARC_FLAG_PREFETCH)
4458 hdr->b_flags |= ARC_FLAG_PREFETCH;
4459 if (*arc_flags & ARC_FLAG_L2CACHE)
4460 hdr->b_flags |= ARC_FLAG_L2CACHE;
4461 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4462 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4463 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4466 buf->b_efunc = NULL;
4467 buf->b_private = NULL;
4469 hdr->b_l1hdr.b_buf = buf;
4470 ASSERT0(hdr->b_l1hdr.b_datacnt);
4471 hdr->b_l1hdr.b_datacnt = 1;
4472 arc_get_data_buf(buf);
4473 arc_access(hdr, hash_lock);
4476 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4477 hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
4478 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4480 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4481 acb->acb_done = done;
4482 acb->acb_private = private;
4484 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4485 hdr->b_l1hdr.b_acb = acb;
4486 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4488 if (HDR_HAS_L2HDR(hdr) &&
4489 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4490 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4491 addr = hdr->b_l2hdr.b_daddr;
4492 b_compress = hdr->b_l2hdr.b_compress;
4493 b_asize = hdr->b_l2hdr.b_asize;
4495 * Lock out device removal.
4497 if (vdev_is_dead(vd) ||
4498 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4502 if (hash_lock != NULL)
4503 mutex_exit(hash_lock);
4506 * At this point, we have a level 1 cache miss. Try again in
4507 * L2ARC if possible.
4509 ASSERT3U(hdr->b_size, ==, size);
4510 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4511 uint64_t, size, zbookmark_phys_t *, zb);
4512 ARCSTAT_BUMP(arcstat_misses);
4513 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4514 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4515 data, metadata, misses);
4520 racct_add_force(curproc, RACCT_READBPS, size);
4521 racct_add_force(curproc, RACCT_READIOPS, 1);
4522 PROC_UNLOCK(curproc);
4525 curthread->td_ru.ru_inblock++;
4528 if (priority == ZIO_PRIORITY_ASYNC_READ)
4529 hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4531 hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4533 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4535 * Read from the L2ARC if the following are true:
4536 * 1. The L2ARC vdev was previously cached.
4537 * 2. This buffer still has L2ARC metadata.
4538 * 3. This buffer isn't currently writing to the L2ARC.
4539 * 4. The L2ARC entry wasn't evicted, which may
4540 * also have invalidated the vdev.
4541 * 5. This isn't prefetch and l2arc_noprefetch is set.
4543 if (HDR_HAS_L2HDR(hdr) &&
4544 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4545 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4546 l2arc_read_callback_t *cb;
4549 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4550 ARCSTAT_BUMP(arcstat_l2_hits);
4552 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4554 cb->l2rcb_buf = buf;
4555 cb->l2rcb_spa = spa;
4558 cb->l2rcb_flags = zio_flags;
4559 cb->l2rcb_compress = b_compress;
4560 if (b_asize > hdr->b_size) {
4561 ASSERT3U(b_compress, ==,
4563 b_data = zio_data_buf_alloc(b_asize);
4564 cb->l2rcb_data = b_data;
4566 b_data = buf->b_data;
4569 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4570 addr + size < vd->vdev_psize -
4571 VDEV_LABEL_END_SIZE);
4574 * l2arc read. The SCL_L2ARC lock will be
4575 * released by l2arc_read_done().
4576 * Issue a null zio if the underlying buffer
4577 * was squashed to zero size by compression.
4579 if (b_compress == ZIO_COMPRESS_EMPTY) {
4580 ASSERT3U(b_asize, ==, 0);
4581 rzio = zio_null(pio, spa, vd,
4582 l2arc_read_done, cb,
4583 zio_flags | ZIO_FLAG_DONT_CACHE |
4585 ZIO_FLAG_DONT_PROPAGATE |
4586 ZIO_FLAG_DONT_RETRY);
4588 rzio = zio_read_phys(pio, vd, addr,
4591 l2arc_read_done, cb, priority,
4592 zio_flags | ZIO_FLAG_DONT_CACHE |
4594 ZIO_FLAG_DONT_PROPAGATE |
4595 ZIO_FLAG_DONT_RETRY, B_FALSE);
4597 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4599 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4601 if (*arc_flags & ARC_FLAG_NOWAIT) {
4606 ASSERT(*arc_flags & ARC_FLAG_WAIT);
4607 if (zio_wait(rzio) == 0)
4610 /* l2arc read error; goto zio_read() */
4612 DTRACE_PROBE1(l2arc__miss,
4613 arc_buf_hdr_t *, hdr);
4614 ARCSTAT_BUMP(arcstat_l2_misses);
4615 if (HDR_L2_WRITING(hdr))
4616 ARCSTAT_BUMP(arcstat_l2_rw_clash);
4617 spa_config_exit(spa, SCL_L2ARC, vd);
4621 spa_config_exit(spa, SCL_L2ARC, vd);
4622 if (l2arc_ndev != 0) {
4623 DTRACE_PROBE1(l2arc__miss,
4624 arc_buf_hdr_t *, hdr);
4625 ARCSTAT_BUMP(arcstat_l2_misses);
4629 rzio = zio_read(pio, spa, bp, buf->b_data, size,
4630 arc_read_done, buf, priority, zio_flags, zb);
4632 if (*arc_flags & ARC_FLAG_WAIT)
4633 return (zio_wait(rzio));
4635 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4642 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4644 ASSERT(buf->b_hdr != NULL);
4645 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4646 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4648 ASSERT(buf->b_efunc == NULL);
4649 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4651 buf->b_efunc = func;
4652 buf->b_private = private;
4656 * Notify the arc that a block was freed, and thus will never be used again.
4659 arc_freed(spa_t *spa, const blkptr_t *bp)
4662 kmutex_t *hash_lock;
4663 uint64_t guid = spa_load_guid(spa);
4665 ASSERT(!BP_IS_EMBEDDED(bp));
4667 hdr = buf_hash_find(guid, bp, &hash_lock);
4670 if (HDR_BUF_AVAILABLE(hdr)) {
4671 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4672 add_reference(hdr, hash_lock, FTAG);
4673 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4674 mutex_exit(hash_lock);
4676 arc_release(buf, FTAG);
4677 (void) arc_buf_remove_ref(buf, FTAG);
4679 mutex_exit(hash_lock);
4685 * Clear the user eviction callback set by arc_set_callback(), first calling
4686 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4687 * clearing the callback may result in the arc_buf being destroyed. However,
4688 * it will not result in the *last* arc_buf being destroyed, hence the data
4689 * will remain cached in the ARC. We make a copy of the arc buffer here so
4690 * that we can process the callback without holding any locks.
4692 * It's possible that the callback is already in the process of being cleared
4693 * by another thread. In this case we can not clear the callback.
4695 * Returns B_TRUE if the callback was successfully called and cleared.
4698 arc_clear_callback(arc_buf_t *buf)
4701 kmutex_t *hash_lock;
4702 arc_evict_func_t *efunc = buf->b_efunc;
4703 void *private = buf->b_private;
4705 mutex_enter(&buf->b_evict_lock);
4709 * We are in arc_do_user_evicts().
4711 ASSERT(buf->b_data == NULL);
4712 mutex_exit(&buf->b_evict_lock);
4714 } else if (buf->b_data == NULL) {
4716 * We are on the eviction list; process this buffer now
4717 * but let arc_do_user_evicts() do the reaping.
4719 buf->b_efunc = NULL;
4720 mutex_exit(&buf->b_evict_lock);
4721 VERIFY0(efunc(private));
4724 hash_lock = HDR_LOCK(hdr);
4725 mutex_enter(hash_lock);
4727 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4729 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4730 hdr->b_l1hdr.b_datacnt);
4731 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4732 hdr->b_l1hdr.b_state == arc_mfu);
4734 buf->b_efunc = NULL;
4735 buf->b_private = NULL;
4737 if (hdr->b_l1hdr.b_datacnt > 1) {
4738 mutex_exit(&buf->b_evict_lock);
4739 arc_buf_destroy(buf, TRUE);
4741 ASSERT(buf == hdr->b_l1hdr.b_buf);
4742 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4743 mutex_exit(&buf->b_evict_lock);
4746 mutex_exit(hash_lock);
4747 VERIFY0(efunc(private));
4752 * Release this buffer from the cache, making it an anonymous buffer. This
4753 * must be done after a read and prior to modifying the buffer contents.
4754 * If the buffer has more than one reference, we must make
4755 * a new hdr for the buffer.
4758 arc_release(arc_buf_t *buf, void *tag)
4760 arc_buf_hdr_t *hdr = buf->b_hdr;
4763 * It would be nice to assert that if it's DMU metadata (level >
4764 * 0 || it's the dnode file), then it must be syncing context.
4765 * But we don't know that information at this level.
4768 mutex_enter(&buf->b_evict_lock);
4770 ASSERT(HDR_HAS_L1HDR(hdr));
4773 * We don't grab the hash lock prior to this check, because if
4774 * the buffer's header is in the arc_anon state, it won't be
4775 * linked into the hash table.
4777 if (hdr->b_l1hdr.b_state == arc_anon) {
4778 mutex_exit(&buf->b_evict_lock);
4779 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4780 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4781 ASSERT(!HDR_HAS_L2HDR(hdr));
4782 ASSERT(BUF_EMPTY(hdr));
4783 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4784 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4785 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4787 ASSERT3P(buf->b_efunc, ==, NULL);
4788 ASSERT3P(buf->b_private, ==, NULL);
4790 hdr->b_l1hdr.b_arc_access = 0;
4796 kmutex_t *hash_lock = HDR_LOCK(hdr);
4797 mutex_enter(hash_lock);
4800 * This assignment is only valid as long as the hash_lock is
4801 * held, we must be careful not to reference state or the
4802 * b_state field after dropping the lock.
4804 arc_state_t *state = hdr->b_l1hdr.b_state;
4805 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4806 ASSERT3P(state, !=, arc_anon);
4808 /* this buffer is not on any list */
4809 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4811 if (HDR_HAS_L2HDR(hdr)) {
4812 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4815 * We have to recheck this conditional again now that
4816 * we're holding the l2ad_mtx to prevent a race with
4817 * another thread which might be concurrently calling
4818 * l2arc_evict(). In that case, l2arc_evict() might have
4819 * destroyed the header's L2 portion as we were waiting
4820 * to acquire the l2ad_mtx.
4822 if (HDR_HAS_L2HDR(hdr)) {
4824 arc_hdr_l2hdr_destroy(hdr);
4827 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4831 * Do we have more than one buf?
4833 if (hdr->b_l1hdr.b_datacnt > 1) {
4834 arc_buf_hdr_t *nhdr;
4836 uint64_t blksz = hdr->b_size;
4837 uint64_t spa = hdr->b_spa;
4838 arc_buf_contents_t type = arc_buf_type(hdr);
4839 uint32_t flags = hdr->b_flags;
4841 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4843 * Pull the data off of this hdr and attach it to
4844 * a new anonymous hdr.
4846 (void) remove_reference(hdr, hash_lock, tag);
4847 bufp = &hdr->b_l1hdr.b_buf;
4848 while (*bufp != buf)
4849 bufp = &(*bufp)->b_next;
4850 *bufp = buf->b_next;
4853 ASSERT3P(state, !=, arc_l2c_only);
4855 (void) refcount_remove_many(
4856 &state->arcs_size, hdr->b_size, buf);
4858 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4859 ASSERT3P(state, !=, arc_l2c_only);
4860 uint64_t *size = &state->arcs_lsize[type];
4861 ASSERT3U(*size, >=, hdr->b_size);
4862 atomic_add_64(size, -hdr->b_size);
4866 * We're releasing a duplicate user data buffer, update
4867 * our statistics accordingly.
4869 if (HDR_ISTYPE_DATA(hdr)) {
4870 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4871 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4874 hdr->b_l1hdr.b_datacnt -= 1;
4875 arc_cksum_verify(buf);
4877 arc_buf_unwatch(buf);
4880 mutex_exit(hash_lock);
4882 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4883 nhdr->b_size = blksz;
4886 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4887 nhdr->b_flags |= arc_bufc_to_flags(type);
4888 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4890 nhdr->b_l1hdr.b_buf = buf;
4891 nhdr->b_l1hdr.b_datacnt = 1;
4892 nhdr->b_l1hdr.b_state = arc_anon;
4893 nhdr->b_l1hdr.b_arc_access = 0;
4894 nhdr->b_l1hdr.b_tmp_cdata = NULL;
4895 nhdr->b_freeze_cksum = NULL;
4897 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4899 mutex_exit(&buf->b_evict_lock);
4900 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
4902 mutex_exit(&buf->b_evict_lock);
4903 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4904 /* protected by hash lock, or hdr is on arc_anon */
4905 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4906 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4907 arc_change_state(arc_anon, hdr, hash_lock);
4908 hdr->b_l1hdr.b_arc_access = 0;
4909 mutex_exit(hash_lock);
4911 buf_discard_identity(hdr);
4914 buf->b_efunc = NULL;
4915 buf->b_private = NULL;
4919 arc_released(arc_buf_t *buf)
4923 mutex_enter(&buf->b_evict_lock);
4924 released = (buf->b_data != NULL &&
4925 buf->b_hdr->b_l1hdr.b_state == arc_anon);
4926 mutex_exit(&buf->b_evict_lock);
4932 arc_referenced(arc_buf_t *buf)
4936 mutex_enter(&buf->b_evict_lock);
4937 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4938 mutex_exit(&buf->b_evict_lock);
4939 return (referenced);
4944 arc_write_ready(zio_t *zio)
4946 arc_write_callback_t *callback = zio->io_private;
4947 arc_buf_t *buf = callback->awcb_buf;
4948 arc_buf_hdr_t *hdr = buf->b_hdr;
4950 ASSERT(HDR_HAS_L1HDR(hdr));
4951 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4952 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4953 callback->awcb_ready(zio, buf, callback->awcb_private);
4956 * If the IO is already in progress, then this is a re-write
4957 * attempt, so we need to thaw and re-compute the cksum.
4958 * It is the responsibility of the callback to handle the
4959 * accounting for any re-write attempt.
4961 if (HDR_IO_IN_PROGRESS(hdr)) {
4962 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4963 if (hdr->b_freeze_cksum != NULL) {
4964 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4965 hdr->b_freeze_cksum = NULL;
4967 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4969 arc_cksum_compute(buf, B_FALSE);
4970 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4974 * The SPA calls this callback for each physical write that happens on behalf
4975 * of a logical write. See the comment in dbuf_write_physdone() for details.
4978 arc_write_physdone(zio_t *zio)
4980 arc_write_callback_t *cb = zio->io_private;
4981 if (cb->awcb_physdone != NULL)
4982 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4986 arc_write_done(zio_t *zio)
4988 arc_write_callback_t *callback = zio->io_private;
4989 arc_buf_t *buf = callback->awcb_buf;
4990 arc_buf_hdr_t *hdr = buf->b_hdr;
4992 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4994 if (zio->io_error == 0) {
4995 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4996 buf_discard_identity(hdr);
4998 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4999 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5002 ASSERT(BUF_EMPTY(hdr));
5006 * If the block to be written was all-zero or compressed enough to be
5007 * embedded in the BP, no write was performed so there will be no
5008 * dva/birth/checksum. The buffer must therefore remain anonymous
5011 if (!BUF_EMPTY(hdr)) {
5012 arc_buf_hdr_t *exists;
5013 kmutex_t *hash_lock;
5015 ASSERT(zio->io_error == 0);
5017 arc_cksum_verify(buf);
5019 exists = buf_hash_insert(hdr, &hash_lock);
5020 if (exists != NULL) {
5022 * This can only happen if we overwrite for
5023 * sync-to-convergence, because we remove
5024 * buffers from the hash table when we arc_free().
5026 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5027 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5028 panic("bad overwrite, hdr=%p exists=%p",
5029 (void *)hdr, (void *)exists);
5030 ASSERT(refcount_is_zero(
5031 &exists->b_l1hdr.b_refcnt));
5032 arc_change_state(arc_anon, exists, hash_lock);
5033 mutex_exit(hash_lock);
5034 arc_hdr_destroy(exists);
5035 exists = buf_hash_insert(hdr, &hash_lock);
5036 ASSERT3P(exists, ==, NULL);
5037 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5039 ASSERT(zio->io_prop.zp_nopwrite);
5040 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5041 panic("bad nopwrite, hdr=%p exists=%p",
5042 (void *)hdr, (void *)exists);
5045 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5046 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5047 ASSERT(BP_GET_DEDUP(zio->io_bp));
5048 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5051 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5052 /* if it's not anon, we are doing a scrub */
5053 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5054 arc_access(hdr, hash_lock);
5055 mutex_exit(hash_lock);
5057 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
5060 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5061 callback->awcb_done(zio, buf, callback->awcb_private);
5063 kmem_free(callback, sizeof (arc_write_callback_t));
5067 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
5068 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
5069 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
5070 arc_done_func_t *done, void *private, zio_priority_t priority,
5071 int zio_flags, const zbookmark_phys_t *zb)
5073 arc_buf_hdr_t *hdr = buf->b_hdr;
5074 arc_write_callback_t *callback;
5077 ASSERT(ready != NULL);
5078 ASSERT(done != NULL);
5079 ASSERT(!HDR_IO_ERROR(hdr));
5080 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5081 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5082 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
5084 hdr->b_flags |= ARC_FLAG_L2CACHE;
5086 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
5087 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5088 callback->awcb_ready = ready;
5089 callback->awcb_physdone = physdone;
5090 callback->awcb_done = done;
5091 callback->awcb_private = private;
5092 callback->awcb_buf = buf;
5094 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
5095 arc_write_ready, arc_write_physdone, arc_write_done, callback,
5096 priority, zio_flags, zb);
5102 arc_memory_throttle(uint64_t reserve, uint64_t txg)
5105 uint64_t available_memory = ptob(freemem);
5106 static uint64_t page_load = 0;
5107 static uint64_t last_txg = 0;
5109 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
5111 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
5114 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
5117 if (txg > last_txg) {
5122 * If we are in pageout, we know that memory is already tight,
5123 * the arc is already going to be evicting, so we just want to
5124 * continue to let page writes occur as quickly as possible.
5126 if (curproc == pageproc) {
5127 if (page_load > MAX(ptob(minfree), available_memory) / 4)
5128 return (SET_ERROR(ERESTART));
5129 /* Note: reserve is inflated, so we deflate */
5130 page_load += reserve / 8;
5132 } else if (page_load > 0 && arc_reclaim_needed()) {
5133 /* memory is low, delay before restarting */
5134 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5135 return (SET_ERROR(EAGAIN));
5143 arc_tempreserve_clear(uint64_t reserve)
5145 atomic_add_64(&arc_tempreserve, -reserve);
5146 ASSERT((int64_t)arc_tempreserve >= 0);
5150 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5155 if (reserve > arc_c/4 && !arc_no_grow) {
5156 arc_c = MIN(arc_c_max, reserve * 4);
5157 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
5159 if (reserve > arc_c)
5160 return (SET_ERROR(ENOMEM));
5163 * Don't count loaned bufs as in flight dirty data to prevent long
5164 * network delays from blocking transactions that are ready to be
5165 * assigned to a txg.
5167 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5168 arc_loaned_bytes), 0);
5171 * Writes will, almost always, require additional memory allocations
5172 * in order to compress/encrypt/etc the data. We therefore need to
5173 * make sure that there is sufficient available memory for this.
5175 error = arc_memory_throttle(reserve, txg);
5180 * Throttle writes when the amount of dirty data in the cache
5181 * gets too large. We try to keep the cache less than half full
5182 * of dirty blocks so that our sync times don't grow too large.
5183 * Note: if two requests come in concurrently, we might let them
5184 * both succeed, when one of them should fail. Not a huge deal.
5187 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5188 anon_size > arc_c / 4) {
5189 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5190 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5191 arc_tempreserve>>10,
5192 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5193 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5194 reserve>>10, arc_c>>10);
5195 return (SET_ERROR(ERESTART));
5197 atomic_add_64(&arc_tempreserve, reserve);
5202 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5203 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5205 size->value.ui64 = refcount_count(&state->arcs_size);
5206 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5207 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5211 arc_kstat_update(kstat_t *ksp, int rw)
5213 arc_stats_t *as = ksp->ks_data;
5215 if (rw == KSTAT_WRITE) {
5218 arc_kstat_update_state(arc_anon,
5219 &as->arcstat_anon_size,
5220 &as->arcstat_anon_evictable_data,
5221 &as->arcstat_anon_evictable_metadata);
5222 arc_kstat_update_state(arc_mru,
5223 &as->arcstat_mru_size,
5224 &as->arcstat_mru_evictable_data,
5225 &as->arcstat_mru_evictable_metadata);
5226 arc_kstat_update_state(arc_mru_ghost,
5227 &as->arcstat_mru_ghost_size,
5228 &as->arcstat_mru_ghost_evictable_data,
5229 &as->arcstat_mru_ghost_evictable_metadata);
5230 arc_kstat_update_state(arc_mfu,
5231 &as->arcstat_mfu_size,
5232 &as->arcstat_mfu_evictable_data,
5233 &as->arcstat_mfu_evictable_metadata);
5234 arc_kstat_update_state(arc_mfu_ghost,
5235 &as->arcstat_mfu_ghost_size,
5236 &as->arcstat_mfu_ghost_evictable_data,
5237 &as->arcstat_mfu_ghost_evictable_metadata);
5244 * This function *must* return indices evenly distributed between all
5245 * sublists of the multilist. This is needed due to how the ARC eviction
5246 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5247 * distributed between all sublists and uses this assumption when
5248 * deciding which sublist to evict from and how much to evict from it.
5251 arc_state_multilist_index_func(multilist_t *ml, void *obj)
5253 arc_buf_hdr_t *hdr = obj;
5256 * We rely on b_dva to generate evenly distributed index
5257 * numbers using buf_hash below. So, as an added precaution,
5258 * let's make sure we never add empty buffers to the arc lists.
5260 ASSERT(!BUF_EMPTY(hdr));
5263 * The assumption here, is the hash value for a given
5264 * arc_buf_hdr_t will remain constant throughout it's lifetime
5265 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
5266 * Thus, we don't need to store the header's sublist index
5267 * on insertion, as this index can be recalculated on removal.
5269 * Also, the low order bits of the hash value are thought to be
5270 * distributed evenly. Otherwise, in the case that the multilist
5271 * has a power of two number of sublists, each sublists' usage
5272 * would not be evenly distributed.
5274 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5275 multilist_get_num_sublists(ml));
5279 static eventhandler_tag arc_event_lowmem = NULL;
5282 arc_lowmem(void *arg __unused, int howto __unused)
5285 mutex_enter(&arc_reclaim_lock);
5286 /* XXX: Memory deficit should be passed as argument. */
5287 needfree = btoc(arc_c >> arc_shrink_shift);
5288 DTRACE_PROBE(arc__needfree);
5289 cv_signal(&arc_reclaim_thread_cv);
5292 * It is unsafe to block here in arbitrary threads, because we can come
5293 * here from ARC itself and may hold ARC locks and thus risk a deadlock
5294 * with ARC reclaim thread.
5296 if (curproc == pageproc)
5297 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5298 mutex_exit(&arc_reclaim_lock);
5305 int i, prefetch_tunable_set = 0;
5307 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5308 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5309 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5311 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5312 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
5314 /* Convert seconds to clock ticks */
5315 arc_min_prefetch_lifespan = 1 * hz;
5317 /* Start out with 1/8 of all memory */
5318 arc_c = kmem_size() / 8;
5323 * On architectures where the physical memory can be larger
5324 * than the addressable space (intel in 32-bit mode), we may
5325 * need to limit the cache to 1/8 of VM size.
5327 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
5329 #endif /* illumos */
5330 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
5331 arc_c_min = MAX(arc_c / 4, 16 << 20);
5332 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
5333 if (arc_c * 8 >= 1 << 30)
5334 arc_c_max = (arc_c * 8) - (1 << 30);
5336 arc_c_max = arc_c_min;
5337 arc_c_max = MAX(arc_c * 5, arc_c_max);
5340 * In userland, there's only the memory pressure that we artificially
5341 * create (see arc_available_memory()). Don't let arc_c get too
5342 * small, because it can cause transactions to be larger than
5343 * arc_c, causing arc_tempreserve_space() to fail.
5346 arc_c_min = arc_c_max / 2;
5351 * Allow the tunables to override our calculations if they are
5352 * reasonable (ie. over 16MB)
5354 if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
5355 arc_c_max = zfs_arc_max;
5356 if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
5357 arc_c_min = zfs_arc_min;
5361 arc_p = (arc_c >> 1);
5363 /* limit meta-data to 1/4 of the arc capacity */
5364 arc_meta_limit = arc_c_max / 4;
5366 /* Allow the tunable to override if it is reasonable */
5367 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
5368 arc_meta_limit = zfs_arc_meta_limit;
5370 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
5371 arc_c_min = arc_meta_limit / 2;
5373 if (zfs_arc_meta_min > 0) {
5374 arc_meta_min = zfs_arc_meta_min;
5376 arc_meta_min = arc_c_min / 2;
5379 if (zfs_arc_grow_retry > 0)
5380 arc_grow_retry = zfs_arc_grow_retry;
5382 if (zfs_arc_shrink_shift > 0)
5383 arc_shrink_shift = zfs_arc_shrink_shift;
5386 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
5388 if (arc_no_grow_shift >= arc_shrink_shift)
5389 arc_no_grow_shift = arc_shrink_shift - 1;
5391 if (zfs_arc_p_min_shift > 0)
5392 arc_p_min_shift = zfs_arc_p_min_shift;
5394 if (zfs_arc_num_sublists_per_state < 1)
5395 zfs_arc_num_sublists_per_state = MAX(max_ncpus, 1);
5397 /* if kmem_flags are set, lets try to use less memory */
5398 if (kmem_debugging())
5400 if (arc_c < arc_c_min)
5403 zfs_arc_min = arc_c_min;
5404 zfs_arc_max = arc_c_max;
5406 arc_anon = &ARC_anon;
5408 arc_mru_ghost = &ARC_mru_ghost;
5410 arc_mfu_ghost = &ARC_mfu_ghost;
5411 arc_l2c_only = &ARC_l2c_only;
5414 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
5415 sizeof (arc_buf_hdr_t),
5416 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5417 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5418 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
5419 sizeof (arc_buf_hdr_t),
5420 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5421 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5422 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
5423 sizeof (arc_buf_hdr_t),
5424 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5425 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5426 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
5427 sizeof (arc_buf_hdr_t),
5428 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5429 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5430 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
5431 sizeof (arc_buf_hdr_t),
5432 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5433 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5434 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
5435 sizeof (arc_buf_hdr_t),
5436 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5437 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5438 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
5439 sizeof (arc_buf_hdr_t),
5440 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5441 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5442 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
5443 sizeof (arc_buf_hdr_t),
5444 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5445 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5446 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
5447 sizeof (arc_buf_hdr_t),
5448 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5449 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5450 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
5451 sizeof (arc_buf_hdr_t),
5452 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5453 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5455 refcount_create(&arc_anon->arcs_size);
5456 refcount_create(&arc_mru->arcs_size);
5457 refcount_create(&arc_mru_ghost->arcs_size);
5458 refcount_create(&arc_mfu->arcs_size);
5459 refcount_create(&arc_mfu_ghost->arcs_size);
5460 refcount_create(&arc_l2c_only->arcs_size);
5464 arc_reclaim_thread_exit = FALSE;
5465 arc_user_evicts_thread_exit = FALSE;
5466 arc_eviction_list = NULL;
5467 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5469 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5470 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5472 if (arc_ksp != NULL) {
5473 arc_ksp->ks_data = &arc_stats;
5474 arc_ksp->ks_update = arc_kstat_update;
5475 kstat_install(arc_ksp);
5478 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5479 TS_RUN, minclsyspri);
5482 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5483 EVENTHANDLER_PRI_FIRST);
5486 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
5487 TS_RUN, minclsyspri);
5493 * Calculate maximum amount of dirty data per pool.
5495 * If it has been set by /etc/system, take that.
5496 * Otherwise, use a percentage of physical memory defined by
5497 * zfs_dirty_data_max_percent (default 10%) with a cap at
5498 * zfs_dirty_data_max_max (default 4GB).
5500 if (zfs_dirty_data_max == 0) {
5501 zfs_dirty_data_max = ptob(physmem) *
5502 zfs_dirty_data_max_percent / 100;
5503 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5504 zfs_dirty_data_max_max);
5508 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5509 prefetch_tunable_set = 1;
5512 if (prefetch_tunable_set == 0) {
5513 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5515 printf(" add \"vfs.zfs.prefetch_disable=0\" "
5516 "to /boot/loader.conf.\n");
5517 zfs_prefetch_disable = 1;
5520 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5521 prefetch_tunable_set == 0) {
5522 printf("ZFS NOTICE: Prefetch is disabled by default if less "
5523 "than 4GB of RAM is present;\n"
5524 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
5525 "to /boot/loader.conf.\n");
5526 zfs_prefetch_disable = 1;
5529 /* Warn about ZFS memory and address space requirements. */
5530 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5531 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5532 "expect unstable behavior.\n");
5534 if (kmem_size() < 512 * (1 << 20)) {
5535 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5536 "expect unstable behavior.\n");
5537 printf(" Consider tuning vm.kmem_size and "
5538 "vm.kmem_size_max\n");
5539 printf(" in /boot/loader.conf.\n");
5547 mutex_enter(&arc_reclaim_lock);
5548 arc_reclaim_thread_exit = TRUE;
5550 * The reclaim thread will set arc_reclaim_thread_exit back to
5551 * FALSE when it is finished exiting; we're waiting for that.
5553 while (arc_reclaim_thread_exit) {
5554 cv_signal(&arc_reclaim_thread_cv);
5555 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5557 mutex_exit(&arc_reclaim_lock);
5559 mutex_enter(&arc_user_evicts_lock);
5560 arc_user_evicts_thread_exit = TRUE;
5562 * The user evicts thread will set arc_user_evicts_thread_exit
5563 * to FALSE when it is finished exiting; we're waiting for that.
5565 while (arc_user_evicts_thread_exit) {
5566 cv_signal(&arc_user_evicts_cv);
5567 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5569 mutex_exit(&arc_user_evicts_lock);
5571 /* Use TRUE to ensure *all* buffers are evicted */
5572 arc_flush(NULL, TRUE);
5576 if (arc_ksp != NULL) {
5577 kstat_delete(arc_ksp);
5581 mutex_destroy(&arc_reclaim_lock);
5582 cv_destroy(&arc_reclaim_thread_cv);
5583 cv_destroy(&arc_reclaim_waiters_cv);
5585 mutex_destroy(&arc_user_evicts_lock);
5586 cv_destroy(&arc_user_evicts_cv);
5588 refcount_destroy(&arc_anon->arcs_size);
5589 refcount_destroy(&arc_mru->arcs_size);
5590 refcount_destroy(&arc_mru_ghost->arcs_size);
5591 refcount_destroy(&arc_mfu->arcs_size);
5592 refcount_destroy(&arc_mfu_ghost->arcs_size);
5593 refcount_destroy(&arc_l2c_only->arcs_size);
5595 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5596 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5597 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5598 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5599 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
5600 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5601 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5602 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5603 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5604 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
5608 ASSERT0(arc_loaned_bytes);
5611 if (arc_event_lowmem != NULL)
5612 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5619 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5620 * It uses dedicated storage devices to hold cached data, which are populated
5621 * using large infrequent writes. The main role of this cache is to boost
5622 * the performance of random read workloads. The intended L2ARC devices
5623 * include short-stroked disks, solid state disks, and other media with
5624 * substantially faster read latency than disk.
5626 * +-----------------------+
5628 * +-----------------------+
5631 * l2arc_feed_thread() arc_read()
5635 * +---------------+ |
5637 * +---------------+ |
5642 * +-------+ +-------+
5644 * | cache | | cache |
5645 * +-------+ +-------+
5646 * +=========+ .-----.
5647 * : L2ARC : |-_____-|
5648 * : devices : | Disks |
5649 * +=========+ `-_____-'
5651 * Read requests are satisfied from the following sources, in order:
5654 * 2) vdev cache of L2ARC devices
5656 * 4) vdev cache of disks
5659 * Some L2ARC device types exhibit extremely slow write performance.
5660 * To accommodate for this there are some significant differences between
5661 * the L2ARC and traditional cache design:
5663 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5664 * the ARC behave as usual, freeing buffers and placing headers on ghost
5665 * lists. The ARC does not send buffers to the L2ARC during eviction as
5666 * this would add inflated write latencies for all ARC memory pressure.
5668 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5669 * It does this by periodically scanning buffers from the eviction-end of
5670 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5671 * not already there. It scans until a headroom of buffers is satisfied,
5672 * which itself is a buffer for ARC eviction. If a compressible buffer is
5673 * found during scanning and selected for writing to an L2ARC device, we
5674 * temporarily boost scanning headroom during the next scan cycle to make
5675 * sure we adapt to compression effects (which might significantly reduce
5676 * the data volume we write to L2ARC). The thread that does this is
5677 * l2arc_feed_thread(), illustrated below; example sizes are included to
5678 * provide a better sense of ratio than this diagram:
5681 * +---------------------+----------+
5682 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5683 * +---------------------+----------+ | o L2ARC eligible
5684 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5685 * +---------------------+----------+ |
5686 * 15.9 Gbytes ^ 32 Mbytes |
5688 * l2arc_feed_thread()
5690 * l2arc write hand <--[oooo]--'
5694 * +==============================+
5695 * L2ARC dev |####|#|###|###| |####| ... |
5696 * +==============================+
5699 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5700 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5701 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5702 * safe to say that this is an uncommon case, since buffers at the end of
5703 * the ARC lists have moved there due to inactivity.
5705 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5706 * then the L2ARC simply misses copying some buffers. This serves as a
5707 * pressure valve to prevent heavy read workloads from both stalling the ARC
5708 * with waits and clogging the L2ARC with writes. This also helps prevent
5709 * the potential for the L2ARC to churn if it attempts to cache content too
5710 * quickly, such as during backups of the entire pool.
5712 * 5. After system boot and before the ARC has filled main memory, there are
5713 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5714 * lists can remain mostly static. Instead of searching from tail of these
5715 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5716 * for eligible buffers, greatly increasing its chance of finding them.
5718 * The L2ARC device write speed is also boosted during this time so that
5719 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5720 * there are no L2ARC reads, and no fear of degrading read performance
5721 * through increased writes.
5723 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5724 * the vdev queue can aggregate them into larger and fewer writes. Each
5725 * device is written to in a rotor fashion, sweeping writes through
5726 * available space then repeating.
5728 * 7. The L2ARC does not store dirty content. It never needs to flush
5729 * write buffers back to disk based storage.
5731 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5732 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5734 * The performance of the L2ARC can be tweaked by a number of tunables, which
5735 * may be necessary for different workloads:
5737 * l2arc_write_max max write bytes per interval
5738 * l2arc_write_boost extra write bytes during device warmup
5739 * l2arc_noprefetch skip caching prefetched buffers
5740 * l2arc_headroom number of max device writes to precache
5741 * l2arc_headroom_boost when we find compressed buffers during ARC
5742 * scanning, we multiply headroom by this
5743 * percentage factor for the next scan cycle,
5744 * since more compressed buffers are likely to
5746 * l2arc_feed_secs seconds between L2ARC writing
5748 * Tunables may be removed or added as future performance improvements are
5749 * integrated, and also may become zpool properties.
5751 * There are three key functions that control how the L2ARC warms up:
5753 * l2arc_write_eligible() check if a buffer is eligible to cache
5754 * l2arc_write_size() calculate how much to write
5755 * l2arc_write_interval() calculate sleep delay between writes
5757 * These three functions determine what to write, how much, and how quickly
5762 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5765 * A buffer is *not* eligible for the L2ARC if it:
5766 * 1. belongs to a different spa.
5767 * 2. is already cached on the L2ARC.
5768 * 3. has an I/O in progress (it may be an incomplete read).
5769 * 4. is flagged not eligible (zfs property).
5771 if (hdr->b_spa != spa_guid) {
5772 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5775 if (HDR_HAS_L2HDR(hdr)) {
5776 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5779 if (HDR_IO_IN_PROGRESS(hdr)) {
5780 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5783 if (!HDR_L2CACHE(hdr)) {
5784 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5792 l2arc_write_size(void)
5797 * Make sure our globals have meaningful values in case the user
5800 size = l2arc_write_max;
5802 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5803 "be greater than zero, resetting it to the default (%d)",
5805 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5808 if (arc_warm == B_FALSE)
5809 size += l2arc_write_boost;
5816 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5818 clock_t interval, next, now;
5821 * If the ARC lists are busy, increase our write rate; if the
5822 * lists are stale, idle back. This is achieved by checking
5823 * how much we previously wrote - if it was more than half of
5824 * what we wanted, schedule the next write much sooner.
5826 if (l2arc_feed_again && wrote > (wanted / 2))
5827 interval = (hz * l2arc_feed_min_ms) / 1000;
5829 interval = hz * l2arc_feed_secs;
5831 now = ddi_get_lbolt();
5832 next = MAX(now, MIN(now + interval, began + interval));
5838 * Cycle through L2ARC devices. This is how L2ARC load balances.
5839 * If a device is returned, this also returns holding the spa config lock.
5841 static l2arc_dev_t *
5842 l2arc_dev_get_next(void)
5844 l2arc_dev_t *first, *next = NULL;
5847 * Lock out the removal of spas (spa_namespace_lock), then removal
5848 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5849 * both locks will be dropped and a spa config lock held instead.
5851 mutex_enter(&spa_namespace_lock);
5852 mutex_enter(&l2arc_dev_mtx);
5854 /* if there are no vdevs, there is nothing to do */
5855 if (l2arc_ndev == 0)
5859 next = l2arc_dev_last;
5861 /* loop around the list looking for a non-faulted vdev */
5863 next = list_head(l2arc_dev_list);
5865 next = list_next(l2arc_dev_list, next);
5867 next = list_head(l2arc_dev_list);
5870 /* if we have come back to the start, bail out */
5873 else if (next == first)
5876 } while (vdev_is_dead(next->l2ad_vdev));
5878 /* if we were unable to find any usable vdevs, return NULL */
5879 if (vdev_is_dead(next->l2ad_vdev))
5882 l2arc_dev_last = next;
5885 mutex_exit(&l2arc_dev_mtx);
5888 * Grab the config lock to prevent the 'next' device from being
5889 * removed while we are writing to it.
5892 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5893 mutex_exit(&spa_namespace_lock);
5899 * Free buffers that were tagged for destruction.
5902 l2arc_do_free_on_write()
5905 l2arc_data_free_t *df, *df_prev;
5907 mutex_enter(&l2arc_free_on_write_mtx);
5908 buflist = l2arc_free_on_write;
5910 for (df = list_tail(buflist); df; df = df_prev) {
5911 df_prev = list_prev(buflist, df);
5912 ASSERT(df->l2df_data != NULL);
5913 ASSERT(df->l2df_func != NULL);
5914 df->l2df_func(df->l2df_data, df->l2df_size);
5915 list_remove(buflist, df);
5916 kmem_free(df, sizeof (l2arc_data_free_t));
5919 mutex_exit(&l2arc_free_on_write_mtx);
5923 * A write to a cache device has completed. Update all headers to allow
5924 * reads from these buffers to begin.
5927 l2arc_write_done(zio_t *zio)
5929 l2arc_write_callback_t *cb;
5932 arc_buf_hdr_t *head, *hdr, *hdr_prev;
5933 kmutex_t *hash_lock;
5934 int64_t bytes_dropped = 0;
5936 cb = zio->io_private;
5938 dev = cb->l2wcb_dev;
5939 ASSERT(dev != NULL);
5940 head = cb->l2wcb_head;
5941 ASSERT(head != NULL);
5942 buflist = &dev->l2ad_buflist;
5943 ASSERT(buflist != NULL);
5944 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5945 l2arc_write_callback_t *, cb);
5947 if (zio->io_error != 0)
5948 ARCSTAT_BUMP(arcstat_l2_writes_error);
5951 * All writes completed, or an error was hit.
5954 mutex_enter(&dev->l2ad_mtx);
5955 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5956 hdr_prev = list_prev(buflist, hdr);
5958 hash_lock = HDR_LOCK(hdr);
5961 * We cannot use mutex_enter or else we can deadlock
5962 * with l2arc_write_buffers (due to swapping the order
5963 * the hash lock and l2ad_mtx are taken).
5965 if (!mutex_tryenter(hash_lock)) {
5967 * Missed the hash lock. We must retry so we
5968 * don't leave the ARC_FLAG_L2_WRITING bit set.
5970 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5973 * We don't want to rescan the headers we've
5974 * already marked as having been written out, so
5975 * we reinsert the head node so we can pick up
5976 * where we left off.
5978 list_remove(buflist, head);
5979 list_insert_after(buflist, hdr, head);
5981 mutex_exit(&dev->l2ad_mtx);
5984 * We wait for the hash lock to become available
5985 * to try and prevent busy waiting, and increase
5986 * the chance we'll be able to acquire the lock
5987 * the next time around.
5989 mutex_enter(hash_lock);
5990 mutex_exit(hash_lock);
5995 * We could not have been moved into the arc_l2c_only
5996 * state while in-flight due to our ARC_FLAG_L2_WRITING
5997 * bit being set. Let's just ensure that's being enforced.
5999 ASSERT(HDR_HAS_L1HDR(hdr));
6002 * We may have allocated a buffer for L2ARC compression,
6003 * we must release it to avoid leaking this data.
6005 l2arc_release_cdata_buf(hdr);
6007 if (zio->io_error != 0) {
6009 * Error - drop L2ARC entry.
6011 list_remove(buflist, hdr);
6013 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
6015 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
6016 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
6018 bytes_dropped += hdr->b_l2hdr.b_asize;
6019 (void) refcount_remove_many(&dev->l2ad_alloc,
6020 hdr->b_l2hdr.b_asize, hdr);
6024 * Allow ARC to begin reads and ghost list evictions to
6027 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
6029 mutex_exit(hash_lock);
6032 atomic_inc_64(&l2arc_writes_done);
6033 list_remove(buflist, head);
6034 ASSERT(!HDR_HAS_L1HDR(head));
6035 kmem_cache_free(hdr_l2only_cache, head);
6036 mutex_exit(&dev->l2ad_mtx);
6038 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6040 l2arc_do_free_on_write();
6042 kmem_free(cb, sizeof (l2arc_write_callback_t));
6046 * A read to a cache device completed. Validate buffer contents before
6047 * handing over to the regular ARC routines.
6050 l2arc_read_done(zio_t *zio)
6052 l2arc_read_callback_t *cb;
6055 kmutex_t *hash_lock;
6058 ASSERT(zio->io_vd != NULL);
6059 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6061 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6063 cb = zio->io_private;
6065 buf = cb->l2rcb_buf;
6066 ASSERT(buf != NULL);
6068 hash_lock = HDR_LOCK(buf->b_hdr);
6069 mutex_enter(hash_lock);
6071 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6074 * If the data was read into a temporary buffer,
6075 * move it and free the buffer.
6077 if (cb->l2rcb_data != NULL) {
6078 ASSERT3U(hdr->b_size, <, zio->io_size);
6079 ASSERT3U(cb->l2rcb_compress, ==, ZIO_COMPRESS_OFF);
6080 if (zio->io_error == 0)
6081 bcopy(cb->l2rcb_data, buf->b_data, hdr->b_size);
6084 * The following must be done regardless of whether
6085 * there was an error:
6086 * - free the temporary buffer
6087 * - point zio to the real ARC buffer
6088 * - set zio size accordingly
6089 * These are required because zio is either re-used for
6090 * an I/O of the block in the case of the error
6091 * or the zio is passed to arc_read_done() and it
6094 zio_data_buf_free(cb->l2rcb_data, zio->io_size);
6095 zio->io_size = zio->io_orig_size = hdr->b_size;
6096 zio->io_data = zio->io_orig_data = buf->b_data;
6100 * If the buffer was compressed, decompress it first.
6102 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
6103 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6104 ASSERT(zio->io_data != NULL);
6105 ASSERT3U(zio->io_size, ==, hdr->b_size);
6106 ASSERT3U(BP_GET_LSIZE(&cb->l2rcb_bp), ==, hdr->b_size);
6109 * Check this survived the L2ARC journey.
6111 equal = arc_cksum_equal(buf);
6112 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6113 mutex_exit(hash_lock);
6114 zio->io_private = buf;
6115 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6116 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
6119 mutex_exit(hash_lock);
6121 * Buffer didn't survive caching. Increment stats and
6122 * reissue to the original storage device.
6124 if (zio->io_error != 0) {
6125 ARCSTAT_BUMP(arcstat_l2_io_error);
6127 zio->io_error = SET_ERROR(EIO);
6130 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6133 * If there's no waiter, issue an async i/o to the primary
6134 * storage now. If there *is* a waiter, the caller must
6135 * issue the i/o in a context where it's OK to block.
6137 if (zio->io_waiter == NULL) {
6138 zio_t *pio = zio_unique_parent(zio);
6140 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6142 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
6143 buf->b_data, hdr->b_size, arc_read_done, buf,
6144 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
6148 kmem_free(cb, sizeof (l2arc_read_callback_t));
6152 * This is the list priority from which the L2ARC will search for pages to
6153 * cache. This is used within loops (0..3) to cycle through lists in the
6154 * desired order. This order can have a significant effect on cache
6157 * Currently the metadata lists are hit first, MFU then MRU, followed by
6158 * the data lists. This function returns a locked list, and also returns
6161 static multilist_sublist_t *
6162 l2arc_sublist_lock(int list_num)
6164 multilist_t *ml = NULL;
6167 ASSERT(list_num >= 0 && list_num <= 3);
6171 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
6174 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
6177 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
6180 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
6185 * Return a randomly-selected sublist. This is acceptable
6186 * because the caller feeds only a little bit of data for each
6187 * call (8MB). Subsequent calls will result in different
6188 * sublists being selected.
6190 idx = multilist_get_random_index(ml);
6191 return (multilist_sublist_lock(ml, idx));
6195 * Evict buffers from the device write hand to the distance specified in
6196 * bytes. This distance may span populated buffers, it may span nothing.
6197 * This is clearing a region on the L2ARC device ready for writing.
6198 * If the 'all' boolean is set, every buffer is evicted.
6201 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6204 arc_buf_hdr_t *hdr, *hdr_prev;
6205 kmutex_t *hash_lock;
6208 buflist = &dev->l2ad_buflist;
6210 if (!all && dev->l2ad_first) {
6212 * This is the first sweep through the device. There is
6218 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6220 * When nearing the end of the device, evict to the end
6221 * before the device write hand jumps to the start.
6223 taddr = dev->l2ad_end;
6225 taddr = dev->l2ad_hand + distance;
6227 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6228 uint64_t, taddr, boolean_t, all);
6231 mutex_enter(&dev->l2ad_mtx);
6232 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6233 hdr_prev = list_prev(buflist, hdr);
6235 hash_lock = HDR_LOCK(hdr);
6238 * We cannot use mutex_enter or else we can deadlock
6239 * with l2arc_write_buffers (due to swapping the order
6240 * the hash lock and l2ad_mtx are taken).
6242 if (!mutex_tryenter(hash_lock)) {
6244 * Missed the hash lock. Retry.
6246 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6247 mutex_exit(&dev->l2ad_mtx);
6248 mutex_enter(hash_lock);
6249 mutex_exit(hash_lock);
6253 if (HDR_L2_WRITE_HEAD(hdr)) {
6255 * We hit a write head node. Leave it for
6256 * l2arc_write_done().
6258 list_remove(buflist, hdr);
6259 mutex_exit(hash_lock);
6263 if (!all && HDR_HAS_L2HDR(hdr) &&
6264 (hdr->b_l2hdr.b_daddr > taddr ||
6265 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6267 * We've evicted to the target address,
6268 * or the end of the device.
6270 mutex_exit(hash_lock);
6274 ASSERT(HDR_HAS_L2HDR(hdr));
6275 if (!HDR_HAS_L1HDR(hdr)) {
6276 ASSERT(!HDR_L2_READING(hdr));
6278 * This doesn't exist in the ARC. Destroy.
6279 * arc_hdr_destroy() will call list_remove()
6280 * and decrement arcstat_l2_size.
6282 arc_change_state(arc_anon, hdr, hash_lock);
6283 arc_hdr_destroy(hdr);
6285 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6286 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6288 * Invalidate issued or about to be issued
6289 * reads, since we may be about to write
6290 * over this location.
6292 if (HDR_L2_READING(hdr)) {
6293 ARCSTAT_BUMP(arcstat_l2_evict_reading);
6294 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
6297 /* Ensure this header has finished being written */
6298 ASSERT(!HDR_L2_WRITING(hdr));
6299 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6301 arc_hdr_l2hdr_destroy(hdr);
6303 mutex_exit(hash_lock);
6305 mutex_exit(&dev->l2ad_mtx);
6309 * Find and write ARC buffers to the L2ARC device.
6311 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
6312 * for reading until they have completed writing.
6313 * The headroom_boost is an in-out parameter used to maintain headroom boost
6314 * state between calls to this function.
6316 * Returns the number of bytes actually written (which may be smaller than
6317 * the delta by which the device hand has changed due to alignment).
6320 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6321 boolean_t *headroom_boost)
6323 arc_buf_hdr_t *hdr, *hdr_prev, *head;
6324 uint64_t write_asize, write_sz, headroom,
6328 l2arc_write_callback_t *cb;
6330 uint64_t guid = spa_load_guid(spa);
6331 const boolean_t do_headroom_boost = *headroom_boost;
6334 ASSERT(dev->l2ad_vdev != NULL);
6336 /* Lower the flag now, we might want to raise it again later. */
6337 *headroom_boost = B_FALSE;
6340 write_sz = write_asize = 0;
6342 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
6343 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
6344 head->b_flags |= ARC_FLAG_HAS_L2HDR;
6346 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
6348 * We will want to try to compress buffers that are at least 2x the
6349 * device sector size.
6351 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6354 * Copy buffers for L2ARC writing.
6356 for (try = 0; try <= 3; try++) {
6357 multilist_sublist_t *mls = l2arc_sublist_lock(try);
6358 uint64_t passed_sz = 0;
6360 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
6363 * L2ARC fast warmup.
6365 * Until the ARC is warm and starts to evict, read from the
6366 * head of the ARC lists rather than the tail.
6368 if (arc_warm == B_FALSE)
6369 hdr = multilist_sublist_head(mls);
6371 hdr = multilist_sublist_tail(mls);
6373 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
6375 headroom = target_sz * l2arc_headroom;
6376 if (do_headroom_boost)
6377 headroom = (headroom * l2arc_headroom_boost) / 100;
6379 for (; hdr; hdr = hdr_prev) {
6380 kmutex_t *hash_lock;
6385 if (arc_warm == B_FALSE)
6386 hdr_prev = multilist_sublist_next(mls, hdr);
6388 hdr_prev = multilist_sublist_prev(mls, hdr);
6389 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
6391 hash_lock = HDR_LOCK(hdr);
6392 if (!mutex_tryenter(hash_lock)) {
6393 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
6395 * Skip this buffer rather than waiting.
6400 passed_sz += hdr->b_size;
6401 if (passed_sz > headroom) {
6405 mutex_exit(hash_lock);
6406 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
6410 if (!l2arc_write_eligible(guid, hdr)) {
6411 mutex_exit(hash_lock);
6416 * Assume that the buffer is not going to be compressed
6417 * and could take more space on disk because of a larger
6420 buf_sz = hdr->b_size;
6421 align = (size_t)1 << dev->l2ad_vdev->vdev_ashift;
6422 buf_a_sz = P2ROUNDUP(buf_sz, align);
6424 if ((write_asize + buf_a_sz) > target_sz) {
6426 mutex_exit(hash_lock);
6427 ARCSTAT_BUMP(arcstat_l2_write_full);
6433 * Insert a dummy header on the buflist so
6434 * l2arc_write_done() can find where the
6435 * write buffers begin without searching.
6437 mutex_enter(&dev->l2ad_mtx);
6438 list_insert_head(&dev->l2ad_buflist, head);
6439 mutex_exit(&dev->l2ad_mtx);
6442 sizeof (l2arc_write_callback_t), KM_SLEEP);
6443 cb->l2wcb_dev = dev;
6444 cb->l2wcb_head = head;
6445 pio = zio_root(spa, l2arc_write_done, cb,
6447 ARCSTAT_BUMP(arcstat_l2_write_pios);
6451 * Create and add a new L2ARC header.
6453 hdr->b_l2hdr.b_dev = dev;
6454 hdr->b_flags |= ARC_FLAG_L2_WRITING;
6456 * Temporarily stash the data buffer in b_tmp_cdata.
6457 * The subsequent write step will pick it up from
6458 * there. This is because can't access b_l1hdr.b_buf
6459 * without holding the hash_lock, which we in turn
6460 * can't access without holding the ARC list locks
6461 * (which we want to avoid during compression/writing).
6463 hdr->b_l2hdr.b_compress = ZIO_COMPRESS_OFF;
6464 hdr->b_l2hdr.b_asize = hdr->b_size;
6465 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
6468 * Explicitly set the b_daddr field to a known
6469 * value which means "invalid address". This
6470 * enables us to differentiate which stage of
6471 * l2arc_write_buffers() the particular header
6472 * is in (e.g. this loop, or the one below).
6473 * ARC_FLAG_L2_WRITING is not enough to make
6474 * this distinction, and we need to know in
6475 * order to do proper l2arc vdev accounting in
6476 * arc_release() and arc_hdr_destroy().
6478 * Note, we can't use a new flag to distinguish
6479 * the two stages because we don't hold the
6480 * header's hash_lock below, in the second stage
6481 * of this function. Thus, we can't simply
6482 * change the b_flags field to denote that the
6483 * IO has been sent. We can change the b_daddr
6484 * field of the L2 portion, though, since we'll
6485 * be holding the l2ad_mtx; which is why we're
6486 * using it to denote the header's state change.
6488 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6490 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
6492 mutex_enter(&dev->l2ad_mtx);
6493 list_insert_head(&dev->l2ad_buflist, hdr);
6494 mutex_exit(&dev->l2ad_mtx);
6497 * Compute and store the buffer cksum before
6498 * writing. On debug the cksum is verified first.
6500 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6501 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
6503 mutex_exit(hash_lock);
6506 write_asize += buf_a_sz;
6509 multilist_sublist_unlock(mls);
6515 /* No buffers selected for writing? */
6518 ASSERT(!HDR_HAS_L1HDR(head));
6519 kmem_cache_free(hdr_l2only_cache, head);
6523 mutex_enter(&dev->l2ad_mtx);
6526 * Now start writing the buffers. We're starting at the write head
6527 * and work backwards, retracing the course of the buffer selector
6531 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6532 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
6537 * We rely on the L1 portion of the header below, so
6538 * it's invalid for this header to have been evicted out
6539 * of the ghost cache, prior to being written out. The
6540 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6542 ASSERT(HDR_HAS_L1HDR(hdr));
6545 * We shouldn't need to lock the buffer here, since we flagged
6546 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6547 * take care to only access its L2 cache parameters. In
6548 * particular, hdr->l1hdr.b_buf may be invalid by now due to
6551 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
6554 * Save a pointer to the original buffer data we had previously
6557 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6559 compress = HDR_L2COMPRESS(hdr) &&
6560 hdr->b_l2hdr.b_asize >= buf_compress_minsz;
6561 if (l2arc_transform_buf(hdr, compress)) {
6563 * If compression succeeded, enable headroom
6564 * boost on the next scan cycle.
6566 *headroom_boost = B_TRUE;
6570 * Get the new buffer size that accounts for compression
6573 buf_sz = hdr->b_l2hdr.b_asize;
6576 * We need to do this regardless if buf_sz is zero or
6577 * not, otherwise, when this l2hdr is evicted we'll
6578 * remove a reference that was never added.
6580 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6582 /* Compression may have squashed the buffer to zero length. */
6585 * If the data was padded or compressed, then it
6586 * it is in a new buffer.
6588 if (hdr->b_l1hdr.b_tmp_cdata != NULL)
6589 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6590 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6591 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6592 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6593 ZIO_FLAG_CANFAIL, B_FALSE);
6595 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6597 (void) zio_nowait(wzio);
6599 write_asize += buf_sz;
6600 dev->l2ad_hand += buf_sz;
6604 mutex_exit(&dev->l2ad_mtx);
6606 ASSERT3U(write_asize, <=, target_sz);
6607 ARCSTAT_BUMP(arcstat_l2_writes_sent);
6608 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6609 ARCSTAT_INCR(arcstat_l2_size, write_sz);
6610 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6611 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6614 * Bump device hand to the device start if it is approaching the end.
6615 * l2arc_evict() will already have evicted ahead for this case.
6617 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6618 dev->l2ad_hand = dev->l2ad_start;
6619 dev->l2ad_first = B_FALSE;
6622 dev->l2ad_writing = B_TRUE;
6623 (void) zio_wait(pio);
6624 dev->l2ad_writing = B_FALSE;
6626 return (write_asize);
6630 * Transforms, possibly compresses and pads, an L2ARC buffer.
6631 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6632 * size in l2hdr->b_asize. This routine tries to compress the data and
6633 * depending on the compression result there are three possible outcomes:
6634 * *) The buffer was incompressible. The buffer size was already ashift aligned.
6635 * The original hdr contents were left untouched except for b_tmp_cdata,
6636 * which is reset to NULL. The caller must keep a pointer to the original
6638 * *) The buffer was incompressible. The buffer size was not ashift aligned.
6639 * b_tmp_cdata was replaced with a temporary data buffer which holds a padded
6640 * (aligned) copy of the data. Once writing is done, invoke
6641 * l2arc_release_cdata_buf on this hdr to free the temporary buffer.
6642 * *) The buffer was all-zeros, so there is no need to write it to an L2
6643 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6644 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6645 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6646 * data buffer which holds the compressed data to be written, and b_asize
6647 * tells us how much data there is. b_compress is set to the appropriate
6648 * compression algorithm. Once writing is done, invoke
6649 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6651 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6652 * buffer was incompressible).
6655 l2arc_transform_buf(arc_buf_hdr_t *hdr, boolean_t compress)
6658 size_t align, asize, csize, len, rounded;
6660 ASSERT(HDR_HAS_L2HDR(hdr));
6661 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6663 ASSERT(HDR_HAS_L1HDR(hdr));
6664 ASSERT3S(l2hdr->b_compress, ==, ZIO_COMPRESS_OFF);
6665 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6667 len = l2hdr->b_asize;
6668 align = (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift;
6669 asize = P2ROUNDUP(len, align);
6670 cdata = zio_data_buf_alloc(asize);
6671 ASSERT3P(cdata, !=, NULL);
6673 csize = zio_compress_data(ZIO_COMPRESS_LZ4,
6674 hdr->b_l1hdr.b_tmp_cdata, cdata, len);
6679 /* zero block, indicate that there's nothing to write */
6680 zio_data_buf_free(cdata, asize);
6681 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
6683 hdr->b_l1hdr.b_tmp_cdata = NULL;
6684 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6688 rounded = P2ROUNDUP(csize, align);
6689 ASSERT3U(rounded, <=, asize);
6690 if (rounded < len) {
6692 * Compression succeeded, we'll keep the cdata around for
6693 * writing and release it afterwards.
6695 if (rounded > csize) {
6696 bzero((char *)cdata + csize, rounded - csize);
6699 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
6700 l2hdr->b_asize = csize;
6701 hdr->b_l1hdr.b_tmp_cdata = cdata;
6702 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6706 * Compression did not save space.
6708 if (P2PHASE(len, align) != 0) {
6710 * Use compression buffer for a copy of data padded to
6711 * the proper size. Compression algorithm remains set
6712 * to ZIO_COMPRESS_OFF.
6714 ASSERT3U(len, <, asize);
6715 bcopy(hdr->b_l1hdr.b_tmp_cdata, cdata, len);
6716 bzero((char *)cdata + len, asize - len);
6717 l2hdr->b_asize = asize;
6718 hdr->b_l1hdr.b_tmp_cdata = cdata;
6719 ARCSTAT_BUMP(arcstat_l2_padding_needed);
6721 ASSERT3U(len, ==, asize);
6723 * The original buffer is good as is,
6724 * release the compressed buffer.
6725 * l2hdr will be left unmodified except for b_tmp_cdata.
6727 zio_data_buf_free(cdata, asize);
6728 hdr->b_l1hdr.b_tmp_cdata = NULL;
6731 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6737 * Decompresses a zio read back from an l2arc device. On success, the
6738 * underlying zio's io_data buffer is overwritten by the uncompressed
6739 * version. On decompression error (corrupt compressed stream), the
6740 * zio->io_error value is set to signal an I/O error.
6742 * Please note that the compressed data stream is not checksummed, so
6743 * if the underlying device is experiencing data corruption, we may feed
6744 * corrupt data to the decompressor, so the decompressor needs to be
6745 * able to handle this situation (LZ4 does).
6748 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6750 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6752 if (zio->io_error != 0) {
6754 * An io error has occured, just restore the original io
6755 * size in preparation for a main pool read.
6757 zio->io_orig_size = zio->io_size = hdr->b_size;
6761 if (c == ZIO_COMPRESS_EMPTY) {
6763 * An empty buffer results in a null zio, which means we
6764 * need to fill its io_data after we're done restoring the
6765 * buffer's contents.
6767 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6768 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6769 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6771 ASSERT(zio->io_data != NULL);
6773 * We copy the compressed data from the start of the arc buffer
6774 * (the zio_read will have pulled in only what we need, the
6775 * rest is garbage which we will overwrite at decompression)
6776 * and then decompress back to the ARC data buffer. This way we
6777 * can minimize copying by simply decompressing back over the
6778 * original compressed data (rather than decompressing to an
6779 * aux buffer and then copying back the uncompressed buffer,
6780 * which is likely to be much larger).
6785 csize = zio->io_size;
6786 cdata = zio_data_buf_alloc(csize);
6787 bcopy(zio->io_data, cdata, csize);
6788 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6790 zio->io_error = EIO;
6791 zio_data_buf_free(cdata, csize);
6794 /* Restore the expected uncompressed IO size. */
6795 zio->io_orig_size = zio->io_size = hdr->b_size;
6799 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6800 * This buffer serves as a temporary holder of compressed or padded data while
6801 * the buffer entry is being written to an l2arc device. Once that is
6802 * done, we can dispose of it.
6805 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6807 size_t align, asize, len;
6808 enum zio_compress comp = hdr->b_l2hdr.b_compress;
6810 ASSERT(HDR_HAS_L2HDR(hdr));
6811 ASSERT(HDR_HAS_L1HDR(hdr));
6812 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6814 if (hdr->b_l1hdr.b_tmp_cdata != NULL) {
6815 ASSERT(comp != ZIO_COMPRESS_EMPTY);
6817 align = (size_t)1 << hdr->b_l2hdr.b_dev->l2ad_vdev->vdev_ashift;
6818 asize = P2ROUNDUP(len, align);
6819 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata, asize);
6820 hdr->b_l1hdr.b_tmp_cdata = NULL;
6822 ASSERT(comp == ZIO_COMPRESS_OFF || comp == ZIO_COMPRESS_EMPTY);
6827 * This thread feeds the L2ARC at regular intervals. This is the beating
6828 * heart of the L2ARC.
6831 l2arc_feed_thread(void *dummy __unused)
6836 uint64_t size, wrote;
6837 clock_t begin, next = ddi_get_lbolt();
6838 boolean_t headroom_boost = B_FALSE;
6840 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6842 mutex_enter(&l2arc_feed_thr_lock);
6844 while (l2arc_thread_exit == 0) {
6845 CALLB_CPR_SAFE_BEGIN(&cpr);
6846 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6847 next - ddi_get_lbolt());
6848 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6849 next = ddi_get_lbolt() + hz;
6852 * Quick check for L2ARC devices.
6854 mutex_enter(&l2arc_dev_mtx);
6855 if (l2arc_ndev == 0) {
6856 mutex_exit(&l2arc_dev_mtx);
6859 mutex_exit(&l2arc_dev_mtx);
6860 begin = ddi_get_lbolt();
6863 * This selects the next l2arc device to write to, and in
6864 * doing so the next spa to feed from: dev->l2ad_spa. This
6865 * will return NULL if there are now no l2arc devices or if
6866 * they are all faulted.
6868 * If a device is returned, its spa's config lock is also
6869 * held to prevent device removal. l2arc_dev_get_next()
6870 * will grab and release l2arc_dev_mtx.
6872 if ((dev = l2arc_dev_get_next()) == NULL)
6875 spa = dev->l2ad_spa;
6876 ASSERT(spa != NULL);
6879 * If the pool is read-only then force the feed thread to
6880 * sleep a little longer.
6882 if (!spa_writeable(spa)) {
6883 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6884 spa_config_exit(spa, SCL_L2ARC, dev);
6889 * Avoid contributing to memory pressure.
6891 if (arc_reclaim_needed()) {
6892 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6893 spa_config_exit(spa, SCL_L2ARC, dev);
6897 ARCSTAT_BUMP(arcstat_l2_feeds);
6899 size = l2arc_write_size();
6902 * Evict L2ARC buffers that will be overwritten.
6904 l2arc_evict(dev, size, B_FALSE);
6907 * Write ARC buffers.
6909 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6912 * Calculate interval between writes.
6914 next = l2arc_write_interval(begin, size, wrote);
6915 spa_config_exit(spa, SCL_L2ARC, dev);
6918 l2arc_thread_exit = 0;
6919 cv_broadcast(&l2arc_feed_thr_cv);
6920 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6925 l2arc_vdev_present(vdev_t *vd)
6929 mutex_enter(&l2arc_dev_mtx);
6930 for (dev = list_head(l2arc_dev_list); dev != NULL;
6931 dev = list_next(l2arc_dev_list, dev)) {
6932 if (dev->l2ad_vdev == vd)
6935 mutex_exit(&l2arc_dev_mtx);
6937 return (dev != NULL);
6941 * Add a vdev for use by the L2ARC. By this point the spa has already
6942 * validated the vdev and opened it.
6945 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6947 l2arc_dev_t *adddev;
6949 ASSERT(!l2arc_vdev_present(vd));
6951 vdev_ashift_optimize(vd);
6954 * Create a new l2arc device entry.
6956 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6957 adddev->l2ad_spa = spa;
6958 adddev->l2ad_vdev = vd;
6959 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6960 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6961 adddev->l2ad_hand = adddev->l2ad_start;
6962 adddev->l2ad_first = B_TRUE;
6963 adddev->l2ad_writing = B_FALSE;
6965 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6967 * This is a list of all ARC buffers that are still valid on the
6970 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6971 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6973 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6974 refcount_create(&adddev->l2ad_alloc);
6977 * Add device to global list
6979 mutex_enter(&l2arc_dev_mtx);
6980 list_insert_head(l2arc_dev_list, adddev);
6981 atomic_inc_64(&l2arc_ndev);
6982 mutex_exit(&l2arc_dev_mtx);
6986 * Remove a vdev from the L2ARC.
6989 l2arc_remove_vdev(vdev_t *vd)
6991 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6994 * Find the device by vdev
6996 mutex_enter(&l2arc_dev_mtx);
6997 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6998 nextdev = list_next(l2arc_dev_list, dev);
6999 if (vd == dev->l2ad_vdev) {
7004 ASSERT(remdev != NULL);
7007 * Remove device from global list
7009 list_remove(l2arc_dev_list, remdev);
7010 l2arc_dev_last = NULL; /* may have been invalidated */
7011 atomic_dec_64(&l2arc_ndev);
7012 mutex_exit(&l2arc_dev_mtx);
7015 * Clear all buflists and ARC references. L2ARC device flush.
7017 l2arc_evict(remdev, 0, B_TRUE);
7018 list_destroy(&remdev->l2ad_buflist);
7019 mutex_destroy(&remdev->l2ad_mtx);
7020 refcount_destroy(&remdev->l2ad_alloc);
7021 kmem_free(remdev, sizeof (l2arc_dev_t));
7027 l2arc_thread_exit = 0;
7029 l2arc_writes_sent = 0;
7030 l2arc_writes_done = 0;
7032 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7033 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7034 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7035 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7037 l2arc_dev_list = &L2ARC_dev_list;
7038 l2arc_free_on_write = &L2ARC_free_on_write;
7039 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7040 offsetof(l2arc_dev_t, l2ad_node));
7041 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7042 offsetof(l2arc_data_free_t, l2df_list_node));
7049 * This is called from dmu_fini(), which is called from spa_fini();
7050 * Because of this, we can assume that all l2arc devices have
7051 * already been removed when the pools themselves were removed.
7054 l2arc_do_free_on_write();
7056 mutex_destroy(&l2arc_feed_thr_lock);
7057 cv_destroy(&l2arc_feed_thr_cv);
7058 mutex_destroy(&l2arc_dev_mtx);
7059 mutex_destroy(&l2arc_free_on_write_mtx);
7061 list_destroy(l2arc_dev_list);
7062 list_destroy(l2arc_free_on_write);
7068 if (!(spa_mode_global & FWRITE))
7071 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7072 TS_RUN, minclsyspri);
7078 if (!(spa_mode_global & FWRITE))
7081 mutex_enter(&l2arc_feed_thr_lock);
7082 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7083 l2arc_thread_exit = 1;
7084 while (l2arc_thread_exit != 0)
7085 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7086 mutex_exit(&l2arc_feed_thr_lock);