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) 2011, 2014 by Delphix. All rights reserved.
24 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
25 * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
29 * DVA-based Adjustable Replacement Cache
31 * While much of the theory of operation used here is
32 * based on the self-tuning, low overhead replacement cache
33 * presented by Megiddo and Modha at FAST 2003, there are some
34 * significant differences:
36 * 1. The Megiddo and Modha model assumes any page is evictable.
37 * Pages in its cache cannot be "locked" into memory. This makes
38 * the eviction algorithm simple: evict the last page in the list.
39 * This also make the performance characteristics easy to reason
40 * about. Our cache is not so simple. At any given moment, some
41 * subset of the blocks in the cache are un-evictable because we
42 * have handed out a reference to them. Blocks are only evictable
43 * when there are no external references active. This makes
44 * eviction far more problematic: we choose to evict the evictable
45 * blocks that are the "lowest" in the list.
47 * There are times when it is not possible to evict the requested
48 * space. In these circumstances we are unable to adjust the cache
49 * size. To prevent the cache growing unbounded at these times we
50 * implement a "cache throttle" that slows the flow of new data
51 * into the cache until we can make space available.
53 * 2. The Megiddo and Modha model assumes a fixed cache size.
54 * Pages are evicted when the cache is full and there is a cache
55 * miss. Our model has a variable sized cache. It grows with
56 * high use, but also tries to react to memory pressure from the
57 * operating system: decreasing its size when system memory is
60 * 3. The Megiddo and Modha model assumes a fixed page size. All
61 * elements of the cache are therefore exactly the same size. So
62 * when adjusting the cache size following a cache miss, its simply
63 * a matter of choosing a single page to evict. In our model, we
64 * have variable sized cache blocks (rangeing from 512 bytes to
65 * 128K bytes). We therefore choose a set of blocks to evict to make
66 * space for a cache miss that approximates as closely as possible
67 * the space used by the new block.
69 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70 * by N. Megiddo & D. Modha, FAST 2003
76 * A new reference to a cache buffer can be obtained in two
77 * ways: 1) via a hash table lookup using the DVA as a key,
78 * or 2) via one of the ARC lists. The arc_read() interface
79 * uses method 1, while the internal arc algorithms for
80 * adjusting the cache use method 2. We therefore provide two
81 * types of locks: 1) the hash table lock array, and 2) the
84 * Buffers do not have their own mutexs, rather they rely on the
85 * hash table mutexs for the bulk of their protection (i.e. most
86 * fields in the arc_buf_hdr_t are protected by these mutexs).
88 * buf_hash_find() returns the appropriate mutex (held) when it
89 * locates the requested buffer in the hash table. It returns
90 * NULL for the mutex if the buffer was not in the table.
92 * buf_hash_remove() expects the appropriate hash mutex to be
93 * already held before it is invoked.
95 * Each arc state also has a mutex which is used to protect the
96 * buffer list associated with the state. When attempting to
97 * obtain a hash table lock while holding an arc list lock you
98 * must use: mutex_tryenter() to avoid deadlock. Also note that
99 * the active state mutex must be held before the ghost state mutex.
101 * Arc buffers may have an associated eviction callback function.
102 * This function will be invoked prior to removing the buffer (e.g.
103 * in arc_do_user_evicts()). Note however that the data associated
104 * with the buffer may be evicted prior to the callback. The callback
105 * must be made with *no locks held* (to prevent deadlock). Additionally,
106 * the users of callbacks must ensure that their private data is
107 * protected from simultaneous callbacks from arc_clear_callback()
108 * and arc_do_user_evicts().
110 * Note that the majority of the performance stats are manipulated
111 * with atomic operations.
113 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
115 * - L2ARC buflist creation
116 * - L2ARC buflist eviction
117 * - L2ARC write completion, which walks L2ARC buflists
118 * - ARC header destruction, as it removes from L2ARC buflists
119 * - ARC header release, as it removes from L2ARC buflists
124 #include <sys/zio_compress.h>
125 #include <sys/zfs_context.h>
127 #include <sys/refcount.h>
128 #include <sys/vdev.h>
129 #include <sys/vdev_impl.h>
130 #include <sys/dsl_pool.h>
132 #include <sys/dnlc.h>
134 #include <sys/callb.h>
135 #include <sys/kstat.h>
136 #include <sys/trim_map.h>
137 #include <zfs_fletcher.h>
140 #include <vm/vm_pageout.h>
141 #include <machine/vmparam.h>
145 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
146 boolean_t arc_watch = B_FALSE;
151 static kmutex_t arc_reclaim_thr_lock;
152 static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
153 static uint8_t arc_thread_exit;
155 #define ARC_REDUCE_DNLC_PERCENT 3
156 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
158 typedef enum arc_reclaim_strategy {
159 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
160 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
161 } arc_reclaim_strategy_t;
164 * The number of iterations through arc_evict_*() before we
165 * drop & reacquire the lock.
167 int arc_evict_iterations = 100;
169 /* number of seconds before growing cache again */
170 static int arc_grow_retry = 60;
172 /* shift of arc_c for calculating both min and max arc_p */
173 static int arc_p_min_shift = 4;
175 /* log2(fraction of arc to reclaim) */
176 static int arc_shrink_shift = 5;
179 * minimum lifespan of a prefetch block in clock ticks
180 * (initialized in arc_init())
182 static int arc_min_prefetch_lifespan;
185 * If this percent of memory is free, don't throttle.
187 int arc_lotsfree_percent = 10;
190 extern int zfs_prefetch_disable;
193 * The arc has filled available memory and has now warmed up.
195 static boolean_t arc_warm;
197 uint64_t zfs_arc_max;
198 uint64_t zfs_arc_min;
199 uint64_t zfs_arc_meta_limit = 0;
200 int zfs_arc_grow_retry = 0;
201 int zfs_arc_shrink_shift = 0;
202 int zfs_arc_p_min_shift = 0;
203 int zfs_disable_dup_eviction = 0;
204 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
205 u_int zfs_arc_free_target = 0;
207 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
211 arc_free_target_init(void *unused __unused)
214 zfs_arc_free_target = vm_pageout_wakeup_thresh;
216 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
217 arc_free_target_init, NULL);
219 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
220 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
221 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
222 TUNABLE_QUAD("vfs.zfs.arc_average_blocksize", &zfs_arc_average_blocksize);
223 SYSCTL_DECL(_vfs_zfs);
224 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
226 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
228 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
229 &zfs_arc_average_blocksize, 0,
230 "ARC average blocksize");
232 * We don't have a tunable for arc_free_target due to the dependency on
233 * pagedaemon initialisation.
235 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
236 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
237 sysctl_vfs_zfs_arc_free_target, "IU",
238 "Desired number of free pages below which ARC triggers reclaim");
241 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
246 val = zfs_arc_free_target;
247 err = sysctl_handle_int(oidp, &val, 0, req);
248 if (err != 0 || req->newptr == NULL)
253 if (val > cnt.v_page_count)
256 zfs_arc_free_target = val;
263 * Note that buffers can be in one of 6 states:
264 * ARC_anon - anonymous (discussed below)
265 * ARC_mru - recently used, currently cached
266 * ARC_mru_ghost - recentely used, no longer in cache
267 * ARC_mfu - frequently used, currently cached
268 * ARC_mfu_ghost - frequently used, no longer in cache
269 * ARC_l2c_only - exists in L2ARC but not other states
270 * When there are no active references to the buffer, they are
271 * are linked onto a list in one of these arc states. These are
272 * the only buffers that can be evicted or deleted. Within each
273 * state there are multiple lists, one for meta-data and one for
274 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
275 * etc.) is tracked separately so that it can be managed more
276 * explicitly: favored over data, limited explicitly.
278 * Anonymous buffers are buffers that are not associated with
279 * a DVA. These are buffers that hold dirty block copies
280 * before they are written to stable storage. By definition,
281 * they are "ref'd" and are considered part of arc_mru
282 * that cannot be freed. Generally, they will aquire a DVA
283 * as they are written and migrate onto the arc_mru list.
285 * The ARC_l2c_only state is for buffers that are in the second
286 * level ARC but no longer in any of the ARC_m* lists. The second
287 * level ARC itself may also contain buffers that are in any of
288 * the ARC_m* states - meaning that a buffer can exist in two
289 * places. The reason for the ARC_l2c_only state is to keep the
290 * buffer header in the hash table, so that reads that hit the
291 * second level ARC benefit from these fast lookups.
294 #define ARCS_LOCK_PAD CACHE_LINE_SIZE
298 unsigned char pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
303 * must be power of two for mask use to work
306 #define ARC_BUFC_NUMDATALISTS 16
307 #define ARC_BUFC_NUMMETADATALISTS 16
308 #define ARC_BUFC_NUMLISTS (ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
310 typedef struct arc_state {
311 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
312 uint64_t arcs_size; /* total amount of data in this state */
313 list_t arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
314 struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
317 #define ARCS_LOCK(s, i) (&((s)->arcs_locks[(i)].arcs_lock))
320 static arc_state_t ARC_anon;
321 static arc_state_t ARC_mru;
322 static arc_state_t ARC_mru_ghost;
323 static arc_state_t ARC_mfu;
324 static arc_state_t ARC_mfu_ghost;
325 static arc_state_t ARC_l2c_only;
327 typedef struct arc_stats {
328 kstat_named_t arcstat_hits;
329 kstat_named_t arcstat_misses;
330 kstat_named_t arcstat_demand_data_hits;
331 kstat_named_t arcstat_demand_data_misses;
332 kstat_named_t arcstat_demand_metadata_hits;
333 kstat_named_t arcstat_demand_metadata_misses;
334 kstat_named_t arcstat_prefetch_data_hits;
335 kstat_named_t arcstat_prefetch_data_misses;
336 kstat_named_t arcstat_prefetch_metadata_hits;
337 kstat_named_t arcstat_prefetch_metadata_misses;
338 kstat_named_t arcstat_mru_hits;
339 kstat_named_t arcstat_mru_ghost_hits;
340 kstat_named_t arcstat_mfu_hits;
341 kstat_named_t arcstat_mfu_ghost_hits;
342 kstat_named_t arcstat_allocated;
343 kstat_named_t arcstat_deleted;
344 kstat_named_t arcstat_stolen;
345 kstat_named_t arcstat_recycle_miss;
347 * Number of buffers that could not be evicted because the hash lock
348 * was held by another thread. The lock may not necessarily be held
349 * by something using the same buffer, since hash locks are shared
350 * by multiple buffers.
352 kstat_named_t arcstat_mutex_miss;
354 * Number of buffers skipped because they have I/O in progress, are
355 * indrect prefetch buffers that have not lived long enough, or are
356 * not from the spa we're trying to evict from.
358 kstat_named_t arcstat_evict_skip;
359 kstat_named_t arcstat_evict_l2_cached;
360 kstat_named_t arcstat_evict_l2_eligible;
361 kstat_named_t arcstat_evict_l2_ineligible;
362 kstat_named_t arcstat_hash_elements;
363 kstat_named_t arcstat_hash_elements_max;
364 kstat_named_t arcstat_hash_collisions;
365 kstat_named_t arcstat_hash_chains;
366 kstat_named_t arcstat_hash_chain_max;
367 kstat_named_t arcstat_p;
368 kstat_named_t arcstat_c;
369 kstat_named_t arcstat_c_min;
370 kstat_named_t arcstat_c_max;
371 kstat_named_t arcstat_size;
372 kstat_named_t arcstat_hdr_size;
373 kstat_named_t arcstat_data_size;
374 kstat_named_t arcstat_other_size;
375 kstat_named_t arcstat_l2_hits;
376 kstat_named_t arcstat_l2_misses;
377 kstat_named_t arcstat_l2_feeds;
378 kstat_named_t arcstat_l2_rw_clash;
379 kstat_named_t arcstat_l2_read_bytes;
380 kstat_named_t arcstat_l2_write_bytes;
381 kstat_named_t arcstat_l2_writes_sent;
382 kstat_named_t arcstat_l2_writes_done;
383 kstat_named_t arcstat_l2_writes_error;
384 kstat_named_t arcstat_l2_writes_hdr_miss;
385 kstat_named_t arcstat_l2_evict_lock_retry;
386 kstat_named_t arcstat_l2_evict_reading;
387 kstat_named_t arcstat_l2_free_on_write;
388 kstat_named_t arcstat_l2_abort_lowmem;
389 kstat_named_t arcstat_l2_cksum_bad;
390 kstat_named_t arcstat_l2_io_error;
391 kstat_named_t arcstat_l2_size;
392 kstat_named_t arcstat_l2_asize;
393 kstat_named_t arcstat_l2_hdr_size;
394 kstat_named_t arcstat_l2_compress_successes;
395 kstat_named_t arcstat_l2_compress_zeros;
396 kstat_named_t arcstat_l2_compress_failures;
397 kstat_named_t arcstat_l2_write_trylock_fail;
398 kstat_named_t arcstat_l2_write_passed_headroom;
399 kstat_named_t arcstat_l2_write_spa_mismatch;
400 kstat_named_t arcstat_l2_write_in_l2;
401 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
402 kstat_named_t arcstat_l2_write_not_cacheable;
403 kstat_named_t arcstat_l2_write_full;
404 kstat_named_t arcstat_l2_write_buffer_iter;
405 kstat_named_t arcstat_l2_write_pios;
406 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
407 kstat_named_t arcstat_l2_write_buffer_list_iter;
408 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
409 kstat_named_t arcstat_memory_throttle_count;
410 kstat_named_t arcstat_duplicate_buffers;
411 kstat_named_t arcstat_duplicate_buffers_size;
412 kstat_named_t arcstat_duplicate_reads;
415 static arc_stats_t arc_stats = {
416 { "hits", KSTAT_DATA_UINT64 },
417 { "misses", KSTAT_DATA_UINT64 },
418 { "demand_data_hits", KSTAT_DATA_UINT64 },
419 { "demand_data_misses", KSTAT_DATA_UINT64 },
420 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
421 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
422 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
423 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
424 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
425 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
426 { "mru_hits", KSTAT_DATA_UINT64 },
427 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
428 { "mfu_hits", KSTAT_DATA_UINT64 },
429 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
430 { "allocated", KSTAT_DATA_UINT64 },
431 { "deleted", KSTAT_DATA_UINT64 },
432 { "stolen", KSTAT_DATA_UINT64 },
433 { "recycle_miss", KSTAT_DATA_UINT64 },
434 { "mutex_miss", KSTAT_DATA_UINT64 },
435 { "evict_skip", KSTAT_DATA_UINT64 },
436 { "evict_l2_cached", KSTAT_DATA_UINT64 },
437 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
438 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
439 { "hash_elements", KSTAT_DATA_UINT64 },
440 { "hash_elements_max", KSTAT_DATA_UINT64 },
441 { "hash_collisions", KSTAT_DATA_UINT64 },
442 { "hash_chains", KSTAT_DATA_UINT64 },
443 { "hash_chain_max", KSTAT_DATA_UINT64 },
444 { "p", KSTAT_DATA_UINT64 },
445 { "c", KSTAT_DATA_UINT64 },
446 { "c_min", KSTAT_DATA_UINT64 },
447 { "c_max", KSTAT_DATA_UINT64 },
448 { "size", KSTAT_DATA_UINT64 },
449 { "hdr_size", KSTAT_DATA_UINT64 },
450 { "data_size", KSTAT_DATA_UINT64 },
451 { "other_size", KSTAT_DATA_UINT64 },
452 { "l2_hits", KSTAT_DATA_UINT64 },
453 { "l2_misses", KSTAT_DATA_UINT64 },
454 { "l2_feeds", KSTAT_DATA_UINT64 },
455 { "l2_rw_clash", KSTAT_DATA_UINT64 },
456 { "l2_read_bytes", KSTAT_DATA_UINT64 },
457 { "l2_write_bytes", KSTAT_DATA_UINT64 },
458 { "l2_writes_sent", KSTAT_DATA_UINT64 },
459 { "l2_writes_done", KSTAT_DATA_UINT64 },
460 { "l2_writes_error", KSTAT_DATA_UINT64 },
461 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
462 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
463 { "l2_evict_reading", KSTAT_DATA_UINT64 },
464 { "l2_free_on_write", KSTAT_DATA_UINT64 },
465 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
466 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
467 { "l2_io_error", KSTAT_DATA_UINT64 },
468 { "l2_size", KSTAT_DATA_UINT64 },
469 { "l2_asize", KSTAT_DATA_UINT64 },
470 { "l2_hdr_size", KSTAT_DATA_UINT64 },
471 { "l2_compress_successes", KSTAT_DATA_UINT64 },
472 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
473 { "l2_compress_failures", KSTAT_DATA_UINT64 },
474 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
475 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
476 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
477 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
478 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
479 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
480 { "l2_write_full", KSTAT_DATA_UINT64 },
481 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
482 { "l2_write_pios", KSTAT_DATA_UINT64 },
483 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
484 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
485 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
486 { "memory_throttle_count", KSTAT_DATA_UINT64 },
487 { "duplicate_buffers", KSTAT_DATA_UINT64 },
488 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
489 { "duplicate_reads", KSTAT_DATA_UINT64 }
492 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
494 #define ARCSTAT_INCR(stat, val) \
495 atomic_add_64(&arc_stats.stat.value.ui64, (val))
497 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
498 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
500 #define ARCSTAT_MAX(stat, val) { \
502 while ((val) > (m = arc_stats.stat.value.ui64) && \
503 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
507 #define ARCSTAT_MAXSTAT(stat) \
508 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
511 * We define a macro to allow ARC hits/misses to be easily broken down by
512 * two separate conditions, giving a total of four different subtypes for
513 * each of hits and misses (so eight statistics total).
515 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
518 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
520 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
524 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
526 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
531 static arc_state_t *arc_anon;
532 static arc_state_t *arc_mru;
533 static arc_state_t *arc_mru_ghost;
534 static arc_state_t *arc_mfu;
535 static arc_state_t *arc_mfu_ghost;
536 static arc_state_t *arc_l2c_only;
539 * There are several ARC variables that are critical to export as kstats --
540 * but we don't want to have to grovel around in the kstat whenever we wish to
541 * manipulate them. For these variables, we therefore define them to be in
542 * terms of the statistic variable. This assures that we are not introducing
543 * the possibility of inconsistency by having shadow copies of the variables,
544 * while still allowing the code to be readable.
546 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
547 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
548 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
549 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
550 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
552 #define L2ARC_IS_VALID_COMPRESS(_c_) \
553 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
555 static int arc_no_grow; /* Don't try to grow cache size */
556 static uint64_t arc_tempreserve;
557 static uint64_t arc_loaned_bytes;
558 static uint64_t arc_meta_used;
559 static uint64_t arc_meta_limit;
560 static uint64_t arc_meta_max = 0;
561 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_used, CTLFLAG_RD, &arc_meta_used, 0,
562 "ARC metadata used");
563 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_limit, CTLFLAG_RW, &arc_meta_limit, 0,
564 "ARC metadata limit");
566 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
568 typedef struct arc_callback arc_callback_t;
570 struct arc_callback {
572 arc_done_func_t *acb_done;
574 zio_t *acb_zio_dummy;
575 arc_callback_t *acb_next;
578 typedef struct arc_write_callback arc_write_callback_t;
580 struct arc_write_callback {
582 arc_done_func_t *awcb_ready;
583 arc_done_func_t *awcb_physdone;
584 arc_done_func_t *awcb_done;
589 /* protected by hash lock */
594 kmutex_t b_freeze_lock;
595 zio_cksum_t *b_freeze_cksum;
598 arc_buf_hdr_t *b_hash_next;
603 arc_callback_t *b_acb;
607 arc_buf_contents_t b_type;
611 /* protected by arc state mutex */
612 arc_state_t *b_state;
613 list_node_t b_arc_node;
615 /* updated atomically */
616 clock_t b_arc_access;
618 /* self protecting */
621 l2arc_buf_hdr_t *b_l2hdr;
622 list_node_t b_l2node;
625 static arc_buf_t *arc_eviction_list;
626 static kmutex_t arc_eviction_mtx;
627 static arc_buf_hdr_t arc_eviction_hdr;
628 static void arc_get_data_buf(arc_buf_t *buf);
629 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
630 static int arc_evict_needed(arc_buf_contents_t type);
631 static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
633 static void arc_buf_watch(arc_buf_t *buf);
636 static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
638 #define GHOST_STATE(state) \
639 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
640 (state) == arc_l2c_only)
643 * Private ARC flags. These flags are private ARC only flags that will show up
644 * in b_flags in the arc_hdr_buf_t. Some flags are publicly declared, and can
645 * be passed in as arc_flags in things like arc_read. However, these flags
646 * should never be passed and should only be set by ARC code. When adding new
647 * public flags, make sure not to smash the private ones.
650 #define ARC_IN_HASH_TABLE (1 << 9) /* this buffer is hashed */
651 #define ARC_IO_IN_PROGRESS (1 << 10) /* I/O in progress for buf */
652 #define ARC_IO_ERROR (1 << 11) /* I/O failed for buf */
653 #define ARC_FREED_IN_READ (1 << 12) /* buf freed while in read */
654 #define ARC_BUF_AVAILABLE (1 << 13) /* block not in active use */
655 #define ARC_INDIRECT (1 << 14) /* this is an indirect block */
656 #define ARC_FREE_IN_PROGRESS (1 << 15) /* hdr about to be freed */
657 #define ARC_L2_WRITING (1 << 16) /* L2ARC write in progress */
658 #define ARC_L2_EVICTED (1 << 17) /* evicted during I/O */
659 #define ARC_L2_WRITE_HEAD (1 << 18) /* head of write list */
661 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_IN_HASH_TABLE)
662 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS)
663 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_IO_ERROR)
664 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_PREFETCH)
665 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FREED_IN_READ)
666 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_BUF_AVAILABLE)
667 #define HDR_FREE_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
668 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_L2CACHE)
669 #define HDR_L2_READING(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS && \
670 (hdr)->b_l2hdr != NULL)
671 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_L2_WRITING)
672 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_L2_EVICTED)
673 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_L2_WRITE_HEAD)
679 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
680 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
683 * Hash table routines
686 #define HT_LOCK_PAD CACHE_LINE_SIZE
691 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
695 #define BUF_LOCKS 256
696 typedef struct buf_hash_table {
698 arc_buf_hdr_t **ht_table;
699 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
702 static buf_hash_table_t buf_hash_table;
704 #define BUF_HASH_INDEX(spa, dva, birth) \
705 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
706 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
707 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
708 #define HDR_LOCK(hdr) \
709 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
711 uint64_t zfs_crc64_table[256];
717 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
718 #define L2ARC_HEADROOM 2 /* num of writes */
720 * If we discover during ARC scan any buffers to be compressed, we boost
721 * our headroom for the next scanning cycle by this percentage multiple.
723 #define L2ARC_HEADROOM_BOOST 200
724 #define L2ARC_FEED_SECS 1 /* caching interval secs */
725 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
727 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
728 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
730 /* L2ARC Performance Tunables */
731 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
732 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
733 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
734 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
735 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
736 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
737 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
738 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
739 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
741 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
742 &l2arc_write_max, 0, "max write size");
743 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
744 &l2arc_write_boost, 0, "extra write during warmup");
745 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
746 &l2arc_headroom, 0, "number of dev writes");
747 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
748 &l2arc_feed_secs, 0, "interval seconds");
749 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
750 &l2arc_feed_min_ms, 0, "min interval milliseconds");
752 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
753 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
754 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
755 &l2arc_feed_again, 0, "turbo warmup");
756 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
757 &l2arc_norw, 0, "no reads during writes");
759 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
760 &ARC_anon.arcs_size, 0, "size of anonymous state");
761 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
762 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
763 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
764 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
766 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
767 &ARC_mru.arcs_size, 0, "size of mru state");
768 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
769 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
770 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
771 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
773 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
774 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
775 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
776 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
777 "size of metadata in mru ghost state");
778 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
779 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
780 "size of data in mru ghost state");
782 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
783 &ARC_mfu.arcs_size, 0, "size of mfu state");
784 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
785 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
786 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
787 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
789 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
790 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
791 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
792 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
793 "size of metadata in mfu ghost state");
794 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
795 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
796 "size of data in mfu ghost state");
798 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
799 &ARC_l2c_only.arcs_size, 0, "size of mru state");
804 typedef struct l2arc_dev {
805 vdev_t *l2ad_vdev; /* vdev */
806 spa_t *l2ad_spa; /* spa */
807 uint64_t l2ad_hand; /* next write location */
808 uint64_t l2ad_start; /* first addr on device */
809 uint64_t l2ad_end; /* last addr on device */
810 uint64_t l2ad_evict; /* last addr eviction reached */
811 boolean_t l2ad_first; /* first sweep through */
812 boolean_t l2ad_writing; /* currently writing */
813 list_t *l2ad_buflist; /* buffer list */
814 list_node_t l2ad_node; /* device list node */
817 static list_t L2ARC_dev_list; /* device list */
818 static list_t *l2arc_dev_list; /* device list pointer */
819 static kmutex_t l2arc_dev_mtx; /* device list mutex */
820 static l2arc_dev_t *l2arc_dev_last; /* last device used */
821 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
822 static list_t L2ARC_free_on_write; /* free after write buf list */
823 static list_t *l2arc_free_on_write; /* free after write list ptr */
824 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
825 static uint64_t l2arc_ndev; /* number of devices */
827 typedef struct l2arc_read_callback {
828 arc_buf_t *l2rcb_buf; /* read buffer */
829 spa_t *l2rcb_spa; /* spa */
830 blkptr_t l2rcb_bp; /* original blkptr */
831 zbookmark_phys_t l2rcb_zb; /* original bookmark */
832 int l2rcb_flags; /* original flags */
833 enum zio_compress l2rcb_compress; /* applied compress */
834 } l2arc_read_callback_t;
836 typedef struct l2arc_write_callback {
837 l2arc_dev_t *l2wcb_dev; /* device info */
838 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
839 } l2arc_write_callback_t;
841 struct l2arc_buf_hdr {
842 /* protected by arc_buf_hdr mutex */
843 l2arc_dev_t *b_dev; /* L2ARC device */
844 uint64_t b_daddr; /* disk address, offset byte */
845 /* compression applied to buffer data */
846 enum zio_compress b_compress;
847 /* real alloc'd buffer size depending on b_compress applied */
849 /* temporary buffer holder for in-flight compressed data */
853 typedef struct l2arc_data_free {
854 /* protected by l2arc_free_on_write_mtx */
857 void (*l2df_func)(void *, size_t);
858 list_node_t l2df_list_node;
861 static kmutex_t l2arc_feed_thr_lock;
862 static kcondvar_t l2arc_feed_thr_cv;
863 static uint8_t l2arc_thread_exit;
865 static void l2arc_read_done(zio_t *zio);
866 static void l2arc_hdr_stat_add(void);
867 static void l2arc_hdr_stat_remove(void);
869 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
870 static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
871 enum zio_compress c);
872 static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
875 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
877 uint8_t *vdva = (uint8_t *)dva;
878 uint64_t crc = -1ULL;
881 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
883 for (i = 0; i < sizeof (dva_t); i++)
884 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
886 crc ^= (spa>>8) ^ birth;
891 #define BUF_EMPTY(buf) \
892 ((buf)->b_dva.dva_word[0] == 0 && \
893 (buf)->b_dva.dva_word[1] == 0 && \
894 (buf)->b_cksum0 == 0)
896 #define BUF_EQUAL(spa, dva, birth, buf) \
897 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
898 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
899 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
902 buf_discard_identity(arc_buf_hdr_t *hdr)
904 hdr->b_dva.dva_word[0] = 0;
905 hdr->b_dva.dva_word[1] = 0;
910 static arc_buf_hdr_t *
911 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
913 const dva_t *dva = BP_IDENTITY(bp);
914 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
915 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
916 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
919 mutex_enter(hash_lock);
920 for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
921 buf = buf->b_hash_next) {
922 if (BUF_EQUAL(spa, dva, birth, buf)) {
927 mutex_exit(hash_lock);
933 * Insert an entry into the hash table. If there is already an element
934 * equal to elem in the hash table, then the already existing element
935 * will be returned and the new element will not be inserted.
936 * Otherwise returns NULL.
938 static arc_buf_hdr_t *
939 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
941 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
942 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
946 ASSERT(!DVA_IS_EMPTY(&buf->b_dva));
947 ASSERT(buf->b_birth != 0);
948 ASSERT(!HDR_IN_HASH_TABLE(buf));
950 mutex_enter(hash_lock);
951 for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
952 fbuf = fbuf->b_hash_next, i++) {
953 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
957 buf->b_hash_next = buf_hash_table.ht_table[idx];
958 buf_hash_table.ht_table[idx] = buf;
959 buf->b_flags |= ARC_IN_HASH_TABLE;
961 /* collect some hash table performance data */
963 ARCSTAT_BUMP(arcstat_hash_collisions);
965 ARCSTAT_BUMP(arcstat_hash_chains);
967 ARCSTAT_MAX(arcstat_hash_chain_max, i);
970 ARCSTAT_BUMP(arcstat_hash_elements);
971 ARCSTAT_MAXSTAT(arcstat_hash_elements);
977 buf_hash_remove(arc_buf_hdr_t *buf)
979 arc_buf_hdr_t *fbuf, **bufp;
980 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
982 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
983 ASSERT(HDR_IN_HASH_TABLE(buf));
985 bufp = &buf_hash_table.ht_table[idx];
986 while ((fbuf = *bufp) != buf) {
987 ASSERT(fbuf != NULL);
988 bufp = &fbuf->b_hash_next;
990 *bufp = buf->b_hash_next;
991 buf->b_hash_next = NULL;
992 buf->b_flags &= ~ARC_IN_HASH_TABLE;
994 /* collect some hash table performance data */
995 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
997 if (buf_hash_table.ht_table[idx] &&
998 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
999 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1003 * Global data structures and functions for the buf kmem cache.
1005 static kmem_cache_t *hdr_cache;
1006 static kmem_cache_t *buf_cache;
1013 kmem_free(buf_hash_table.ht_table,
1014 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1015 for (i = 0; i < BUF_LOCKS; i++)
1016 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1017 kmem_cache_destroy(hdr_cache);
1018 kmem_cache_destroy(buf_cache);
1022 * Constructor callback - called when the cache is empty
1023 * and a new buf is requested.
1027 hdr_cons(void *vbuf, void *unused, int kmflag)
1029 arc_buf_hdr_t *buf = vbuf;
1031 bzero(buf, sizeof (arc_buf_hdr_t));
1032 refcount_create(&buf->b_refcnt);
1033 cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
1034 mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1035 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1042 buf_cons(void *vbuf, void *unused, int kmflag)
1044 arc_buf_t *buf = vbuf;
1046 bzero(buf, sizeof (arc_buf_t));
1047 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1048 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1054 * Destructor callback - called when a cached buf is
1055 * no longer required.
1059 hdr_dest(void *vbuf, void *unused)
1061 arc_buf_hdr_t *buf = vbuf;
1063 ASSERT(BUF_EMPTY(buf));
1064 refcount_destroy(&buf->b_refcnt);
1065 cv_destroy(&buf->b_cv);
1066 mutex_destroy(&buf->b_freeze_lock);
1067 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1072 buf_dest(void *vbuf, void *unused)
1074 arc_buf_t *buf = vbuf;
1076 mutex_destroy(&buf->b_evict_lock);
1077 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1081 * Reclaim callback -- invoked when memory is low.
1085 hdr_recl(void *unused)
1087 dprintf("hdr_recl called\n");
1089 * umem calls the reclaim func when we destroy the buf cache,
1090 * which is after we do arc_fini().
1093 cv_signal(&arc_reclaim_thr_cv);
1100 uint64_t hsize = 1ULL << 12;
1104 * The hash table is big enough to fill all of physical memory
1105 * with an average block size of zfs_arc_average_blocksize (default 8K).
1106 * By default, the table will take up
1107 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1109 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1112 buf_hash_table.ht_mask = hsize - 1;
1113 buf_hash_table.ht_table =
1114 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1115 if (buf_hash_table.ht_table == NULL) {
1116 ASSERT(hsize > (1ULL << 8));
1121 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1122 0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1123 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1124 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1126 for (i = 0; i < 256; i++)
1127 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1128 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1130 for (i = 0; i < BUF_LOCKS; i++) {
1131 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1132 NULL, MUTEX_DEFAULT, NULL);
1136 #define ARC_MINTIME (hz>>4) /* 62 ms */
1139 arc_cksum_verify(arc_buf_t *buf)
1143 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1146 mutex_enter(&buf->b_hdr->b_freeze_lock);
1147 if (buf->b_hdr->b_freeze_cksum == NULL ||
1148 (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1149 mutex_exit(&buf->b_hdr->b_freeze_lock);
1152 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1153 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1154 panic("buffer modified while frozen!");
1155 mutex_exit(&buf->b_hdr->b_freeze_lock);
1159 arc_cksum_equal(arc_buf_t *buf)
1164 mutex_enter(&buf->b_hdr->b_freeze_lock);
1165 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1166 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1167 mutex_exit(&buf->b_hdr->b_freeze_lock);
1173 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1175 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1178 mutex_enter(&buf->b_hdr->b_freeze_lock);
1179 if (buf->b_hdr->b_freeze_cksum != NULL) {
1180 mutex_exit(&buf->b_hdr->b_freeze_lock);
1183 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1184 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1185 buf->b_hdr->b_freeze_cksum);
1186 mutex_exit(&buf->b_hdr->b_freeze_lock);
1189 #endif /* illumos */
1194 typedef struct procctl {
1202 arc_buf_unwatch(arc_buf_t *buf)
1209 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1210 ctl.prwatch.pr_size = 0;
1211 ctl.prwatch.pr_wflags = 0;
1212 result = write(arc_procfd, &ctl, sizeof (ctl));
1213 ASSERT3U(result, ==, sizeof (ctl));
1220 arc_buf_watch(arc_buf_t *buf)
1227 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1228 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1229 ctl.prwatch.pr_wflags = WA_WRITE;
1230 result = write(arc_procfd, &ctl, sizeof (ctl));
1231 ASSERT3U(result, ==, sizeof (ctl));
1235 #endif /* illumos */
1238 arc_buf_thaw(arc_buf_t *buf)
1240 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1241 if (buf->b_hdr->b_state != arc_anon)
1242 panic("modifying non-anon buffer!");
1243 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1244 panic("modifying buffer while i/o in progress!");
1245 arc_cksum_verify(buf);
1248 mutex_enter(&buf->b_hdr->b_freeze_lock);
1249 if (buf->b_hdr->b_freeze_cksum != NULL) {
1250 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1251 buf->b_hdr->b_freeze_cksum = NULL;
1254 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1255 if (buf->b_hdr->b_thawed)
1256 kmem_free(buf->b_hdr->b_thawed, 1);
1257 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1260 mutex_exit(&buf->b_hdr->b_freeze_lock);
1263 arc_buf_unwatch(buf);
1264 #endif /* illumos */
1268 arc_buf_freeze(arc_buf_t *buf)
1270 kmutex_t *hash_lock;
1272 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1275 hash_lock = HDR_LOCK(buf->b_hdr);
1276 mutex_enter(hash_lock);
1278 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1279 buf->b_hdr->b_state == arc_anon);
1280 arc_cksum_compute(buf, B_FALSE);
1281 mutex_exit(hash_lock);
1286 get_buf_info(arc_buf_hdr_t *ab, arc_state_t *state, list_t **list, kmutex_t **lock)
1288 uint64_t buf_hashid = buf_hash(ab->b_spa, &ab->b_dva, ab->b_birth);
1290 if (ab->b_type == ARC_BUFC_METADATA)
1291 buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1293 buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1294 buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1297 *list = &state->arcs_lists[buf_hashid];
1298 *lock = ARCS_LOCK(state, buf_hashid);
1303 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1305 ASSERT(MUTEX_HELD(hash_lock));
1307 if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1308 (ab->b_state != arc_anon)) {
1309 uint64_t delta = ab->b_size * ab->b_datacnt;
1310 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1314 get_buf_info(ab, ab->b_state, &list, &lock);
1315 ASSERT(!MUTEX_HELD(lock));
1317 ASSERT(list_link_active(&ab->b_arc_node));
1318 list_remove(list, ab);
1319 if (GHOST_STATE(ab->b_state)) {
1320 ASSERT0(ab->b_datacnt);
1321 ASSERT3P(ab->b_buf, ==, NULL);
1325 ASSERT3U(*size, >=, delta);
1326 atomic_add_64(size, -delta);
1328 /* remove the prefetch flag if we get a reference */
1329 if (ab->b_flags & ARC_PREFETCH)
1330 ab->b_flags &= ~ARC_PREFETCH;
1335 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1338 arc_state_t *state = ab->b_state;
1340 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1341 ASSERT(!GHOST_STATE(state));
1343 if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1344 (state != arc_anon)) {
1345 uint64_t *size = &state->arcs_lsize[ab->b_type];
1349 get_buf_info(ab, state, &list, &lock);
1350 ASSERT(!MUTEX_HELD(lock));
1352 ASSERT(!list_link_active(&ab->b_arc_node));
1353 list_insert_head(list, ab);
1354 ASSERT(ab->b_datacnt > 0);
1355 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1362 * Move the supplied buffer to the indicated state. The mutex
1363 * for the buffer must be held by the caller.
1366 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1368 arc_state_t *old_state = ab->b_state;
1369 int64_t refcnt = refcount_count(&ab->b_refcnt);
1370 uint64_t from_delta, to_delta;
1374 ASSERT(MUTEX_HELD(hash_lock));
1375 ASSERT3P(new_state, !=, old_state);
1376 ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1377 ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1378 ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1380 from_delta = to_delta = ab->b_datacnt * ab->b_size;
1383 * If this buffer is evictable, transfer it from the
1384 * old state list to the new state list.
1387 if (old_state != arc_anon) {
1389 uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1391 get_buf_info(ab, old_state, &list, &lock);
1392 use_mutex = !MUTEX_HELD(lock);
1396 ASSERT(list_link_active(&ab->b_arc_node));
1397 list_remove(list, ab);
1400 * If prefetching out of the ghost cache,
1401 * we will have a non-zero datacnt.
1403 if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1404 /* ghost elements have a ghost size */
1405 ASSERT(ab->b_buf == NULL);
1406 from_delta = ab->b_size;
1408 ASSERT3U(*size, >=, from_delta);
1409 atomic_add_64(size, -from_delta);
1414 if (new_state != arc_anon) {
1416 uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1418 get_buf_info(ab, new_state, &list, &lock);
1419 use_mutex = !MUTEX_HELD(lock);
1423 list_insert_head(list, ab);
1425 /* ghost elements have a ghost size */
1426 if (GHOST_STATE(new_state)) {
1427 ASSERT(ab->b_datacnt == 0);
1428 ASSERT(ab->b_buf == NULL);
1429 to_delta = ab->b_size;
1431 atomic_add_64(size, to_delta);
1438 ASSERT(!BUF_EMPTY(ab));
1439 if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1440 buf_hash_remove(ab);
1442 /* adjust state sizes */
1444 atomic_add_64(&new_state->arcs_size, to_delta);
1446 ASSERT3U(old_state->arcs_size, >=, from_delta);
1447 atomic_add_64(&old_state->arcs_size, -from_delta);
1449 ab->b_state = new_state;
1451 /* adjust l2arc hdr stats */
1452 if (new_state == arc_l2c_only)
1453 l2arc_hdr_stat_add();
1454 else if (old_state == arc_l2c_only)
1455 l2arc_hdr_stat_remove();
1459 arc_space_consume(uint64_t space, arc_space_type_t type)
1461 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1464 case ARC_SPACE_DATA:
1465 ARCSTAT_INCR(arcstat_data_size, space);
1467 case ARC_SPACE_OTHER:
1468 ARCSTAT_INCR(arcstat_other_size, space);
1470 case ARC_SPACE_HDRS:
1471 ARCSTAT_INCR(arcstat_hdr_size, space);
1473 case ARC_SPACE_L2HDRS:
1474 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1478 atomic_add_64(&arc_meta_used, space);
1479 atomic_add_64(&arc_size, space);
1483 arc_space_return(uint64_t space, arc_space_type_t type)
1485 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1488 case ARC_SPACE_DATA:
1489 ARCSTAT_INCR(arcstat_data_size, -space);
1491 case ARC_SPACE_OTHER:
1492 ARCSTAT_INCR(arcstat_other_size, -space);
1494 case ARC_SPACE_HDRS:
1495 ARCSTAT_INCR(arcstat_hdr_size, -space);
1497 case ARC_SPACE_L2HDRS:
1498 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1502 ASSERT(arc_meta_used >= space);
1503 if (arc_meta_max < arc_meta_used)
1504 arc_meta_max = arc_meta_used;
1505 atomic_add_64(&arc_meta_used, -space);
1506 ASSERT(arc_size >= space);
1507 atomic_add_64(&arc_size, -space);
1511 arc_data_buf_alloc(uint64_t size)
1513 if (arc_evict_needed(ARC_BUFC_DATA))
1514 cv_signal(&arc_reclaim_thr_cv);
1515 atomic_add_64(&arc_size, size);
1516 return (zio_data_buf_alloc(size));
1520 arc_data_buf_free(void *buf, uint64_t size)
1522 zio_data_buf_free(buf, size);
1523 ASSERT(arc_size >= size);
1524 atomic_add_64(&arc_size, -size);
1528 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1533 ASSERT3U(size, >, 0);
1534 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1535 ASSERT(BUF_EMPTY(hdr));
1538 hdr->b_spa = spa_load_guid(spa);
1539 hdr->b_state = arc_anon;
1540 hdr->b_arc_access = 0;
1541 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1544 buf->b_efunc = NULL;
1545 buf->b_private = NULL;
1548 arc_get_data_buf(buf);
1551 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1552 (void) refcount_add(&hdr->b_refcnt, tag);
1557 static char *arc_onloan_tag = "onloan";
1560 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1561 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1562 * buffers must be returned to the arc before they can be used by the DMU or
1566 arc_loan_buf(spa_t *spa, int size)
1570 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1572 atomic_add_64(&arc_loaned_bytes, size);
1577 * Return a loaned arc buffer to the arc.
1580 arc_return_buf(arc_buf_t *buf, void *tag)
1582 arc_buf_hdr_t *hdr = buf->b_hdr;
1584 ASSERT(buf->b_data != NULL);
1585 (void) refcount_add(&hdr->b_refcnt, tag);
1586 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1588 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1591 /* Detach an arc_buf from a dbuf (tag) */
1593 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1597 ASSERT(buf->b_data != NULL);
1599 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1600 (void) refcount_remove(&hdr->b_refcnt, tag);
1601 buf->b_efunc = NULL;
1602 buf->b_private = NULL;
1604 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1608 arc_buf_clone(arc_buf_t *from)
1611 arc_buf_hdr_t *hdr = from->b_hdr;
1612 uint64_t size = hdr->b_size;
1614 ASSERT(hdr->b_state != arc_anon);
1616 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1619 buf->b_efunc = NULL;
1620 buf->b_private = NULL;
1621 buf->b_next = hdr->b_buf;
1623 arc_get_data_buf(buf);
1624 bcopy(from->b_data, buf->b_data, size);
1627 * This buffer already exists in the arc so create a duplicate
1628 * copy for the caller. If the buffer is associated with user data
1629 * then track the size and number of duplicates. These stats will be
1630 * updated as duplicate buffers are created and destroyed.
1632 if (hdr->b_type == ARC_BUFC_DATA) {
1633 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1634 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1636 hdr->b_datacnt += 1;
1641 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1644 kmutex_t *hash_lock;
1647 * Check to see if this buffer is evicted. Callers
1648 * must verify b_data != NULL to know if the add_ref
1651 mutex_enter(&buf->b_evict_lock);
1652 if (buf->b_data == NULL) {
1653 mutex_exit(&buf->b_evict_lock);
1656 hash_lock = HDR_LOCK(buf->b_hdr);
1657 mutex_enter(hash_lock);
1659 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1660 mutex_exit(&buf->b_evict_lock);
1662 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1663 add_reference(hdr, hash_lock, tag);
1664 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1665 arc_access(hdr, hash_lock);
1666 mutex_exit(hash_lock);
1667 ARCSTAT_BUMP(arcstat_hits);
1668 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1669 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1670 data, metadata, hits);
1674 * Free the arc data buffer. If it is an l2arc write in progress,
1675 * the buffer is placed on l2arc_free_on_write to be freed later.
1678 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1680 arc_buf_hdr_t *hdr = buf->b_hdr;
1682 if (HDR_L2_WRITING(hdr)) {
1683 l2arc_data_free_t *df;
1684 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1685 df->l2df_data = buf->b_data;
1686 df->l2df_size = hdr->b_size;
1687 df->l2df_func = free_func;
1688 mutex_enter(&l2arc_free_on_write_mtx);
1689 list_insert_head(l2arc_free_on_write, df);
1690 mutex_exit(&l2arc_free_on_write_mtx);
1691 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1693 free_func(buf->b_data, hdr->b_size);
1698 * Free up buf->b_data and if 'remove' is set, then pull the
1699 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1702 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1706 /* free up data associated with the buf */
1708 arc_state_t *state = buf->b_hdr->b_state;
1709 uint64_t size = buf->b_hdr->b_size;
1710 arc_buf_contents_t type = buf->b_hdr->b_type;
1712 arc_cksum_verify(buf);
1714 arc_buf_unwatch(buf);
1715 #endif /* illumos */
1718 if (type == ARC_BUFC_METADATA) {
1719 arc_buf_data_free(buf, zio_buf_free);
1720 arc_space_return(size, ARC_SPACE_DATA);
1722 ASSERT(type == ARC_BUFC_DATA);
1723 arc_buf_data_free(buf, zio_data_buf_free);
1724 ARCSTAT_INCR(arcstat_data_size, -size);
1725 atomic_add_64(&arc_size, -size);
1728 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1729 uint64_t *cnt = &state->arcs_lsize[type];
1731 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1732 ASSERT(state != arc_anon);
1734 ASSERT3U(*cnt, >=, size);
1735 atomic_add_64(cnt, -size);
1737 ASSERT3U(state->arcs_size, >=, size);
1738 atomic_add_64(&state->arcs_size, -size);
1742 * If we're destroying a duplicate buffer make sure
1743 * that the appropriate statistics are updated.
1745 if (buf->b_hdr->b_datacnt > 1 &&
1746 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1747 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1748 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1750 ASSERT(buf->b_hdr->b_datacnt > 0);
1751 buf->b_hdr->b_datacnt -= 1;
1754 /* only remove the buf if requested */
1758 /* remove the buf from the hdr list */
1759 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1761 *bufp = buf->b_next;
1764 ASSERT(buf->b_efunc == NULL);
1766 /* clean up the buf */
1768 kmem_cache_free(buf_cache, buf);
1772 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1774 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1775 ASSERT3P(hdr->b_state, ==, arc_anon);
1776 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1777 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1779 if (l2hdr != NULL) {
1780 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1782 * To prevent arc_free() and l2arc_evict() from
1783 * attempting to free the same buffer at the same time,
1784 * a FREE_IN_PROGRESS flag is given to arc_free() to
1785 * give it priority. l2arc_evict() can't destroy this
1786 * header while we are waiting on l2arc_buflist_mtx.
1788 * The hdr may be removed from l2ad_buflist before we
1789 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1791 if (!buflist_held) {
1792 mutex_enter(&l2arc_buflist_mtx);
1793 l2hdr = hdr->b_l2hdr;
1796 if (l2hdr != NULL) {
1797 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1799 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1800 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1801 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1802 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1803 -l2hdr->b_asize, 0, 0);
1804 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1805 if (hdr->b_state == arc_l2c_only)
1806 l2arc_hdr_stat_remove();
1807 hdr->b_l2hdr = NULL;
1811 mutex_exit(&l2arc_buflist_mtx);
1814 if (!BUF_EMPTY(hdr)) {
1815 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1816 buf_discard_identity(hdr);
1818 while (hdr->b_buf) {
1819 arc_buf_t *buf = hdr->b_buf;
1822 mutex_enter(&arc_eviction_mtx);
1823 mutex_enter(&buf->b_evict_lock);
1824 ASSERT(buf->b_hdr != NULL);
1825 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1826 hdr->b_buf = buf->b_next;
1827 buf->b_hdr = &arc_eviction_hdr;
1828 buf->b_next = arc_eviction_list;
1829 arc_eviction_list = buf;
1830 mutex_exit(&buf->b_evict_lock);
1831 mutex_exit(&arc_eviction_mtx);
1833 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1836 if (hdr->b_freeze_cksum != NULL) {
1837 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1838 hdr->b_freeze_cksum = NULL;
1840 if (hdr->b_thawed) {
1841 kmem_free(hdr->b_thawed, 1);
1842 hdr->b_thawed = NULL;
1845 ASSERT(!list_link_active(&hdr->b_arc_node));
1846 ASSERT3P(hdr->b_hash_next, ==, NULL);
1847 ASSERT3P(hdr->b_acb, ==, NULL);
1848 kmem_cache_free(hdr_cache, hdr);
1852 arc_buf_free(arc_buf_t *buf, void *tag)
1854 arc_buf_hdr_t *hdr = buf->b_hdr;
1855 int hashed = hdr->b_state != arc_anon;
1857 ASSERT(buf->b_efunc == NULL);
1858 ASSERT(buf->b_data != NULL);
1861 kmutex_t *hash_lock = HDR_LOCK(hdr);
1863 mutex_enter(hash_lock);
1865 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1867 (void) remove_reference(hdr, hash_lock, tag);
1868 if (hdr->b_datacnt > 1) {
1869 arc_buf_destroy(buf, FALSE, TRUE);
1871 ASSERT(buf == hdr->b_buf);
1872 ASSERT(buf->b_efunc == NULL);
1873 hdr->b_flags |= ARC_BUF_AVAILABLE;
1875 mutex_exit(hash_lock);
1876 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1879 * We are in the middle of an async write. Don't destroy
1880 * this buffer unless the write completes before we finish
1881 * decrementing the reference count.
1883 mutex_enter(&arc_eviction_mtx);
1884 (void) remove_reference(hdr, NULL, tag);
1885 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1886 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1887 mutex_exit(&arc_eviction_mtx);
1889 arc_hdr_destroy(hdr);
1891 if (remove_reference(hdr, NULL, tag) > 0)
1892 arc_buf_destroy(buf, FALSE, TRUE);
1894 arc_hdr_destroy(hdr);
1899 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1901 arc_buf_hdr_t *hdr = buf->b_hdr;
1902 kmutex_t *hash_lock = HDR_LOCK(hdr);
1903 boolean_t no_callback = (buf->b_efunc == NULL);
1905 if (hdr->b_state == arc_anon) {
1906 ASSERT(hdr->b_datacnt == 1);
1907 arc_buf_free(buf, tag);
1908 return (no_callback);
1911 mutex_enter(hash_lock);
1913 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1914 ASSERT(hdr->b_state != arc_anon);
1915 ASSERT(buf->b_data != NULL);
1917 (void) remove_reference(hdr, hash_lock, tag);
1918 if (hdr->b_datacnt > 1) {
1920 arc_buf_destroy(buf, FALSE, TRUE);
1921 } else if (no_callback) {
1922 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1923 ASSERT(buf->b_efunc == NULL);
1924 hdr->b_flags |= ARC_BUF_AVAILABLE;
1926 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1927 refcount_is_zero(&hdr->b_refcnt));
1928 mutex_exit(hash_lock);
1929 return (no_callback);
1933 arc_buf_size(arc_buf_t *buf)
1935 return (buf->b_hdr->b_size);
1939 * Called from the DMU to determine if the current buffer should be
1940 * evicted. In order to ensure proper locking, the eviction must be initiated
1941 * from the DMU. Return true if the buffer is associated with user data and
1942 * duplicate buffers still exist.
1945 arc_buf_eviction_needed(arc_buf_t *buf)
1948 boolean_t evict_needed = B_FALSE;
1950 if (zfs_disable_dup_eviction)
1953 mutex_enter(&buf->b_evict_lock);
1957 * We are in arc_do_user_evicts(); let that function
1958 * perform the eviction.
1960 ASSERT(buf->b_data == NULL);
1961 mutex_exit(&buf->b_evict_lock);
1963 } else if (buf->b_data == NULL) {
1965 * We have already been added to the arc eviction list;
1966 * recommend eviction.
1968 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1969 mutex_exit(&buf->b_evict_lock);
1973 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1974 evict_needed = B_TRUE;
1976 mutex_exit(&buf->b_evict_lock);
1977 return (evict_needed);
1981 * Evict buffers from list until we've removed the specified number of
1982 * bytes. Move the removed buffers to the appropriate evict state.
1983 * If the recycle flag is set, then attempt to "recycle" a buffer:
1984 * - look for a buffer to evict that is `bytes' long.
1985 * - return the data block from this buffer rather than freeing it.
1986 * This flag is used by callers that are trying to make space for a
1987 * new buffer in a full arc cache.
1989 * This function makes a "best effort". It skips over any buffers
1990 * it can't get a hash_lock on, and so may not catch all candidates.
1991 * It may also return without evicting as much space as requested.
1994 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1995 arc_buf_contents_t type)
1997 arc_state_t *evicted_state;
1998 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1999 int64_t bytes_remaining;
2000 arc_buf_hdr_t *ab, *ab_prev = NULL;
2001 list_t *evicted_list, *list, *evicted_list_start, *list_start;
2002 kmutex_t *lock, *evicted_lock;
2003 kmutex_t *hash_lock;
2004 boolean_t have_lock;
2005 void *stolen = NULL;
2006 arc_buf_hdr_t marker = { 0 };
2008 static int evict_metadata_offset, evict_data_offset;
2009 int i, idx, offset, list_count, lists;
2011 ASSERT(state == arc_mru || state == arc_mfu);
2013 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2015 if (type == ARC_BUFC_METADATA) {
2017 list_count = ARC_BUFC_NUMMETADATALISTS;
2018 list_start = &state->arcs_lists[0];
2019 evicted_list_start = &evicted_state->arcs_lists[0];
2020 idx = evict_metadata_offset;
2022 offset = ARC_BUFC_NUMMETADATALISTS;
2023 list_start = &state->arcs_lists[offset];
2024 evicted_list_start = &evicted_state->arcs_lists[offset];
2025 list_count = ARC_BUFC_NUMDATALISTS;
2026 idx = evict_data_offset;
2028 bytes_remaining = evicted_state->arcs_lsize[type];
2032 list = &list_start[idx];
2033 evicted_list = &evicted_list_start[idx];
2034 lock = ARCS_LOCK(state, (offset + idx));
2035 evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
2038 mutex_enter(evicted_lock);
2040 for (ab = list_tail(list); ab; ab = ab_prev) {
2041 ab_prev = list_prev(list, ab);
2042 bytes_remaining -= (ab->b_size * ab->b_datacnt);
2043 /* prefetch buffers have a minimum lifespan */
2044 if (HDR_IO_IN_PROGRESS(ab) ||
2045 (spa && ab->b_spa != spa) ||
2046 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
2047 ddi_get_lbolt() - ab->b_arc_access <
2048 arc_min_prefetch_lifespan)) {
2052 /* "lookahead" for better eviction candidate */
2053 if (recycle && ab->b_size != bytes &&
2054 ab_prev && ab_prev->b_size == bytes)
2057 /* ignore markers */
2062 * It may take a long time to evict all the bufs requested.
2063 * To avoid blocking all arc activity, periodically drop
2064 * the arcs_mtx and give other threads a chance to run
2065 * before reacquiring the lock.
2067 * If we are looking for a buffer to recycle, we are in
2068 * the hot code path, so don't sleep.
2070 if (!recycle && count++ > arc_evict_iterations) {
2071 list_insert_after(list, ab, &marker);
2072 mutex_exit(evicted_lock);
2074 kpreempt(KPREEMPT_SYNC);
2076 mutex_enter(evicted_lock);
2077 ab_prev = list_prev(list, &marker);
2078 list_remove(list, &marker);
2083 hash_lock = HDR_LOCK(ab);
2084 have_lock = MUTEX_HELD(hash_lock);
2085 if (have_lock || mutex_tryenter(hash_lock)) {
2086 ASSERT0(refcount_count(&ab->b_refcnt));
2087 ASSERT(ab->b_datacnt > 0);
2089 arc_buf_t *buf = ab->b_buf;
2090 if (!mutex_tryenter(&buf->b_evict_lock)) {
2095 bytes_evicted += ab->b_size;
2096 if (recycle && ab->b_type == type &&
2097 ab->b_size == bytes &&
2098 !HDR_L2_WRITING(ab)) {
2099 stolen = buf->b_data;
2104 mutex_enter(&arc_eviction_mtx);
2105 arc_buf_destroy(buf,
2106 buf->b_data == stolen, FALSE);
2107 ab->b_buf = buf->b_next;
2108 buf->b_hdr = &arc_eviction_hdr;
2109 buf->b_next = arc_eviction_list;
2110 arc_eviction_list = buf;
2111 mutex_exit(&arc_eviction_mtx);
2112 mutex_exit(&buf->b_evict_lock);
2114 mutex_exit(&buf->b_evict_lock);
2115 arc_buf_destroy(buf,
2116 buf->b_data == stolen, TRUE);
2121 ARCSTAT_INCR(arcstat_evict_l2_cached,
2124 if (l2arc_write_eligible(ab->b_spa, ab)) {
2125 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2129 arcstat_evict_l2_ineligible,
2134 if (ab->b_datacnt == 0) {
2135 arc_change_state(evicted_state, ab, hash_lock);
2136 ASSERT(HDR_IN_HASH_TABLE(ab));
2137 ab->b_flags |= ARC_IN_HASH_TABLE;
2138 ab->b_flags &= ~ARC_BUF_AVAILABLE;
2139 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2142 mutex_exit(hash_lock);
2143 if (bytes >= 0 && bytes_evicted >= bytes)
2145 if (bytes_remaining > 0) {
2146 mutex_exit(evicted_lock);
2148 idx = ((idx + 1) & (list_count - 1));
2157 mutex_exit(evicted_lock);
2160 idx = ((idx + 1) & (list_count - 1));
2163 if (bytes_evicted < bytes) {
2164 if (lists < list_count)
2167 dprintf("only evicted %lld bytes from %x",
2168 (longlong_t)bytes_evicted, state);
2170 if (type == ARC_BUFC_METADATA)
2171 evict_metadata_offset = idx;
2173 evict_data_offset = idx;
2176 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2179 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2182 * Note: we have just evicted some data into the ghost state,
2183 * potentially putting the ghost size over the desired size. Rather
2184 * that evicting from the ghost list in this hot code path, leave
2185 * this chore to the arc_reclaim_thread().
2189 ARCSTAT_BUMP(arcstat_stolen);
2194 * Remove buffers from list until we've removed the specified number of
2195 * bytes. Destroy the buffers that are removed.
2198 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2200 arc_buf_hdr_t *ab, *ab_prev;
2201 arc_buf_hdr_t marker = { 0 };
2202 list_t *list, *list_start;
2203 kmutex_t *hash_lock, *lock;
2204 uint64_t bytes_deleted = 0;
2205 uint64_t bufs_skipped = 0;
2207 static int evict_offset;
2208 int list_count, idx = evict_offset;
2209 int offset, lists = 0;
2211 ASSERT(GHOST_STATE(state));
2214 * data lists come after metadata lists
2216 list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2217 list_count = ARC_BUFC_NUMDATALISTS;
2218 offset = ARC_BUFC_NUMMETADATALISTS;
2221 list = &list_start[idx];
2222 lock = ARCS_LOCK(state, idx + offset);
2225 for (ab = list_tail(list); ab; ab = ab_prev) {
2226 ab_prev = list_prev(list, ab);
2227 if (ab->b_type > ARC_BUFC_NUMTYPES)
2228 panic("invalid ab=%p", (void *)ab);
2229 if (spa && ab->b_spa != spa)
2232 /* ignore markers */
2236 hash_lock = HDR_LOCK(ab);
2237 /* caller may be trying to modify this buffer, skip it */
2238 if (MUTEX_HELD(hash_lock))
2242 * It may take a long time to evict all the bufs requested.
2243 * To avoid blocking all arc activity, periodically drop
2244 * the arcs_mtx and give other threads a chance to run
2245 * before reacquiring the lock.
2247 if (count++ > arc_evict_iterations) {
2248 list_insert_after(list, ab, &marker);
2250 kpreempt(KPREEMPT_SYNC);
2252 ab_prev = list_prev(list, &marker);
2253 list_remove(list, &marker);
2257 if (mutex_tryenter(hash_lock)) {
2258 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2259 ASSERT(ab->b_buf == NULL);
2260 ARCSTAT_BUMP(arcstat_deleted);
2261 bytes_deleted += ab->b_size;
2263 if (ab->b_l2hdr != NULL) {
2265 * This buffer is cached on the 2nd Level ARC;
2266 * don't destroy the header.
2268 arc_change_state(arc_l2c_only, ab, hash_lock);
2269 mutex_exit(hash_lock);
2271 arc_change_state(arc_anon, ab, hash_lock);
2272 mutex_exit(hash_lock);
2273 arc_hdr_destroy(ab);
2276 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2277 if (bytes >= 0 && bytes_deleted >= bytes)
2279 } else if (bytes < 0) {
2281 * Insert a list marker and then wait for the
2282 * hash lock to become available. Once its
2283 * available, restart from where we left off.
2285 list_insert_after(list, ab, &marker);
2287 mutex_enter(hash_lock);
2288 mutex_exit(hash_lock);
2290 ab_prev = list_prev(list, &marker);
2291 list_remove(list, &marker);
2298 idx = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2301 if (lists < list_count)
2305 if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2306 (bytes < 0 || bytes_deleted < bytes)) {
2307 list_start = &state->arcs_lists[0];
2308 list_count = ARC_BUFC_NUMMETADATALISTS;
2314 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2318 if (bytes_deleted < bytes)
2319 dprintf("only deleted %lld bytes from %p",
2320 (longlong_t)bytes_deleted, state);
2326 int64_t adjustment, delta;
2332 adjustment = MIN((int64_t)(arc_size - arc_c),
2333 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2336 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2337 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2338 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2339 adjustment -= delta;
2342 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2343 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2344 (void) arc_evict(arc_mru, 0, delta, FALSE,
2352 adjustment = arc_size - arc_c;
2354 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2355 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2356 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2357 adjustment -= delta;
2360 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2361 int64_t delta = MIN(adjustment,
2362 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2363 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2368 * Adjust ghost lists
2371 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2373 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2374 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2375 arc_evict_ghost(arc_mru_ghost, 0, delta);
2379 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2381 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2382 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2383 arc_evict_ghost(arc_mfu_ghost, 0, delta);
2388 arc_do_user_evicts(void)
2390 static arc_buf_t *tmp_arc_eviction_list;
2393 * Move list over to avoid LOR
2396 mutex_enter(&arc_eviction_mtx);
2397 tmp_arc_eviction_list = arc_eviction_list;
2398 arc_eviction_list = NULL;
2399 mutex_exit(&arc_eviction_mtx);
2401 while (tmp_arc_eviction_list != NULL) {
2402 arc_buf_t *buf = tmp_arc_eviction_list;
2403 tmp_arc_eviction_list = buf->b_next;
2404 mutex_enter(&buf->b_evict_lock);
2406 mutex_exit(&buf->b_evict_lock);
2408 if (buf->b_efunc != NULL)
2409 VERIFY0(buf->b_efunc(buf->b_private));
2411 buf->b_efunc = NULL;
2412 buf->b_private = NULL;
2413 kmem_cache_free(buf_cache, buf);
2416 if (arc_eviction_list != NULL)
2421 * Flush all *evictable* data from the cache for the given spa.
2422 * NOTE: this will not touch "active" (i.e. referenced) data.
2425 arc_flush(spa_t *spa)
2430 guid = spa_load_guid(spa);
2432 while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2433 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2437 while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2438 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2442 while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2443 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2447 while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2448 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2453 arc_evict_ghost(arc_mru_ghost, guid, -1);
2454 arc_evict_ghost(arc_mfu_ghost, guid, -1);
2456 mutex_enter(&arc_reclaim_thr_lock);
2457 arc_do_user_evicts();
2458 mutex_exit(&arc_reclaim_thr_lock);
2459 ASSERT(spa || arc_eviction_list == NULL);
2466 if (arc_c > arc_c_min) {
2469 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
2470 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
2472 to_free = arc_c >> arc_shrink_shift;
2474 to_free = arc_c >> arc_shrink_shift;
2476 if (arc_c > arc_c_min + to_free)
2477 atomic_add_64(&arc_c, -to_free);
2481 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2482 if (arc_c > arc_size)
2483 arc_c = MAX(arc_size, arc_c_min);
2485 arc_p = (arc_c >> 1);
2487 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
2490 ASSERT(arc_c >= arc_c_min);
2491 ASSERT((int64_t)arc_p >= 0);
2494 if (arc_size > arc_c) {
2495 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
2501 static int needfree = 0;
2504 arc_reclaim_needed(void)
2510 DTRACE_PROBE(arc__reclaim_needfree);
2515 * Cooperate with pagedaemon when it's time for it to scan
2516 * and reclaim some pages.
2518 if (freemem < zfs_arc_free_target) {
2519 DTRACE_PROBE2(arc__reclaim_freemem, uint64_t,
2520 freemem, uint64_t, zfs_arc_free_target);
2526 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2531 * check that we're out of range of the pageout scanner. It starts to
2532 * schedule paging if freemem is less than lotsfree and needfree.
2533 * lotsfree is the high-water mark for pageout, and needfree is the
2534 * number of needed free pages. We add extra pages here to make sure
2535 * the scanner doesn't start up while we're freeing memory.
2537 if (freemem < lotsfree + needfree + extra)
2541 * check to make sure that swapfs has enough space so that anon
2542 * reservations can still succeed. anon_resvmem() checks that the
2543 * availrmem is greater than swapfs_minfree, and the number of reserved
2544 * swap pages. We also add a bit of extra here just to prevent
2545 * circumstances from getting really dire.
2547 if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2551 * Check that we have enough availrmem that memory locking (e.g., via
2552 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
2553 * stores the number of pages that cannot be locked; when availrmem
2554 * drops below pages_pp_maximum, page locking mechanisms such as
2555 * page_pp_lock() will fail.)
2557 if (availrmem <= pages_pp_maximum)
2561 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
2563 * If we're on an i386 platform, it's possible that we'll exhaust the
2564 * kernel heap space before we ever run out of available physical
2565 * memory. Most checks of the size of the heap_area compare against
2566 * tune.t_minarmem, which is the minimum available real memory that we
2567 * can have in the system. However, this is generally fixed at 25 pages
2568 * which is so low that it's useless. In this comparison, we seek to
2569 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2570 * heap is allocated. (Or, in the calculation, if less than 1/4th is
2573 if (vmem_size(heap_arena, VMEM_FREE) <
2574 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2)) {
2575 DTRACE_PROBE2(arc__reclaim_used, uint64_t,
2576 vmem_size(heap_arena, VMEM_FREE), uint64_t,
2577 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2);
2583 * If zio data pages are being allocated out of a separate heap segment,
2584 * then enforce that the size of available vmem for this arena remains
2585 * above about 1/16th free.
2587 * Note: The 1/16th arena free requirement was put in place
2588 * to aggressively evict memory from the arc in order to avoid
2589 * memory fragmentation issues.
2591 if (zio_arena != NULL &&
2592 vmem_size(zio_arena, VMEM_FREE) <
2593 (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2597 if (spa_get_random(100) == 0)
2599 #endif /* _KERNEL */
2600 DTRACE_PROBE(arc__reclaim_no);
2605 extern kmem_cache_t *zio_buf_cache[];
2606 extern kmem_cache_t *zio_data_buf_cache[];
2608 static void __noinline
2609 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2612 kmem_cache_t *prev_cache = NULL;
2613 kmem_cache_t *prev_data_cache = NULL;
2615 DTRACE_PROBE(arc__kmem_reap_start);
2617 if (arc_meta_used >= arc_meta_limit) {
2619 * We are exceeding our meta-data cache limit.
2620 * Purge some DNLC entries to release holds on meta-data.
2622 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2626 * Reclaim unused memory from all kmem caches.
2633 * An aggressive reclamation will shrink the cache size as well as
2634 * reap free buffers from the arc kmem caches.
2636 if (strat == ARC_RECLAIM_AGGR)
2639 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2640 if (zio_buf_cache[i] != prev_cache) {
2641 prev_cache = zio_buf_cache[i];
2642 kmem_cache_reap_now(zio_buf_cache[i]);
2644 if (zio_data_buf_cache[i] != prev_data_cache) {
2645 prev_data_cache = zio_data_buf_cache[i];
2646 kmem_cache_reap_now(zio_data_buf_cache[i]);
2649 kmem_cache_reap_now(buf_cache);
2650 kmem_cache_reap_now(hdr_cache);
2654 * Ask the vmem arena to reclaim unused memory from its
2657 if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2658 vmem_qcache_reap(zio_arena);
2660 DTRACE_PROBE(arc__kmem_reap_end);
2664 arc_reclaim_thread(void *dummy __unused)
2666 clock_t growtime = 0;
2667 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2670 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2672 mutex_enter(&arc_reclaim_thr_lock);
2673 while (arc_thread_exit == 0) {
2674 if (arc_reclaim_needed()) {
2677 if (last_reclaim == ARC_RECLAIM_CONS) {
2678 DTRACE_PROBE(arc__reclaim_aggr_no_grow);
2679 last_reclaim = ARC_RECLAIM_AGGR;
2681 last_reclaim = ARC_RECLAIM_CONS;
2685 last_reclaim = ARC_RECLAIM_AGGR;
2686 DTRACE_PROBE(arc__reclaim_aggr);
2690 /* reset the growth delay for every reclaim */
2691 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2693 if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2695 * If needfree is TRUE our vm_lowmem hook
2696 * was called and in that case we must free some
2697 * memory, so switch to aggressive mode.
2700 last_reclaim = ARC_RECLAIM_AGGR;
2702 arc_kmem_reap_now(last_reclaim);
2705 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2706 arc_no_grow = FALSE;
2711 if (arc_eviction_list != NULL)
2712 arc_do_user_evicts();
2721 /* block until needed, or one second, whichever is shorter */
2722 CALLB_CPR_SAFE_BEGIN(&cpr);
2723 (void) cv_timedwait(&arc_reclaim_thr_cv,
2724 &arc_reclaim_thr_lock, hz);
2725 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2728 arc_thread_exit = 0;
2729 cv_broadcast(&arc_reclaim_thr_cv);
2730 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2735 * Adapt arc info given the number of bytes we are trying to add and
2736 * the state that we are comming from. This function is only called
2737 * when we are adding new content to the cache.
2740 arc_adapt(int bytes, arc_state_t *state)
2743 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2745 if (state == arc_l2c_only)
2750 * Adapt the target size of the MRU list:
2751 * - if we just hit in the MRU ghost list, then increase
2752 * the target size of the MRU list.
2753 * - if we just hit in the MFU ghost list, then increase
2754 * the target size of the MFU list by decreasing the
2755 * target size of the MRU list.
2757 if (state == arc_mru_ghost) {
2758 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2759 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2760 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2762 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2763 } else if (state == arc_mfu_ghost) {
2766 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2767 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2768 mult = MIN(mult, 10);
2770 delta = MIN(bytes * mult, arc_p);
2771 arc_p = MAX(arc_p_min, arc_p - delta);
2773 ASSERT((int64_t)arc_p >= 0);
2775 if (arc_reclaim_needed()) {
2776 cv_signal(&arc_reclaim_thr_cv);
2783 if (arc_c >= arc_c_max)
2787 * If we're within (2 * maxblocksize) bytes of the target
2788 * cache size, increment the target cache size
2790 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2791 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
2792 atomic_add_64(&arc_c, (int64_t)bytes);
2793 if (arc_c > arc_c_max)
2795 else if (state == arc_anon)
2796 atomic_add_64(&arc_p, (int64_t)bytes);
2800 ASSERT((int64_t)arc_p >= 0);
2804 * Check if the cache has reached its limits and eviction is required
2808 arc_evict_needed(arc_buf_contents_t type)
2810 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2813 if (arc_reclaim_needed())
2816 return (arc_size > arc_c);
2820 * The buffer, supplied as the first argument, needs a data block.
2821 * So, if we are at cache max, determine which cache should be victimized.
2822 * We have the following cases:
2824 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2825 * In this situation if we're out of space, but the resident size of the MFU is
2826 * under the limit, victimize the MFU cache to satisfy this insertion request.
2828 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2829 * Here, we've used up all of the available space for the MRU, so we need to
2830 * evict from our own cache instead. Evict from the set of resident MRU
2833 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2834 * c minus p represents the MFU space in the cache, since p is the size of the
2835 * cache that is dedicated to the MRU. In this situation there's still space on
2836 * the MFU side, so the MRU side needs to be victimized.
2838 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2839 * MFU's resident set is consuming more space than it has been allotted. In
2840 * this situation, we must victimize our own cache, the MFU, for this insertion.
2843 arc_get_data_buf(arc_buf_t *buf)
2845 arc_state_t *state = buf->b_hdr->b_state;
2846 uint64_t size = buf->b_hdr->b_size;
2847 arc_buf_contents_t type = buf->b_hdr->b_type;
2849 arc_adapt(size, state);
2852 * We have not yet reached cache maximum size,
2853 * just allocate a new buffer.
2855 if (!arc_evict_needed(type)) {
2856 if (type == ARC_BUFC_METADATA) {
2857 buf->b_data = zio_buf_alloc(size);
2858 arc_space_consume(size, ARC_SPACE_DATA);
2860 ASSERT(type == ARC_BUFC_DATA);
2861 buf->b_data = zio_data_buf_alloc(size);
2862 ARCSTAT_INCR(arcstat_data_size, size);
2863 atomic_add_64(&arc_size, size);
2869 * If we are prefetching from the mfu ghost list, this buffer
2870 * will end up on the mru list; so steal space from there.
2872 if (state == arc_mfu_ghost)
2873 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2874 else if (state == arc_mru_ghost)
2877 if (state == arc_mru || state == arc_anon) {
2878 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2879 state = (arc_mfu->arcs_lsize[type] >= size &&
2880 arc_p > mru_used) ? arc_mfu : arc_mru;
2883 uint64_t mfu_space = arc_c - arc_p;
2884 state = (arc_mru->arcs_lsize[type] >= size &&
2885 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2887 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2888 if (type == ARC_BUFC_METADATA) {
2889 buf->b_data = zio_buf_alloc(size);
2890 arc_space_consume(size, ARC_SPACE_DATA);
2892 ASSERT(type == ARC_BUFC_DATA);
2893 buf->b_data = zio_data_buf_alloc(size);
2894 ARCSTAT_INCR(arcstat_data_size, size);
2895 atomic_add_64(&arc_size, size);
2897 ARCSTAT_BUMP(arcstat_recycle_miss);
2899 ASSERT(buf->b_data != NULL);
2902 * Update the state size. Note that ghost states have a
2903 * "ghost size" and so don't need to be updated.
2905 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2906 arc_buf_hdr_t *hdr = buf->b_hdr;
2908 atomic_add_64(&hdr->b_state->arcs_size, size);
2909 if (list_link_active(&hdr->b_arc_node)) {
2910 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2911 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2914 * If we are growing the cache, and we are adding anonymous
2915 * data, and we have outgrown arc_p, update arc_p
2917 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2918 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2919 arc_p = MIN(arc_c, arc_p + size);
2921 ARCSTAT_BUMP(arcstat_allocated);
2925 * This routine is called whenever a buffer is accessed.
2926 * NOTE: the hash lock is dropped in this function.
2929 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2933 ASSERT(MUTEX_HELD(hash_lock));
2935 if (buf->b_state == arc_anon) {
2937 * This buffer is not in the cache, and does not
2938 * appear in our "ghost" list. Add the new buffer
2942 ASSERT(buf->b_arc_access == 0);
2943 buf->b_arc_access = ddi_get_lbolt();
2944 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2945 arc_change_state(arc_mru, buf, hash_lock);
2947 } else if (buf->b_state == arc_mru) {
2948 now = ddi_get_lbolt();
2951 * If this buffer is here because of a prefetch, then either:
2952 * - clear the flag if this is a "referencing" read
2953 * (any subsequent access will bump this into the MFU state).
2955 * - move the buffer to the head of the list if this is
2956 * another prefetch (to make it less likely to be evicted).
2958 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2959 if (refcount_count(&buf->b_refcnt) == 0) {
2960 ASSERT(list_link_active(&buf->b_arc_node));
2962 buf->b_flags &= ~ARC_PREFETCH;
2963 ARCSTAT_BUMP(arcstat_mru_hits);
2965 buf->b_arc_access = now;
2970 * This buffer has been "accessed" only once so far,
2971 * but it is still in the cache. Move it to the MFU
2974 if (now > buf->b_arc_access + ARC_MINTIME) {
2976 * More than 125ms have passed since we
2977 * instantiated this buffer. Move it to the
2978 * most frequently used state.
2980 buf->b_arc_access = now;
2981 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2982 arc_change_state(arc_mfu, buf, hash_lock);
2984 ARCSTAT_BUMP(arcstat_mru_hits);
2985 } else if (buf->b_state == arc_mru_ghost) {
2986 arc_state_t *new_state;
2988 * This buffer has been "accessed" recently, but
2989 * was evicted from the cache. Move it to the
2993 if (buf->b_flags & ARC_PREFETCH) {
2994 new_state = arc_mru;
2995 if (refcount_count(&buf->b_refcnt) > 0)
2996 buf->b_flags &= ~ARC_PREFETCH;
2997 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2999 new_state = arc_mfu;
3000 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
3003 buf->b_arc_access = ddi_get_lbolt();
3004 arc_change_state(new_state, buf, hash_lock);
3006 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3007 } else if (buf->b_state == arc_mfu) {
3009 * This buffer has been accessed more than once and is
3010 * still in the cache. Keep it in the MFU state.
3012 * NOTE: an add_reference() that occurred when we did
3013 * the arc_read() will have kicked this off the list.
3014 * If it was a prefetch, we will explicitly move it to
3015 * the head of the list now.
3017 if ((buf->b_flags & ARC_PREFETCH) != 0) {
3018 ASSERT(refcount_count(&buf->b_refcnt) == 0);
3019 ASSERT(list_link_active(&buf->b_arc_node));
3021 ARCSTAT_BUMP(arcstat_mfu_hits);
3022 buf->b_arc_access = ddi_get_lbolt();
3023 } else if (buf->b_state == arc_mfu_ghost) {
3024 arc_state_t *new_state = arc_mfu;
3026 * This buffer has been accessed more than once but has
3027 * been evicted from the cache. Move it back to the
3031 if (buf->b_flags & ARC_PREFETCH) {
3033 * This is a prefetch access...
3034 * move this block back to the MRU state.
3036 ASSERT0(refcount_count(&buf->b_refcnt));
3037 new_state = arc_mru;
3040 buf->b_arc_access = ddi_get_lbolt();
3041 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
3042 arc_change_state(new_state, buf, hash_lock);
3044 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3045 } else if (buf->b_state == arc_l2c_only) {
3047 * This buffer is on the 2nd Level ARC.
3050 buf->b_arc_access = ddi_get_lbolt();
3051 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
3052 arc_change_state(arc_mfu, buf, hash_lock);
3054 ASSERT(!"invalid arc state");
3058 /* a generic arc_done_func_t which you can use */
3061 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3063 if (zio == NULL || zio->io_error == 0)
3064 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3065 VERIFY(arc_buf_remove_ref(buf, arg));
3068 /* a generic arc_done_func_t */
3070 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3072 arc_buf_t **bufp = arg;
3073 if (zio && zio->io_error) {
3074 VERIFY(arc_buf_remove_ref(buf, arg));
3078 ASSERT(buf->b_data);
3083 arc_read_done(zio_t *zio)
3087 arc_buf_t *abuf; /* buffer we're assigning to callback */
3088 kmutex_t *hash_lock = NULL;
3089 arc_callback_t *callback_list, *acb;
3090 int freeable = FALSE;
3092 buf = zio->io_private;
3096 * The hdr was inserted into hash-table and removed from lists
3097 * prior to starting I/O. We should find this header, since
3098 * it's in the hash table, and it should be legit since it's
3099 * not possible to evict it during the I/O. The only possible
3100 * reason for it not to be found is if we were freed during the
3103 if (HDR_IN_HASH_TABLE(hdr)) {
3104 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3105 ASSERT3U(hdr->b_dva.dva_word[0], ==,
3106 BP_IDENTITY(zio->io_bp)->dva_word[0]);
3107 ASSERT3U(hdr->b_dva.dva_word[1], ==,
3108 BP_IDENTITY(zio->io_bp)->dva_word[1]);
3110 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3113 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3114 hash_lock == NULL) ||
3116 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3117 (found == hdr && HDR_L2_READING(hdr)));
3120 hdr->b_flags &= ~ARC_L2_EVICTED;
3121 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
3122 hdr->b_flags &= ~ARC_L2CACHE;
3124 /* byteswap if necessary */
3125 callback_list = hdr->b_acb;
3126 ASSERT(callback_list != NULL);
3127 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3128 dmu_object_byteswap_t bswap =
3129 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3130 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3131 byteswap_uint64_array :
3132 dmu_ot_byteswap[bswap].ob_func;
3133 func(buf->b_data, hdr->b_size);
3136 arc_cksum_compute(buf, B_FALSE);
3139 #endif /* illumos */
3141 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3143 * Only call arc_access on anonymous buffers. This is because
3144 * if we've issued an I/O for an evicted buffer, we've already
3145 * called arc_access (to prevent any simultaneous readers from
3146 * getting confused).
3148 arc_access(hdr, hash_lock);
3151 /* create copies of the data buffer for the callers */
3153 for (acb = callback_list; acb; acb = acb->acb_next) {
3154 if (acb->acb_done) {
3156 ARCSTAT_BUMP(arcstat_duplicate_reads);
3157 abuf = arc_buf_clone(buf);
3159 acb->acb_buf = abuf;
3164 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3165 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3167 ASSERT(buf->b_efunc == NULL);
3168 ASSERT(hdr->b_datacnt == 1);
3169 hdr->b_flags |= ARC_BUF_AVAILABLE;
3172 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3174 if (zio->io_error != 0) {
3175 hdr->b_flags |= ARC_IO_ERROR;
3176 if (hdr->b_state != arc_anon)
3177 arc_change_state(arc_anon, hdr, hash_lock);
3178 if (HDR_IN_HASH_TABLE(hdr))
3179 buf_hash_remove(hdr);
3180 freeable = refcount_is_zero(&hdr->b_refcnt);
3184 * Broadcast before we drop the hash_lock to avoid the possibility
3185 * that the hdr (and hence the cv) might be freed before we get to
3186 * the cv_broadcast().
3188 cv_broadcast(&hdr->b_cv);
3191 mutex_exit(hash_lock);
3194 * This block was freed while we waited for the read to
3195 * complete. It has been removed from the hash table and
3196 * moved to the anonymous state (so that it won't show up
3199 ASSERT3P(hdr->b_state, ==, arc_anon);
3200 freeable = refcount_is_zero(&hdr->b_refcnt);
3203 /* execute each callback and free its structure */
3204 while ((acb = callback_list) != NULL) {
3206 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3208 if (acb->acb_zio_dummy != NULL) {
3209 acb->acb_zio_dummy->io_error = zio->io_error;
3210 zio_nowait(acb->acb_zio_dummy);
3213 callback_list = acb->acb_next;
3214 kmem_free(acb, sizeof (arc_callback_t));
3218 arc_hdr_destroy(hdr);
3222 * "Read" the block block at the specified DVA (in bp) via the
3223 * cache. If the block is found in the cache, invoke the provided
3224 * callback immediately and return. Note that the `zio' parameter
3225 * in the callback will be NULL in this case, since no IO was
3226 * required. If the block is not in the cache pass the read request
3227 * on to the spa with a substitute callback function, so that the
3228 * requested block will be added to the cache.
3230 * If a read request arrives for a block that has a read in-progress,
3231 * either wait for the in-progress read to complete (and return the
3232 * results); or, if this is a read with a "done" func, add a record
3233 * to the read to invoke the "done" func when the read completes,
3234 * and return; or just return.
3236 * arc_read_done() will invoke all the requested "done" functions
3237 * for readers of this block.
3240 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3241 void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
3242 const zbookmark_phys_t *zb)
3244 arc_buf_hdr_t *hdr = NULL;
3245 arc_buf_t *buf = NULL;
3246 kmutex_t *hash_lock = NULL;
3248 uint64_t guid = spa_load_guid(spa);
3250 ASSERT(!BP_IS_EMBEDDED(bp) ||
3251 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3254 if (!BP_IS_EMBEDDED(bp)) {
3256 * Embedded BP's have no DVA and require no I/O to "read".
3257 * Create an anonymous arc buf to back it.
3259 hdr = buf_hash_find(guid, bp, &hash_lock);
3262 if (hdr != NULL && hdr->b_datacnt > 0) {
3264 *arc_flags |= ARC_CACHED;
3266 if (HDR_IO_IN_PROGRESS(hdr)) {
3268 if (*arc_flags & ARC_WAIT) {
3269 cv_wait(&hdr->b_cv, hash_lock);
3270 mutex_exit(hash_lock);
3273 ASSERT(*arc_flags & ARC_NOWAIT);
3276 arc_callback_t *acb = NULL;
3278 acb = kmem_zalloc(sizeof (arc_callback_t),
3280 acb->acb_done = done;
3281 acb->acb_private = private;
3283 acb->acb_zio_dummy = zio_null(pio,
3284 spa, NULL, NULL, NULL, zio_flags);
3286 ASSERT(acb->acb_done != NULL);
3287 acb->acb_next = hdr->b_acb;
3289 add_reference(hdr, hash_lock, private);
3290 mutex_exit(hash_lock);
3293 mutex_exit(hash_lock);
3297 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3300 add_reference(hdr, hash_lock, private);
3302 * If this block is already in use, create a new
3303 * copy of the data so that we will be guaranteed
3304 * that arc_release() will always succeed.
3308 ASSERT(buf->b_data);
3309 if (HDR_BUF_AVAILABLE(hdr)) {
3310 ASSERT(buf->b_efunc == NULL);
3311 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3313 buf = arc_buf_clone(buf);
3316 } else if (*arc_flags & ARC_PREFETCH &&
3317 refcount_count(&hdr->b_refcnt) == 0) {
3318 hdr->b_flags |= ARC_PREFETCH;
3320 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3321 arc_access(hdr, hash_lock);
3322 if (*arc_flags & ARC_L2CACHE)
3323 hdr->b_flags |= ARC_L2CACHE;
3324 if (*arc_flags & ARC_L2COMPRESS)
3325 hdr->b_flags |= ARC_L2COMPRESS;
3326 mutex_exit(hash_lock);
3327 ARCSTAT_BUMP(arcstat_hits);
3328 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3329 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3330 data, metadata, hits);
3333 done(NULL, buf, private);
3335 uint64_t size = BP_GET_LSIZE(bp);
3336 arc_callback_t *acb;
3339 boolean_t devw = B_FALSE;
3340 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3341 uint64_t b_asize = 0;
3344 /* this block is not in the cache */
3345 arc_buf_hdr_t *exists = NULL;
3346 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3347 buf = arc_buf_alloc(spa, size, private, type);
3349 if (!BP_IS_EMBEDDED(bp)) {
3350 hdr->b_dva = *BP_IDENTITY(bp);
3351 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3352 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3353 exists = buf_hash_insert(hdr, &hash_lock);
3355 if (exists != NULL) {
3356 /* somebody beat us to the hash insert */
3357 mutex_exit(hash_lock);
3358 buf_discard_identity(hdr);
3359 (void) arc_buf_remove_ref(buf, private);
3360 goto top; /* restart the IO request */
3362 /* if this is a prefetch, we don't have a reference */
3363 if (*arc_flags & ARC_PREFETCH) {
3364 (void) remove_reference(hdr, hash_lock,
3366 hdr->b_flags |= ARC_PREFETCH;
3368 if (*arc_flags & ARC_L2CACHE)
3369 hdr->b_flags |= ARC_L2CACHE;
3370 if (*arc_flags & ARC_L2COMPRESS)
3371 hdr->b_flags |= ARC_L2COMPRESS;
3372 if (BP_GET_LEVEL(bp) > 0)
3373 hdr->b_flags |= ARC_INDIRECT;
3375 /* this block is in the ghost cache */
3376 ASSERT(GHOST_STATE(hdr->b_state));
3377 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3378 ASSERT0(refcount_count(&hdr->b_refcnt));
3379 ASSERT(hdr->b_buf == NULL);
3381 /* if this is a prefetch, we don't have a reference */
3382 if (*arc_flags & ARC_PREFETCH)
3383 hdr->b_flags |= ARC_PREFETCH;
3385 add_reference(hdr, hash_lock, private);
3386 if (*arc_flags & ARC_L2CACHE)
3387 hdr->b_flags |= ARC_L2CACHE;
3388 if (*arc_flags & ARC_L2COMPRESS)
3389 hdr->b_flags |= ARC_L2COMPRESS;
3390 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3393 buf->b_efunc = NULL;
3394 buf->b_private = NULL;
3397 ASSERT(hdr->b_datacnt == 0);
3399 arc_get_data_buf(buf);
3400 arc_access(hdr, hash_lock);
3403 ASSERT(!GHOST_STATE(hdr->b_state));
3405 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3406 acb->acb_done = done;
3407 acb->acb_private = private;
3409 ASSERT(hdr->b_acb == NULL);
3411 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3413 if (hdr->b_l2hdr != NULL &&
3414 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3415 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3416 addr = hdr->b_l2hdr->b_daddr;
3417 b_compress = hdr->b_l2hdr->b_compress;
3418 b_asize = hdr->b_l2hdr->b_asize;
3420 * Lock out device removal.
3422 if (vdev_is_dead(vd) ||
3423 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3427 if (hash_lock != NULL)
3428 mutex_exit(hash_lock);
3431 * At this point, we have a level 1 cache miss. Try again in
3432 * L2ARC if possible.
3434 ASSERT3U(hdr->b_size, ==, size);
3435 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3436 uint64_t, size, zbookmark_phys_t *, zb);
3437 ARCSTAT_BUMP(arcstat_misses);
3438 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3439 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3440 data, metadata, misses);
3442 curthread->td_ru.ru_inblock++;
3445 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3447 * Read from the L2ARC if the following are true:
3448 * 1. The L2ARC vdev was previously cached.
3449 * 2. This buffer still has L2ARC metadata.
3450 * 3. This buffer isn't currently writing to the L2ARC.
3451 * 4. The L2ARC entry wasn't evicted, which may
3452 * also have invalidated the vdev.
3453 * 5. This isn't prefetch and l2arc_noprefetch is set.
3455 if (hdr->b_l2hdr != NULL &&
3456 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3457 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3458 l2arc_read_callback_t *cb;
3460 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3461 ARCSTAT_BUMP(arcstat_l2_hits);
3463 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3465 cb->l2rcb_buf = buf;
3466 cb->l2rcb_spa = spa;
3469 cb->l2rcb_flags = zio_flags;
3470 cb->l2rcb_compress = b_compress;
3472 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3473 addr + size < vd->vdev_psize -
3474 VDEV_LABEL_END_SIZE);
3477 * l2arc read. The SCL_L2ARC lock will be
3478 * released by l2arc_read_done().
3479 * Issue a null zio if the underlying buffer
3480 * was squashed to zero size by compression.
3482 if (b_compress == ZIO_COMPRESS_EMPTY) {
3483 rzio = zio_null(pio, spa, vd,
3484 l2arc_read_done, cb,
3485 zio_flags | ZIO_FLAG_DONT_CACHE |
3487 ZIO_FLAG_DONT_PROPAGATE |
3488 ZIO_FLAG_DONT_RETRY);
3490 rzio = zio_read_phys(pio, vd, addr,
3491 b_asize, buf->b_data,
3493 l2arc_read_done, cb, priority,
3494 zio_flags | ZIO_FLAG_DONT_CACHE |
3496 ZIO_FLAG_DONT_PROPAGATE |
3497 ZIO_FLAG_DONT_RETRY, B_FALSE);
3499 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3501 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3503 if (*arc_flags & ARC_NOWAIT) {
3508 ASSERT(*arc_flags & ARC_WAIT);
3509 if (zio_wait(rzio) == 0)
3512 /* l2arc read error; goto zio_read() */
3514 DTRACE_PROBE1(l2arc__miss,
3515 arc_buf_hdr_t *, hdr);
3516 ARCSTAT_BUMP(arcstat_l2_misses);
3517 if (HDR_L2_WRITING(hdr))
3518 ARCSTAT_BUMP(arcstat_l2_rw_clash);
3519 spa_config_exit(spa, SCL_L2ARC, vd);
3523 spa_config_exit(spa, SCL_L2ARC, vd);
3524 if (l2arc_ndev != 0) {
3525 DTRACE_PROBE1(l2arc__miss,
3526 arc_buf_hdr_t *, hdr);
3527 ARCSTAT_BUMP(arcstat_l2_misses);
3531 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3532 arc_read_done, buf, priority, zio_flags, zb);
3534 if (*arc_flags & ARC_WAIT)
3535 return (zio_wait(rzio));
3537 ASSERT(*arc_flags & ARC_NOWAIT);
3544 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3546 ASSERT(buf->b_hdr != NULL);
3547 ASSERT(buf->b_hdr->b_state != arc_anon);
3548 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3549 ASSERT(buf->b_efunc == NULL);
3550 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3552 buf->b_efunc = func;
3553 buf->b_private = private;
3557 * Notify the arc that a block was freed, and thus will never be used again.
3560 arc_freed(spa_t *spa, const blkptr_t *bp)
3563 kmutex_t *hash_lock;
3564 uint64_t guid = spa_load_guid(spa);
3566 ASSERT(!BP_IS_EMBEDDED(bp));
3568 hdr = buf_hash_find(guid, bp, &hash_lock);
3571 if (HDR_BUF_AVAILABLE(hdr)) {
3572 arc_buf_t *buf = hdr->b_buf;
3573 add_reference(hdr, hash_lock, FTAG);
3574 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3575 mutex_exit(hash_lock);
3577 arc_release(buf, FTAG);
3578 (void) arc_buf_remove_ref(buf, FTAG);
3580 mutex_exit(hash_lock);
3586 * Clear the user eviction callback set by arc_set_callback(), first calling
3587 * it if it exists. Because the presence of a callback keeps an arc_buf cached
3588 * clearing the callback may result in the arc_buf being destroyed. However,
3589 * it will not result in the *last* arc_buf being destroyed, hence the data
3590 * will remain cached in the ARC. We make a copy of the arc buffer here so
3591 * that we can process the callback without holding any locks.
3593 * It's possible that the callback is already in the process of being cleared
3594 * by another thread. In this case we can not clear the callback.
3596 * Returns B_TRUE if the callback was successfully called and cleared.
3599 arc_clear_callback(arc_buf_t *buf)
3602 kmutex_t *hash_lock;
3603 arc_evict_func_t *efunc = buf->b_efunc;
3604 void *private = buf->b_private;
3605 list_t *list, *evicted_list;
3606 kmutex_t *lock, *evicted_lock;
3608 mutex_enter(&buf->b_evict_lock);
3612 * We are in arc_do_user_evicts().
3614 ASSERT(buf->b_data == NULL);
3615 mutex_exit(&buf->b_evict_lock);
3617 } else if (buf->b_data == NULL) {
3619 * We are on the eviction list; process this buffer now
3620 * but let arc_do_user_evicts() do the reaping.
3622 buf->b_efunc = NULL;
3623 mutex_exit(&buf->b_evict_lock);
3624 VERIFY0(efunc(private));
3627 hash_lock = HDR_LOCK(hdr);
3628 mutex_enter(hash_lock);
3630 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3632 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3633 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3635 buf->b_efunc = NULL;
3636 buf->b_private = NULL;
3638 if (hdr->b_datacnt > 1) {
3639 mutex_exit(&buf->b_evict_lock);
3640 arc_buf_destroy(buf, FALSE, TRUE);
3642 ASSERT(buf == hdr->b_buf);
3643 hdr->b_flags |= ARC_BUF_AVAILABLE;
3644 mutex_exit(&buf->b_evict_lock);
3647 mutex_exit(hash_lock);
3648 VERIFY0(efunc(private));
3653 * Release this buffer from the cache, making it an anonymous buffer. This
3654 * must be done after a read and prior to modifying the buffer contents.
3655 * If the buffer has more than one reference, we must make
3656 * a new hdr for the buffer.
3659 arc_release(arc_buf_t *buf, void *tag)
3662 kmutex_t *hash_lock = NULL;
3663 l2arc_buf_hdr_t *l2hdr;
3667 * It would be nice to assert that if it's DMU metadata (level >
3668 * 0 || it's the dnode file), then it must be syncing context.
3669 * But we don't know that information at this level.
3672 mutex_enter(&buf->b_evict_lock);
3675 /* this buffer is not on any list */
3676 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3678 if (hdr->b_state == arc_anon) {
3679 /* this buffer is already released */
3680 ASSERT(buf->b_efunc == NULL);
3682 hash_lock = HDR_LOCK(hdr);
3683 mutex_enter(hash_lock);
3685 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3688 l2hdr = hdr->b_l2hdr;
3690 mutex_enter(&l2arc_buflist_mtx);
3691 hdr->b_l2hdr = NULL;
3692 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3694 buf_size = hdr->b_size;
3697 * Do we have more than one buf?
3699 if (hdr->b_datacnt > 1) {
3700 arc_buf_hdr_t *nhdr;
3702 uint64_t blksz = hdr->b_size;
3703 uint64_t spa = hdr->b_spa;
3704 arc_buf_contents_t type = hdr->b_type;
3705 uint32_t flags = hdr->b_flags;
3707 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3709 * Pull the data off of this hdr and attach it to
3710 * a new anonymous hdr.
3712 (void) remove_reference(hdr, hash_lock, tag);
3714 while (*bufp != buf)
3715 bufp = &(*bufp)->b_next;
3716 *bufp = buf->b_next;
3719 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3720 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3721 if (refcount_is_zero(&hdr->b_refcnt)) {
3722 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3723 ASSERT3U(*size, >=, hdr->b_size);
3724 atomic_add_64(size, -hdr->b_size);
3728 * We're releasing a duplicate user data buffer, update
3729 * our statistics accordingly.
3731 if (hdr->b_type == ARC_BUFC_DATA) {
3732 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3733 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3736 hdr->b_datacnt -= 1;
3737 arc_cksum_verify(buf);
3739 arc_buf_unwatch(buf);
3740 #endif /* illumos */
3742 mutex_exit(hash_lock);
3744 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3745 nhdr->b_size = blksz;
3747 nhdr->b_type = type;
3749 nhdr->b_state = arc_anon;
3750 nhdr->b_arc_access = 0;
3751 nhdr->b_flags = flags & ARC_L2_WRITING;
3752 nhdr->b_l2hdr = NULL;
3753 nhdr->b_datacnt = 1;
3754 nhdr->b_freeze_cksum = NULL;
3755 (void) refcount_add(&nhdr->b_refcnt, tag);
3757 mutex_exit(&buf->b_evict_lock);
3758 atomic_add_64(&arc_anon->arcs_size, blksz);
3760 mutex_exit(&buf->b_evict_lock);
3761 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3762 ASSERT(!list_link_active(&hdr->b_arc_node));
3763 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3764 if (hdr->b_state != arc_anon)
3765 arc_change_state(arc_anon, hdr, hash_lock);
3766 hdr->b_arc_access = 0;
3768 mutex_exit(hash_lock);
3770 buf_discard_identity(hdr);
3773 buf->b_efunc = NULL;
3774 buf->b_private = NULL;
3777 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3778 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3779 -l2hdr->b_asize, 0, 0);
3780 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3782 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3783 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3784 mutex_exit(&l2arc_buflist_mtx);
3789 arc_released(arc_buf_t *buf)
3793 mutex_enter(&buf->b_evict_lock);
3794 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3795 mutex_exit(&buf->b_evict_lock);
3801 arc_referenced(arc_buf_t *buf)
3805 mutex_enter(&buf->b_evict_lock);
3806 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3807 mutex_exit(&buf->b_evict_lock);
3808 return (referenced);
3813 arc_write_ready(zio_t *zio)
3815 arc_write_callback_t *callback = zio->io_private;
3816 arc_buf_t *buf = callback->awcb_buf;
3817 arc_buf_hdr_t *hdr = buf->b_hdr;
3819 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3820 callback->awcb_ready(zio, buf, callback->awcb_private);
3823 * If the IO is already in progress, then this is a re-write
3824 * attempt, so we need to thaw and re-compute the cksum.
3825 * It is the responsibility of the callback to handle the
3826 * accounting for any re-write attempt.
3828 if (HDR_IO_IN_PROGRESS(hdr)) {
3829 mutex_enter(&hdr->b_freeze_lock);
3830 if (hdr->b_freeze_cksum != NULL) {
3831 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3832 hdr->b_freeze_cksum = NULL;
3834 mutex_exit(&hdr->b_freeze_lock);
3836 arc_cksum_compute(buf, B_FALSE);
3837 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3841 * The SPA calls this callback for each physical write that happens on behalf
3842 * of a logical write. See the comment in dbuf_write_physdone() for details.
3845 arc_write_physdone(zio_t *zio)
3847 arc_write_callback_t *cb = zio->io_private;
3848 if (cb->awcb_physdone != NULL)
3849 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3853 arc_write_done(zio_t *zio)
3855 arc_write_callback_t *callback = zio->io_private;
3856 arc_buf_t *buf = callback->awcb_buf;
3857 arc_buf_hdr_t *hdr = buf->b_hdr;
3859 ASSERT(hdr->b_acb == NULL);
3861 if (zio->io_error == 0) {
3862 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3863 buf_discard_identity(hdr);
3865 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3866 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3867 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3870 ASSERT(BUF_EMPTY(hdr));
3874 * If the block to be written was all-zero or compressed enough to be
3875 * embedded in the BP, no write was performed so there will be no
3876 * dva/birth/checksum. The buffer must therefore remain anonymous
3879 if (!BUF_EMPTY(hdr)) {
3880 arc_buf_hdr_t *exists;
3881 kmutex_t *hash_lock;
3883 ASSERT(zio->io_error == 0);
3885 arc_cksum_verify(buf);
3887 exists = buf_hash_insert(hdr, &hash_lock);
3890 * This can only happen if we overwrite for
3891 * sync-to-convergence, because we remove
3892 * buffers from the hash table when we arc_free().
3894 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3895 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3896 panic("bad overwrite, hdr=%p exists=%p",
3897 (void *)hdr, (void *)exists);
3898 ASSERT(refcount_is_zero(&exists->b_refcnt));
3899 arc_change_state(arc_anon, exists, hash_lock);
3900 mutex_exit(hash_lock);
3901 arc_hdr_destroy(exists);
3902 exists = buf_hash_insert(hdr, &hash_lock);
3903 ASSERT3P(exists, ==, NULL);
3904 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3906 ASSERT(zio->io_prop.zp_nopwrite);
3907 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3908 panic("bad nopwrite, hdr=%p exists=%p",
3909 (void *)hdr, (void *)exists);
3912 ASSERT(hdr->b_datacnt == 1);
3913 ASSERT(hdr->b_state == arc_anon);
3914 ASSERT(BP_GET_DEDUP(zio->io_bp));
3915 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3918 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3919 /* if it's not anon, we are doing a scrub */
3920 if (!exists && hdr->b_state == arc_anon)
3921 arc_access(hdr, hash_lock);
3922 mutex_exit(hash_lock);
3924 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3927 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3928 callback->awcb_done(zio, buf, callback->awcb_private);
3930 kmem_free(callback, sizeof (arc_write_callback_t));
3934 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3935 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3936 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3937 arc_done_func_t *done, void *private, zio_priority_t priority,
3938 int zio_flags, const zbookmark_phys_t *zb)
3940 arc_buf_hdr_t *hdr = buf->b_hdr;
3941 arc_write_callback_t *callback;
3944 ASSERT(ready != NULL);
3945 ASSERT(done != NULL);
3946 ASSERT(!HDR_IO_ERROR(hdr));
3947 ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3948 ASSERT(hdr->b_acb == NULL);
3950 hdr->b_flags |= ARC_L2CACHE;
3952 hdr->b_flags |= ARC_L2COMPRESS;
3953 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3954 callback->awcb_ready = ready;
3955 callback->awcb_physdone = physdone;
3956 callback->awcb_done = done;
3957 callback->awcb_private = private;
3958 callback->awcb_buf = buf;
3960 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3961 arc_write_ready, arc_write_physdone, arc_write_done, callback,
3962 priority, zio_flags, zb);
3968 arc_memory_throttle(uint64_t reserve, uint64_t txg)
3971 uint64_t available_memory = ptob(freemem);
3972 static uint64_t page_load = 0;
3973 static uint64_t last_txg = 0;
3975 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3977 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
3980 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
3983 if (txg > last_txg) {
3988 * If we are in pageout, we know that memory is already tight,
3989 * the arc is already going to be evicting, so we just want to
3990 * continue to let page writes occur as quickly as possible.
3992 if (curproc == pageproc) {
3993 if (page_load > MAX(ptob(minfree), available_memory) / 4)
3994 return (SET_ERROR(ERESTART));
3995 /* Note: reserve is inflated, so we deflate */
3996 page_load += reserve / 8;
3998 } else if (page_load > 0 && arc_reclaim_needed()) {
3999 /* memory is low, delay before restarting */
4000 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4001 return (SET_ERROR(EAGAIN));
4009 arc_tempreserve_clear(uint64_t reserve)
4011 atomic_add_64(&arc_tempreserve, -reserve);
4012 ASSERT((int64_t)arc_tempreserve >= 0);
4016 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4021 if (reserve > arc_c/4 && !arc_no_grow) {
4022 arc_c = MIN(arc_c_max, reserve * 4);
4023 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4025 if (reserve > arc_c)
4026 return (SET_ERROR(ENOMEM));
4029 * Don't count loaned bufs as in flight dirty data to prevent long
4030 * network delays from blocking transactions that are ready to be
4031 * assigned to a txg.
4033 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4036 * Writes will, almost always, require additional memory allocations
4037 * in order to compress/encrypt/etc the data. We therefore need to
4038 * make sure that there is sufficient available memory for this.
4040 error = arc_memory_throttle(reserve, txg);
4045 * Throttle writes when the amount of dirty data in the cache
4046 * gets too large. We try to keep the cache less than half full
4047 * of dirty blocks so that our sync times don't grow too large.
4048 * Note: if two requests come in concurrently, we might let them
4049 * both succeed, when one of them should fail. Not a huge deal.
4052 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4053 anon_size > arc_c / 4) {
4054 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4055 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4056 arc_tempreserve>>10,
4057 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4058 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4059 reserve>>10, arc_c>>10);
4060 return (SET_ERROR(ERESTART));
4062 atomic_add_64(&arc_tempreserve, reserve);
4066 static kmutex_t arc_lowmem_lock;
4068 static eventhandler_tag arc_event_lowmem = NULL;
4071 arc_lowmem(void *arg __unused, int howto __unused)
4074 /* Serialize access via arc_lowmem_lock. */
4075 mutex_enter(&arc_lowmem_lock);
4076 mutex_enter(&arc_reclaim_thr_lock);
4078 DTRACE_PROBE(arc__needfree);
4079 cv_signal(&arc_reclaim_thr_cv);
4082 * It is unsafe to block here in arbitrary threads, because we can come
4083 * here from ARC itself and may hold ARC locks and thus risk a deadlock
4084 * with ARC reclaim thread.
4086 if (curproc == pageproc) {
4088 msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4090 mutex_exit(&arc_reclaim_thr_lock);
4091 mutex_exit(&arc_lowmem_lock);
4098 int i, prefetch_tunable_set = 0;
4100 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4101 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4102 mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
4104 /* Convert seconds to clock ticks */
4105 arc_min_prefetch_lifespan = 1 * hz;
4107 /* Start out with 1/8 of all memory */
4108 arc_c = kmem_size() / 8;
4113 * On architectures where the physical memory can be larger
4114 * than the addressable space (intel in 32-bit mode), we may
4115 * need to limit the cache to 1/8 of VM size.
4117 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4120 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4121 arc_c_min = MAX(arc_c / 4, 64<<18);
4122 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4123 if (arc_c * 8 >= 1<<30)
4124 arc_c_max = (arc_c * 8) - (1<<30);
4126 arc_c_max = arc_c_min;
4127 arc_c_max = MAX(arc_c * 5, arc_c_max);
4131 * Allow the tunables to override our calculations if they are
4132 * reasonable (ie. over 16MB)
4134 if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
4135 arc_c_max = zfs_arc_max;
4136 if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
4137 arc_c_min = zfs_arc_min;
4141 arc_p = (arc_c >> 1);
4143 /* limit meta-data to 1/4 of the arc capacity */
4144 arc_meta_limit = arc_c_max / 4;
4146 /* Allow the tunable to override if it is reasonable */
4147 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4148 arc_meta_limit = zfs_arc_meta_limit;
4150 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4151 arc_c_min = arc_meta_limit / 2;
4153 if (zfs_arc_grow_retry > 0)
4154 arc_grow_retry = zfs_arc_grow_retry;
4156 if (zfs_arc_shrink_shift > 0)
4157 arc_shrink_shift = zfs_arc_shrink_shift;
4159 if (zfs_arc_p_min_shift > 0)
4160 arc_p_min_shift = zfs_arc_p_min_shift;
4162 /* if kmem_flags are set, lets try to use less memory */
4163 if (kmem_debugging())
4165 if (arc_c < arc_c_min)
4168 zfs_arc_min = arc_c_min;
4169 zfs_arc_max = arc_c_max;
4171 arc_anon = &ARC_anon;
4173 arc_mru_ghost = &ARC_mru_ghost;
4175 arc_mfu_ghost = &ARC_mfu_ghost;
4176 arc_l2c_only = &ARC_l2c_only;
4179 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4180 mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4181 NULL, MUTEX_DEFAULT, NULL);
4182 mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4183 NULL, MUTEX_DEFAULT, NULL);
4184 mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4185 NULL, MUTEX_DEFAULT, NULL);
4186 mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4187 NULL, MUTEX_DEFAULT, NULL);
4188 mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4189 NULL, MUTEX_DEFAULT, NULL);
4190 mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4191 NULL, MUTEX_DEFAULT, NULL);
4193 list_create(&arc_mru->arcs_lists[i],
4194 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4195 list_create(&arc_mru_ghost->arcs_lists[i],
4196 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4197 list_create(&arc_mfu->arcs_lists[i],
4198 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4199 list_create(&arc_mfu_ghost->arcs_lists[i],
4200 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4201 list_create(&arc_mfu_ghost->arcs_lists[i],
4202 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4203 list_create(&arc_l2c_only->arcs_lists[i],
4204 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4209 arc_thread_exit = 0;
4210 arc_eviction_list = NULL;
4211 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4212 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4214 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4215 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4217 if (arc_ksp != NULL) {
4218 arc_ksp->ks_data = &arc_stats;
4219 kstat_install(arc_ksp);
4222 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4223 TS_RUN, minclsyspri);
4226 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4227 EVENTHANDLER_PRI_FIRST);
4234 * Calculate maximum amount of dirty data per pool.
4236 * If it has been set by /etc/system, take that.
4237 * Otherwise, use a percentage of physical memory defined by
4238 * zfs_dirty_data_max_percent (default 10%) with a cap at
4239 * zfs_dirty_data_max_max (default 4GB).
4241 if (zfs_dirty_data_max == 0) {
4242 zfs_dirty_data_max = ptob(physmem) *
4243 zfs_dirty_data_max_percent / 100;
4244 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4245 zfs_dirty_data_max_max);
4249 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4250 prefetch_tunable_set = 1;
4253 if (prefetch_tunable_set == 0) {
4254 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4256 printf(" add \"vfs.zfs.prefetch_disable=0\" "
4257 "to /boot/loader.conf.\n");
4258 zfs_prefetch_disable = 1;
4261 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4262 prefetch_tunable_set == 0) {
4263 printf("ZFS NOTICE: Prefetch is disabled by default if less "
4264 "than 4GB of RAM is present;\n"
4265 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
4266 "to /boot/loader.conf.\n");
4267 zfs_prefetch_disable = 1;
4270 /* Warn about ZFS memory and address space requirements. */
4271 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4272 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4273 "expect unstable behavior.\n");
4275 if (kmem_size() < 512 * (1 << 20)) {
4276 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4277 "expect unstable behavior.\n");
4278 printf(" Consider tuning vm.kmem_size and "
4279 "vm.kmem_size_max\n");
4280 printf(" in /boot/loader.conf.\n");
4290 mutex_enter(&arc_reclaim_thr_lock);
4291 arc_thread_exit = 1;
4292 cv_signal(&arc_reclaim_thr_cv);
4293 while (arc_thread_exit != 0)
4294 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4295 mutex_exit(&arc_reclaim_thr_lock);
4301 if (arc_ksp != NULL) {
4302 kstat_delete(arc_ksp);
4306 mutex_destroy(&arc_eviction_mtx);
4307 mutex_destroy(&arc_reclaim_thr_lock);
4308 cv_destroy(&arc_reclaim_thr_cv);
4310 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4311 list_destroy(&arc_mru->arcs_lists[i]);
4312 list_destroy(&arc_mru_ghost->arcs_lists[i]);
4313 list_destroy(&arc_mfu->arcs_lists[i]);
4314 list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4315 list_destroy(&arc_l2c_only->arcs_lists[i]);
4317 mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4318 mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4319 mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4320 mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4321 mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4322 mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4327 ASSERT(arc_loaned_bytes == 0);
4329 mutex_destroy(&arc_lowmem_lock);
4331 if (arc_event_lowmem != NULL)
4332 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4339 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4340 * It uses dedicated storage devices to hold cached data, which are populated
4341 * using large infrequent writes. The main role of this cache is to boost
4342 * the performance of random read workloads. The intended L2ARC devices
4343 * include short-stroked disks, solid state disks, and other media with
4344 * substantially faster read latency than disk.
4346 * +-----------------------+
4348 * +-----------------------+
4351 * l2arc_feed_thread() arc_read()
4355 * +---------------+ |
4357 * +---------------+ |
4362 * +-------+ +-------+
4364 * | cache | | cache |
4365 * +-------+ +-------+
4366 * +=========+ .-----.
4367 * : L2ARC : |-_____-|
4368 * : devices : | Disks |
4369 * +=========+ `-_____-'
4371 * Read requests are satisfied from the following sources, in order:
4374 * 2) vdev cache of L2ARC devices
4376 * 4) vdev cache of disks
4379 * Some L2ARC device types exhibit extremely slow write performance.
4380 * To accommodate for this there are some significant differences between
4381 * the L2ARC and traditional cache design:
4383 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4384 * the ARC behave as usual, freeing buffers and placing headers on ghost
4385 * lists. The ARC does not send buffers to the L2ARC during eviction as
4386 * this would add inflated write latencies for all ARC memory pressure.
4388 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4389 * It does this by periodically scanning buffers from the eviction-end of
4390 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4391 * not already there. It scans until a headroom of buffers is satisfied,
4392 * which itself is a buffer for ARC eviction. If a compressible buffer is
4393 * found during scanning and selected for writing to an L2ARC device, we
4394 * temporarily boost scanning headroom during the next scan cycle to make
4395 * sure we adapt to compression effects (which might significantly reduce
4396 * the data volume we write to L2ARC). The thread that does this is
4397 * l2arc_feed_thread(), illustrated below; example sizes are included to
4398 * provide a better sense of ratio than this diagram:
4401 * +---------------------+----------+
4402 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4403 * +---------------------+----------+ | o L2ARC eligible
4404 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4405 * +---------------------+----------+ |
4406 * 15.9 Gbytes ^ 32 Mbytes |
4408 * l2arc_feed_thread()
4410 * l2arc write hand <--[oooo]--'
4414 * +==============================+
4415 * L2ARC dev |####|#|###|###| |####| ... |
4416 * +==============================+
4419 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4420 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4421 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4422 * safe to say that this is an uncommon case, since buffers at the end of
4423 * the ARC lists have moved there due to inactivity.
4425 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4426 * then the L2ARC simply misses copying some buffers. This serves as a
4427 * pressure valve to prevent heavy read workloads from both stalling the ARC
4428 * with waits and clogging the L2ARC with writes. This also helps prevent
4429 * the potential for the L2ARC to churn if it attempts to cache content too
4430 * quickly, such as during backups of the entire pool.
4432 * 5. After system boot and before the ARC has filled main memory, there are
4433 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4434 * lists can remain mostly static. Instead of searching from tail of these
4435 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4436 * for eligible buffers, greatly increasing its chance of finding them.
4438 * The L2ARC device write speed is also boosted during this time so that
4439 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4440 * there are no L2ARC reads, and no fear of degrading read performance
4441 * through increased writes.
4443 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4444 * the vdev queue can aggregate them into larger and fewer writes. Each
4445 * device is written to in a rotor fashion, sweeping writes through
4446 * available space then repeating.
4448 * 7. The L2ARC does not store dirty content. It never needs to flush
4449 * write buffers back to disk based storage.
4451 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4452 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4454 * The performance of the L2ARC can be tweaked by a number of tunables, which
4455 * may be necessary for different workloads:
4457 * l2arc_write_max max write bytes per interval
4458 * l2arc_write_boost extra write bytes during device warmup
4459 * l2arc_noprefetch skip caching prefetched buffers
4460 * l2arc_headroom number of max device writes to precache
4461 * l2arc_headroom_boost when we find compressed buffers during ARC
4462 * scanning, we multiply headroom by this
4463 * percentage factor for the next scan cycle,
4464 * since more compressed buffers are likely to
4466 * l2arc_feed_secs seconds between L2ARC writing
4468 * Tunables may be removed or added as future performance improvements are
4469 * integrated, and also may become zpool properties.
4471 * There are three key functions that control how the L2ARC warms up:
4473 * l2arc_write_eligible() check if a buffer is eligible to cache
4474 * l2arc_write_size() calculate how much to write
4475 * l2arc_write_interval() calculate sleep delay between writes
4477 * These three functions determine what to write, how much, and how quickly
4482 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4485 * A buffer is *not* eligible for the L2ARC if it:
4486 * 1. belongs to a different spa.
4487 * 2. is already cached on the L2ARC.
4488 * 3. has an I/O in progress (it may be an incomplete read).
4489 * 4. is flagged not eligible (zfs property).
4491 if (ab->b_spa != spa_guid) {
4492 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4495 if (ab->b_l2hdr != NULL) {
4496 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4499 if (HDR_IO_IN_PROGRESS(ab)) {
4500 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4503 if (!HDR_L2CACHE(ab)) {
4504 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4512 l2arc_write_size(void)
4517 * Make sure our globals have meaningful values in case the user
4520 size = l2arc_write_max;
4522 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4523 "be greater than zero, resetting it to the default (%d)",
4525 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4528 if (arc_warm == B_FALSE)
4529 size += l2arc_write_boost;
4536 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4538 clock_t interval, next, now;
4541 * If the ARC lists are busy, increase our write rate; if the
4542 * lists are stale, idle back. This is achieved by checking
4543 * how much we previously wrote - if it was more than half of
4544 * what we wanted, schedule the next write much sooner.
4546 if (l2arc_feed_again && wrote > (wanted / 2))
4547 interval = (hz * l2arc_feed_min_ms) / 1000;
4549 interval = hz * l2arc_feed_secs;
4551 now = ddi_get_lbolt();
4552 next = MAX(now, MIN(now + interval, began + interval));
4558 l2arc_hdr_stat_add(void)
4560 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4561 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4565 l2arc_hdr_stat_remove(void)
4567 ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4568 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4572 * Cycle through L2ARC devices. This is how L2ARC load balances.
4573 * If a device is returned, this also returns holding the spa config lock.
4575 static l2arc_dev_t *
4576 l2arc_dev_get_next(void)
4578 l2arc_dev_t *first, *next = NULL;
4581 * Lock out the removal of spas (spa_namespace_lock), then removal
4582 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4583 * both locks will be dropped and a spa config lock held instead.
4585 mutex_enter(&spa_namespace_lock);
4586 mutex_enter(&l2arc_dev_mtx);
4588 /* if there are no vdevs, there is nothing to do */
4589 if (l2arc_ndev == 0)
4593 next = l2arc_dev_last;
4595 /* loop around the list looking for a non-faulted vdev */
4597 next = list_head(l2arc_dev_list);
4599 next = list_next(l2arc_dev_list, next);
4601 next = list_head(l2arc_dev_list);
4604 /* if we have come back to the start, bail out */
4607 else if (next == first)
4610 } while (vdev_is_dead(next->l2ad_vdev));
4612 /* if we were unable to find any usable vdevs, return NULL */
4613 if (vdev_is_dead(next->l2ad_vdev))
4616 l2arc_dev_last = next;
4619 mutex_exit(&l2arc_dev_mtx);
4622 * Grab the config lock to prevent the 'next' device from being
4623 * removed while we are writing to it.
4626 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4627 mutex_exit(&spa_namespace_lock);
4633 * Free buffers that were tagged for destruction.
4636 l2arc_do_free_on_write()
4639 l2arc_data_free_t *df, *df_prev;
4641 mutex_enter(&l2arc_free_on_write_mtx);
4642 buflist = l2arc_free_on_write;
4644 for (df = list_tail(buflist); df; df = df_prev) {
4645 df_prev = list_prev(buflist, df);
4646 ASSERT(df->l2df_data != NULL);
4647 ASSERT(df->l2df_func != NULL);
4648 df->l2df_func(df->l2df_data, df->l2df_size);
4649 list_remove(buflist, df);
4650 kmem_free(df, sizeof (l2arc_data_free_t));
4653 mutex_exit(&l2arc_free_on_write_mtx);
4657 * A write to a cache device has completed. Update all headers to allow
4658 * reads from these buffers to begin.
4661 l2arc_write_done(zio_t *zio)
4663 l2arc_write_callback_t *cb;
4666 arc_buf_hdr_t *head, *ab, *ab_prev;
4667 l2arc_buf_hdr_t *abl2;
4668 kmutex_t *hash_lock;
4669 int64_t bytes_dropped = 0;
4671 cb = zio->io_private;
4673 dev = cb->l2wcb_dev;
4674 ASSERT(dev != NULL);
4675 head = cb->l2wcb_head;
4676 ASSERT(head != NULL);
4677 buflist = dev->l2ad_buflist;
4678 ASSERT(buflist != NULL);
4679 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4680 l2arc_write_callback_t *, cb);
4682 if (zio->io_error != 0)
4683 ARCSTAT_BUMP(arcstat_l2_writes_error);
4685 mutex_enter(&l2arc_buflist_mtx);
4688 * All writes completed, or an error was hit.
4690 for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4691 ab_prev = list_prev(buflist, ab);
4695 * Release the temporary compressed buffer as soon as possible.
4697 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4698 l2arc_release_cdata_buf(ab);
4700 hash_lock = HDR_LOCK(ab);
4701 if (!mutex_tryenter(hash_lock)) {
4703 * This buffer misses out. It may be in a stage
4704 * of eviction. Its ARC_L2_WRITING flag will be
4705 * left set, denying reads to this buffer.
4707 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4711 if (zio->io_error != 0) {
4713 * Error - drop L2ARC entry.
4715 list_remove(buflist, ab);
4716 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4717 bytes_dropped += abl2->b_asize;
4719 trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4721 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4722 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4726 * Allow ARC to begin reads to this L2ARC entry.
4728 ab->b_flags &= ~ARC_L2_WRITING;
4730 mutex_exit(hash_lock);
4733 atomic_inc_64(&l2arc_writes_done);
4734 list_remove(buflist, head);
4735 kmem_cache_free(hdr_cache, head);
4736 mutex_exit(&l2arc_buflist_mtx);
4738 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4740 l2arc_do_free_on_write();
4742 kmem_free(cb, sizeof (l2arc_write_callback_t));
4746 * A read to a cache device completed. Validate buffer contents before
4747 * handing over to the regular ARC routines.
4750 l2arc_read_done(zio_t *zio)
4752 l2arc_read_callback_t *cb;
4755 kmutex_t *hash_lock;
4758 ASSERT(zio->io_vd != NULL);
4759 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4761 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4763 cb = zio->io_private;
4765 buf = cb->l2rcb_buf;
4766 ASSERT(buf != NULL);
4768 hash_lock = HDR_LOCK(buf->b_hdr);
4769 mutex_enter(hash_lock);
4771 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4774 * If the buffer was compressed, decompress it first.
4776 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4777 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4778 ASSERT(zio->io_data != NULL);
4781 * Check this survived the L2ARC journey.
4783 equal = arc_cksum_equal(buf);
4784 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4785 mutex_exit(hash_lock);
4786 zio->io_private = buf;
4787 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4788 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
4791 mutex_exit(hash_lock);
4793 * Buffer didn't survive caching. Increment stats and
4794 * reissue to the original storage device.
4796 if (zio->io_error != 0) {
4797 ARCSTAT_BUMP(arcstat_l2_io_error);
4799 zio->io_error = SET_ERROR(EIO);
4802 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4805 * If there's no waiter, issue an async i/o to the primary
4806 * storage now. If there *is* a waiter, the caller must
4807 * issue the i/o in a context where it's OK to block.
4809 if (zio->io_waiter == NULL) {
4810 zio_t *pio = zio_unique_parent(zio);
4812 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4814 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4815 buf->b_data, zio->io_size, arc_read_done, buf,
4816 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4820 kmem_free(cb, sizeof (l2arc_read_callback_t));
4824 * This is the list priority from which the L2ARC will search for pages to
4825 * cache. This is used within loops (0..3) to cycle through lists in the
4826 * desired order. This order can have a significant effect on cache
4829 * Currently the metadata lists are hit first, MFU then MRU, followed by
4830 * the data lists. This function returns a locked list, and also returns
4834 l2arc_list_locked(int list_num, kmutex_t **lock)
4836 list_t *list = NULL;
4839 ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4841 if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4843 list = &arc_mfu->arcs_lists[idx];
4844 *lock = ARCS_LOCK(arc_mfu, idx);
4845 } else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4846 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4847 list = &arc_mru->arcs_lists[idx];
4848 *lock = ARCS_LOCK(arc_mru, idx);
4849 } else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4850 ARC_BUFC_NUMDATALISTS)) {
4851 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4852 list = &arc_mfu->arcs_lists[idx];
4853 *lock = ARCS_LOCK(arc_mfu, idx);
4855 idx = list_num - ARC_BUFC_NUMLISTS;
4856 list = &arc_mru->arcs_lists[idx];
4857 *lock = ARCS_LOCK(arc_mru, idx);
4860 ASSERT(!(MUTEX_HELD(*lock)));
4866 * Evict buffers from the device write hand to the distance specified in
4867 * bytes. This distance may span populated buffers, it may span nothing.
4868 * This is clearing a region on the L2ARC device ready for writing.
4869 * If the 'all' boolean is set, every buffer is evicted.
4872 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4875 l2arc_buf_hdr_t *abl2;
4876 arc_buf_hdr_t *ab, *ab_prev;
4877 kmutex_t *hash_lock;
4879 int64_t bytes_evicted = 0;
4881 buflist = dev->l2ad_buflist;
4883 if (buflist == NULL)
4886 if (!all && dev->l2ad_first) {
4888 * This is the first sweep through the device. There is
4894 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4896 * When nearing the end of the device, evict to the end
4897 * before the device write hand jumps to the start.
4899 taddr = dev->l2ad_end;
4901 taddr = dev->l2ad_hand + distance;
4903 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4904 uint64_t, taddr, boolean_t, all);
4907 mutex_enter(&l2arc_buflist_mtx);
4908 for (ab = list_tail(buflist); ab; ab = ab_prev) {
4909 ab_prev = list_prev(buflist, ab);
4911 hash_lock = HDR_LOCK(ab);
4912 if (!mutex_tryenter(hash_lock)) {
4914 * Missed the hash lock. Retry.
4916 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4917 mutex_exit(&l2arc_buflist_mtx);
4918 mutex_enter(hash_lock);
4919 mutex_exit(hash_lock);
4923 if (HDR_L2_WRITE_HEAD(ab)) {
4925 * We hit a write head node. Leave it for
4926 * l2arc_write_done().
4928 list_remove(buflist, ab);
4929 mutex_exit(hash_lock);
4933 if (!all && ab->b_l2hdr != NULL &&
4934 (ab->b_l2hdr->b_daddr > taddr ||
4935 ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4937 * We've evicted to the target address,
4938 * or the end of the device.
4940 mutex_exit(hash_lock);
4944 if (HDR_FREE_IN_PROGRESS(ab)) {
4946 * Already on the path to destruction.
4948 mutex_exit(hash_lock);
4952 if (ab->b_state == arc_l2c_only) {
4953 ASSERT(!HDR_L2_READING(ab));
4955 * This doesn't exist in the ARC. Destroy.
4956 * arc_hdr_destroy() will call list_remove()
4957 * and decrement arcstat_l2_size.
4959 arc_change_state(arc_anon, ab, hash_lock);
4960 arc_hdr_destroy(ab);
4963 * Invalidate issued or about to be issued
4964 * reads, since we may be about to write
4965 * over this location.
4967 if (HDR_L2_READING(ab)) {
4968 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4969 ab->b_flags |= ARC_L2_EVICTED;
4973 * Tell ARC this no longer exists in L2ARC.
4975 if (ab->b_l2hdr != NULL) {
4977 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4978 bytes_evicted += abl2->b_asize;
4980 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4981 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4983 list_remove(buflist, ab);
4986 * This may have been leftover after a
4989 ab->b_flags &= ~ARC_L2_WRITING;
4991 mutex_exit(hash_lock);
4993 mutex_exit(&l2arc_buflist_mtx);
4995 vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
4996 dev->l2ad_evict = taddr;
5000 * Find and write ARC buffers to the L2ARC device.
5002 * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
5003 * for reading until they have completed writing.
5004 * The headroom_boost is an in-out parameter used to maintain headroom boost
5005 * state between calls to this function.
5007 * Returns the number of bytes actually written (which may be smaller than
5008 * the delta by which the device hand has changed due to alignment).
5011 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5012 boolean_t *headroom_boost)
5014 arc_buf_hdr_t *ab, *ab_prev, *head;
5016 uint64_t write_asize, write_psize, write_sz, headroom,
5019 kmutex_t *list_lock;
5021 l2arc_write_callback_t *cb;
5023 uint64_t guid = spa_load_guid(spa);
5024 const boolean_t do_headroom_boost = *headroom_boost;
5027 ASSERT(dev->l2ad_vdev != NULL);
5029 /* Lower the flag now, we might want to raise it again later. */
5030 *headroom_boost = B_FALSE;
5033 write_sz = write_asize = write_psize = 0;
5035 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5036 head->b_flags |= ARC_L2_WRITE_HEAD;
5038 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
5040 * We will want to try to compress buffers that are at least 2x the
5041 * device sector size.
5043 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5046 * Copy buffers for L2ARC writing.
5048 mutex_enter(&l2arc_buflist_mtx);
5049 for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
5050 uint64_t passed_sz = 0;
5052 list = l2arc_list_locked(try, &list_lock);
5053 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
5056 * L2ARC fast warmup.
5058 * Until the ARC is warm and starts to evict, read from the
5059 * head of the ARC lists rather than the tail.
5061 if (arc_warm == B_FALSE)
5062 ab = list_head(list);
5064 ab = list_tail(list);
5066 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
5068 headroom = target_sz * l2arc_headroom;
5069 if (do_headroom_boost)
5070 headroom = (headroom * l2arc_headroom_boost) / 100;
5072 for (; ab; ab = ab_prev) {
5073 l2arc_buf_hdr_t *l2hdr;
5074 kmutex_t *hash_lock;
5077 if (arc_warm == B_FALSE)
5078 ab_prev = list_next(list, ab);
5080 ab_prev = list_prev(list, ab);
5081 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, ab->b_size);
5083 hash_lock = HDR_LOCK(ab);
5084 if (!mutex_tryenter(hash_lock)) {
5085 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5087 * Skip this buffer rather than waiting.
5092 passed_sz += ab->b_size;
5093 if (passed_sz > headroom) {
5097 mutex_exit(hash_lock);
5098 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5102 if (!l2arc_write_eligible(guid, ab)) {
5103 mutex_exit(hash_lock);
5107 if ((write_sz + ab->b_size) > target_sz) {
5109 mutex_exit(hash_lock);
5110 ARCSTAT_BUMP(arcstat_l2_write_full);
5116 * Insert a dummy header on the buflist so
5117 * l2arc_write_done() can find where the
5118 * write buffers begin without searching.
5120 list_insert_head(dev->l2ad_buflist, head);
5123 sizeof (l2arc_write_callback_t), KM_SLEEP);
5124 cb->l2wcb_dev = dev;
5125 cb->l2wcb_head = head;
5126 pio = zio_root(spa, l2arc_write_done, cb,
5128 ARCSTAT_BUMP(arcstat_l2_write_pios);
5132 * Create and add a new L2ARC header.
5134 l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
5136 ab->b_flags |= ARC_L2_WRITING;
5139 * Temporarily stash the data buffer in b_tmp_cdata.
5140 * The subsequent write step will pick it up from
5141 * there. This is because can't access ab->b_buf
5142 * without holding the hash_lock, which we in turn
5143 * can't access without holding the ARC list locks
5144 * (which we want to avoid during compression/writing).
5146 l2hdr->b_compress = ZIO_COMPRESS_OFF;
5147 l2hdr->b_asize = ab->b_size;
5148 l2hdr->b_tmp_cdata = ab->b_buf->b_data;
5150 buf_sz = ab->b_size;
5151 ab->b_l2hdr = l2hdr;
5153 list_insert_head(dev->l2ad_buflist, ab);
5156 * Compute and store the buffer cksum before
5157 * writing. On debug the cksum is verified first.
5159 arc_cksum_verify(ab->b_buf);
5160 arc_cksum_compute(ab->b_buf, B_TRUE);
5162 mutex_exit(hash_lock);
5167 mutex_exit(list_lock);
5173 /* No buffers selected for writing? */
5176 mutex_exit(&l2arc_buflist_mtx);
5177 kmem_cache_free(hdr_cache, head);
5182 * Now start writing the buffers. We're starting at the write head
5183 * and work backwards, retracing the course of the buffer selector
5186 for (ab = list_prev(dev->l2ad_buflist, head); ab;
5187 ab = list_prev(dev->l2ad_buflist, ab)) {
5188 l2arc_buf_hdr_t *l2hdr;
5192 * We shouldn't need to lock the buffer here, since we flagged
5193 * it as ARC_L2_WRITING in the previous step, but we must take
5194 * care to only access its L2 cache parameters. In particular,
5195 * ab->b_buf may be invalid by now due to ARC eviction.
5197 l2hdr = ab->b_l2hdr;
5198 l2hdr->b_daddr = dev->l2ad_hand;
5200 if ((ab->b_flags & ARC_L2COMPRESS) &&
5201 l2hdr->b_asize >= buf_compress_minsz) {
5202 if (l2arc_compress_buf(l2hdr)) {
5204 * If compression succeeded, enable headroom
5205 * boost on the next scan cycle.
5207 *headroom_boost = B_TRUE;
5212 * Pick up the buffer data we had previously stashed away
5213 * (and now potentially also compressed).
5215 buf_data = l2hdr->b_tmp_cdata;
5216 buf_sz = l2hdr->b_asize;
5218 /* Compression may have squashed the buffer to zero length. */
5222 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5223 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5224 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5225 ZIO_FLAG_CANFAIL, B_FALSE);
5227 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5229 (void) zio_nowait(wzio);
5231 write_asize += buf_sz;
5233 * Keep the clock hand suitably device-aligned.
5235 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5236 write_psize += buf_p_sz;
5237 dev->l2ad_hand += buf_p_sz;
5241 mutex_exit(&l2arc_buflist_mtx);
5243 ASSERT3U(write_asize, <=, target_sz);
5244 ARCSTAT_BUMP(arcstat_l2_writes_sent);
5245 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5246 ARCSTAT_INCR(arcstat_l2_size, write_sz);
5247 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5248 vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
5251 * Bump device hand to the device start if it is approaching the end.
5252 * l2arc_evict() will already have evicted ahead for this case.
5254 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5255 dev->l2ad_hand = dev->l2ad_start;
5256 dev->l2ad_evict = dev->l2ad_start;
5257 dev->l2ad_first = B_FALSE;
5260 dev->l2ad_writing = B_TRUE;
5261 (void) zio_wait(pio);
5262 dev->l2ad_writing = B_FALSE;
5264 return (write_asize);
5268 * Compresses an L2ARC buffer.
5269 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5270 * size in l2hdr->b_asize. This routine tries to compress the data and
5271 * depending on the compression result there are three possible outcomes:
5272 * *) The buffer was incompressible. The original l2hdr contents were left
5273 * untouched and are ready for writing to an L2 device.
5274 * *) The buffer was all-zeros, so there is no need to write it to an L2
5275 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5276 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5277 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5278 * data buffer which holds the compressed data to be written, and b_asize
5279 * tells us how much data there is. b_compress is set to the appropriate
5280 * compression algorithm. Once writing is done, invoke
5281 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5283 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5284 * buffer was incompressible).
5287 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5290 size_t csize, len, rounded;
5292 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5293 ASSERT(l2hdr->b_tmp_cdata != NULL);
5295 len = l2hdr->b_asize;
5296 cdata = zio_data_buf_alloc(len);
5297 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5298 cdata, l2hdr->b_asize);
5300 rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
5301 if (rounded > csize) {
5302 bzero((char *)cdata + csize, rounded - csize);
5307 /* zero block, indicate that there's nothing to write */
5308 zio_data_buf_free(cdata, len);
5309 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5311 l2hdr->b_tmp_cdata = NULL;
5312 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5314 } else if (csize > 0 && csize < len) {
5316 * Compression succeeded, we'll keep the cdata around for
5317 * writing and release it afterwards.
5319 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5320 l2hdr->b_asize = csize;
5321 l2hdr->b_tmp_cdata = cdata;
5322 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5326 * Compression failed, release the compressed buffer.
5327 * l2hdr will be left unmodified.
5329 zio_data_buf_free(cdata, len);
5330 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5336 * Decompresses a zio read back from an l2arc device. On success, the
5337 * underlying zio's io_data buffer is overwritten by the uncompressed
5338 * version. On decompression error (corrupt compressed stream), the
5339 * zio->io_error value is set to signal an I/O error.
5341 * Please note that the compressed data stream is not checksummed, so
5342 * if the underlying device is experiencing data corruption, we may feed
5343 * corrupt data to the decompressor, so the decompressor needs to be
5344 * able to handle this situation (LZ4 does).
5347 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5349 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5351 if (zio->io_error != 0) {
5353 * An io error has occured, just restore the original io
5354 * size in preparation for a main pool read.
5356 zio->io_orig_size = zio->io_size = hdr->b_size;
5360 if (c == ZIO_COMPRESS_EMPTY) {
5362 * An empty buffer results in a null zio, which means we
5363 * need to fill its io_data after we're done restoring the
5364 * buffer's contents.
5366 ASSERT(hdr->b_buf != NULL);
5367 bzero(hdr->b_buf->b_data, hdr->b_size);
5368 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5370 ASSERT(zio->io_data != NULL);
5372 * We copy the compressed data from the start of the arc buffer
5373 * (the zio_read will have pulled in only what we need, the
5374 * rest is garbage which we will overwrite at decompression)
5375 * and then decompress back to the ARC data buffer. This way we
5376 * can minimize copying by simply decompressing back over the
5377 * original compressed data (rather than decompressing to an
5378 * aux buffer and then copying back the uncompressed buffer,
5379 * which is likely to be much larger).
5384 csize = zio->io_size;
5385 cdata = zio_data_buf_alloc(csize);
5386 bcopy(zio->io_data, cdata, csize);
5387 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5389 zio->io_error = EIO;
5390 zio_data_buf_free(cdata, csize);
5393 /* Restore the expected uncompressed IO size. */
5394 zio->io_orig_size = zio->io_size = hdr->b_size;
5398 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5399 * This buffer serves as a temporary holder of compressed data while
5400 * the buffer entry is being written to an l2arc device. Once that is
5401 * done, we can dispose of it.
5404 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5406 l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5408 if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5410 * If the data was compressed, then we've allocated a
5411 * temporary buffer for it, so now we need to release it.
5413 ASSERT(l2hdr->b_tmp_cdata != NULL);
5414 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5416 l2hdr->b_tmp_cdata = NULL;
5420 * This thread feeds the L2ARC at regular intervals. This is the beating
5421 * heart of the L2ARC.
5424 l2arc_feed_thread(void *dummy __unused)
5429 uint64_t size, wrote;
5430 clock_t begin, next = ddi_get_lbolt();
5431 boolean_t headroom_boost = B_FALSE;
5433 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5435 mutex_enter(&l2arc_feed_thr_lock);
5437 while (l2arc_thread_exit == 0) {
5438 CALLB_CPR_SAFE_BEGIN(&cpr);
5439 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5440 next - ddi_get_lbolt());
5441 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5442 next = ddi_get_lbolt() + hz;
5445 * Quick check for L2ARC devices.
5447 mutex_enter(&l2arc_dev_mtx);
5448 if (l2arc_ndev == 0) {
5449 mutex_exit(&l2arc_dev_mtx);
5452 mutex_exit(&l2arc_dev_mtx);
5453 begin = ddi_get_lbolt();
5456 * This selects the next l2arc device to write to, and in
5457 * doing so the next spa to feed from: dev->l2ad_spa. This
5458 * will return NULL if there are now no l2arc devices or if
5459 * they are all faulted.
5461 * If a device is returned, its spa's config lock is also
5462 * held to prevent device removal. l2arc_dev_get_next()
5463 * will grab and release l2arc_dev_mtx.
5465 if ((dev = l2arc_dev_get_next()) == NULL)
5468 spa = dev->l2ad_spa;
5469 ASSERT(spa != NULL);
5472 * If the pool is read-only then force the feed thread to
5473 * sleep a little longer.
5475 if (!spa_writeable(spa)) {
5476 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5477 spa_config_exit(spa, SCL_L2ARC, dev);
5482 * Avoid contributing to memory pressure.
5484 if (arc_reclaim_needed()) {
5485 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5486 spa_config_exit(spa, SCL_L2ARC, dev);
5490 ARCSTAT_BUMP(arcstat_l2_feeds);
5492 size = l2arc_write_size();
5495 * Evict L2ARC buffers that will be overwritten.
5497 l2arc_evict(dev, size, B_FALSE);
5500 * Write ARC buffers.
5502 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5505 * Calculate interval between writes.
5507 next = l2arc_write_interval(begin, size, wrote);
5508 spa_config_exit(spa, SCL_L2ARC, dev);
5511 l2arc_thread_exit = 0;
5512 cv_broadcast(&l2arc_feed_thr_cv);
5513 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5518 l2arc_vdev_present(vdev_t *vd)
5522 mutex_enter(&l2arc_dev_mtx);
5523 for (dev = list_head(l2arc_dev_list); dev != NULL;
5524 dev = list_next(l2arc_dev_list, dev)) {
5525 if (dev->l2ad_vdev == vd)
5528 mutex_exit(&l2arc_dev_mtx);
5530 return (dev != NULL);
5534 * Add a vdev for use by the L2ARC. By this point the spa has already
5535 * validated the vdev and opened it.
5538 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5540 l2arc_dev_t *adddev;
5542 ASSERT(!l2arc_vdev_present(vd));
5544 vdev_ashift_optimize(vd);
5547 * Create a new l2arc device entry.
5549 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5550 adddev->l2ad_spa = spa;
5551 adddev->l2ad_vdev = vd;
5552 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5553 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5554 adddev->l2ad_hand = adddev->l2ad_start;
5555 adddev->l2ad_evict = adddev->l2ad_start;
5556 adddev->l2ad_first = B_TRUE;
5557 adddev->l2ad_writing = B_FALSE;
5560 * This is a list of all ARC buffers that are still valid on the
5563 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5564 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5565 offsetof(arc_buf_hdr_t, b_l2node));
5567 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5570 * Add device to global list
5572 mutex_enter(&l2arc_dev_mtx);
5573 list_insert_head(l2arc_dev_list, adddev);
5574 atomic_inc_64(&l2arc_ndev);
5575 mutex_exit(&l2arc_dev_mtx);
5579 * Remove a vdev from the L2ARC.
5582 l2arc_remove_vdev(vdev_t *vd)
5584 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5587 * Find the device by vdev
5589 mutex_enter(&l2arc_dev_mtx);
5590 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5591 nextdev = list_next(l2arc_dev_list, dev);
5592 if (vd == dev->l2ad_vdev) {
5597 ASSERT(remdev != NULL);
5600 * Remove device from global list
5602 list_remove(l2arc_dev_list, remdev);
5603 l2arc_dev_last = NULL; /* may have been invalidated */
5604 atomic_dec_64(&l2arc_ndev);
5605 mutex_exit(&l2arc_dev_mtx);
5608 * Clear all buflists and ARC references. L2ARC device flush.
5610 l2arc_evict(remdev, 0, B_TRUE);
5611 list_destroy(remdev->l2ad_buflist);
5612 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5613 kmem_free(remdev, sizeof (l2arc_dev_t));
5619 l2arc_thread_exit = 0;
5621 l2arc_writes_sent = 0;
5622 l2arc_writes_done = 0;
5624 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5625 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5626 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5627 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5628 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5630 l2arc_dev_list = &L2ARC_dev_list;
5631 l2arc_free_on_write = &L2ARC_free_on_write;
5632 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5633 offsetof(l2arc_dev_t, l2ad_node));
5634 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5635 offsetof(l2arc_data_free_t, l2df_list_node));
5642 * This is called from dmu_fini(), which is called from spa_fini();
5643 * Because of this, we can assume that all l2arc devices have
5644 * already been removed when the pools themselves were removed.
5647 l2arc_do_free_on_write();
5649 mutex_destroy(&l2arc_feed_thr_lock);
5650 cv_destroy(&l2arc_feed_thr_cv);
5651 mutex_destroy(&l2arc_dev_mtx);
5652 mutex_destroy(&l2arc_buflist_mtx);
5653 mutex_destroy(&l2arc_free_on_write_mtx);
5655 list_destroy(l2arc_dev_list);
5656 list_destroy(l2arc_free_on_write);
5662 if (!(spa_mode_global & FWRITE))
5665 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5666 TS_RUN, minclsyspri);
5672 if (!(spa_mode_global & FWRITE))
5675 mutex_enter(&l2arc_feed_thr_lock);
5676 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5677 l2arc_thread_exit = 1;
5678 while (l2arc_thread_exit != 0)
5679 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5680 mutex_exit(&l2arc_feed_thr_lock);