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) 2013 by Delphix. All rights reserved.
24 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25 * Copyright 2013 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_buf_evict()
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>
131 #include <sys/dnlc.h>
133 #include <sys/callb.h>
134 #include <sys/kstat.h>
135 #include <sys/trim_map.h>
136 #include <zfs_fletcher.h>
139 #include <vm/vm_pageout.h>
143 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
144 boolean_t arc_watch = B_FALSE;
149 static kmutex_t arc_reclaim_thr_lock;
150 static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
151 static uint8_t arc_thread_exit;
153 extern int zfs_write_limit_shift;
154 extern uint64_t zfs_write_limit_max;
155 extern kmutex_t zfs_write_limit_lock;
157 #define ARC_REDUCE_DNLC_PERCENT 3
158 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
160 typedef enum arc_reclaim_strategy {
161 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
162 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
163 } arc_reclaim_strategy_t;
165 /* number of seconds before growing cache again */
166 static int arc_grow_retry = 60;
168 /* shift of arc_c for calculating both min and max arc_p */
169 static int arc_p_min_shift = 4;
171 /* log2(fraction of arc to reclaim) */
172 static int arc_shrink_shift = 5;
175 * minimum lifespan of a prefetch block in clock ticks
176 * (initialized in arc_init())
178 static int arc_min_prefetch_lifespan;
181 extern int zfs_prefetch_disable;
184 * The arc has filled available memory and has now warmed up.
186 static boolean_t arc_warm;
189 * These tunables are for performance analysis.
191 uint64_t zfs_arc_max;
192 uint64_t zfs_arc_min;
193 uint64_t zfs_arc_meta_limit = 0;
194 int zfs_arc_grow_retry = 0;
195 int zfs_arc_shrink_shift = 0;
196 int zfs_arc_p_min_shift = 0;
197 int zfs_disable_dup_eviction = 0;
199 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
200 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
201 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
202 SYSCTL_DECL(_vfs_zfs);
203 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
205 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
209 * Note that buffers can be in one of 6 states:
210 * ARC_anon - anonymous (discussed below)
211 * ARC_mru - recently used, currently cached
212 * ARC_mru_ghost - recentely used, no longer in cache
213 * ARC_mfu - frequently used, currently cached
214 * ARC_mfu_ghost - frequently used, no longer in cache
215 * ARC_l2c_only - exists in L2ARC but not other states
216 * When there are no active references to the buffer, they are
217 * are linked onto a list in one of these arc states. These are
218 * the only buffers that can be evicted or deleted. Within each
219 * state there are multiple lists, one for meta-data and one for
220 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
221 * etc.) is tracked separately so that it can be managed more
222 * explicitly: favored over data, limited explicitly.
224 * Anonymous buffers are buffers that are not associated with
225 * a DVA. These are buffers that hold dirty block copies
226 * before they are written to stable storage. By definition,
227 * they are "ref'd" and are considered part of arc_mru
228 * that cannot be freed. Generally, they will aquire a DVA
229 * as they are written and migrate onto the arc_mru list.
231 * The ARC_l2c_only state is for buffers that are in the second
232 * level ARC but no longer in any of the ARC_m* lists. The second
233 * level ARC itself may also contain buffers that are in any of
234 * the ARC_m* states - meaning that a buffer can exist in two
235 * places. The reason for the ARC_l2c_only state is to keep the
236 * buffer header in the hash table, so that reads that hit the
237 * second level ARC benefit from these fast lookups.
240 #define ARCS_LOCK_PAD CACHE_LINE_SIZE
244 unsigned char pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
249 * must be power of two for mask use to work
252 #define ARC_BUFC_NUMDATALISTS 16
253 #define ARC_BUFC_NUMMETADATALISTS 16
254 #define ARC_BUFC_NUMLISTS (ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
256 typedef struct arc_state {
257 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
258 uint64_t arcs_size; /* total amount of data in this state */
259 list_t arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
260 struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
263 #define ARCS_LOCK(s, i) (&((s)->arcs_locks[(i)].arcs_lock))
266 static arc_state_t ARC_anon;
267 static arc_state_t ARC_mru;
268 static arc_state_t ARC_mru_ghost;
269 static arc_state_t ARC_mfu;
270 static arc_state_t ARC_mfu_ghost;
271 static arc_state_t ARC_l2c_only;
273 typedef struct arc_stats {
274 kstat_named_t arcstat_hits;
275 kstat_named_t arcstat_misses;
276 kstat_named_t arcstat_demand_data_hits;
277 kstat_named_t arcstat_demand_data_misses;
278 kstat_named_t arcstat_demand_metadata_hits;
279 kstat_named_t arcstat_demand_metadata_misses;
280 kstat_named_t arcstat_prefetch_data_hits;
281 kstat_named_t arcstat_prefetch_data_misses;
282 kstat_named_t arcstat_prefetch_metadata_hits;
283 kstat_named_t arcstat_prefetch_metadata_misses;
284 kstat_named_t arcstat_mru_hits;
285 kstat_named_t arcstat_mru_ghost_hits;
286 kstat_named_t arcstat_mfu_hits;
287 kstat_named_t arcstat_mfu_ghost_hits;
288 kstat_named_t arcstat_allocated;
289 kstat_named_t arcstat_deleted;
290 kstat_named_t arcstat_stolen;
291 kstat_named_t arcstat_recycle_miss;
293 * Number of buffers that could not be evicted because the hash lock
294 * was held by another thread. The lock may not necessarily be held
295 * by something using the same buffer, since hash locks are shared
296 * by multiple buffers.
298 kstat_named_t arcstat_mutex_miss;
300 * Number of buffers skipped because they have I/O in progress, are
301 * indrect prefetch buffers that have not lived long enough, or are
302 * not from the spa we're trying to evict from.
304 kstat_named_t arcstat_evict_skip;
305 kstat_named_t arcstat_evict_l2_cached;
306 kstat_named_t arcstat_evict_l2_eligible;
307 kstat_named_t arcstat_evict_l2_ineligible;
308 kstat_named_t arcstat_hash_elements;
309 kstat_named_t arcstat_hash_elements_max;
310 kstat_named_t arcstat_hash_collisions;
311 kstat_named_t arcstat_hash_chains;
312 kstat_named_t arcstat_hash_chain_max;
313 kstat_named_t arcstat_p;
314 kstat_named_t arcstat_c;
315 kstat_named_t arcstat_c_min;
316 kstat_named_t arcstat_c_max;
317 kstat_named_t arcstat_size;
318 kstat_named_t arcstat_hdr_size;
319 kstat_named_t arcstat_data_size;
320 kstat_named_t arcstat_other_size;
321 kstat_named_t arcstat_l2_hits;
322 kstat_named_t arcstat_l2_misses;
323 kstat_named_t arcstat_l2_feeds;
324 kstat_named_t arcstat_l2_rw_clash;
325 kstat_named_t arcstat_l2_read_bytes;
326 kstat_named_t arcstat_l2_write_bytes;
327 kstat_named_t arcstat_l2_writes_sent;
328 kstat_named_t arcstat_l2_writes_done;
329 kstat_named_t arcstat_l2_writes_error;
330 kstat_named_t arcstat_l2_writes_hdr_miss;
331 kstat_named_t arcstat_l2_evict_lock_retry;
332 kstat_named_t arcstat_l2_evict_reading;
333 kstat_named_t arcstat_l2_free_on_write;
334 kstat_named_t arcstat_l2_abort_lowmem;
335 kstat_named_t arcstat_l2_cksum_bad;
336 kstat_named_t arcstat_l2_io_error;
337 kstat_named_t arcstat_l2_size;
338 kstat_named_t arcstat_l2_asize;
339 kstat_named_t arcstat_l2_hdr_size;
340 kstat_named_t arcstat_l2_compress_successes;
341 kstat_named_t arcstat_l2_compress_zeros;
342 kstat_named_t arcstat_l2_compress_failures;
343 kstat_named_t arcstat_l2_write_trylock_fail;
344 kstat_named_t arcstat_l2_write_passed_headroom;
345 kstat_named_t arcstat_l2_write_spa_mismatch;
346 kstat_named_t arcstat_l2_write_in_l2;
347 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
348 kstat_named_t arcstat_l2_write_not_cacheable;
349 kstat_named_t arcstat_l2_write_full;
350 kstat_named_t arcstat_l2_write_buffer_iter;
351 kstat_named_t arcstat_l2_write_pios;
352 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
353 kstat_named_t arcstat_l2_write_buffer_list_iter;
354 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
355 kstat_named_t arcstat_memory_throttle_count;
356 kstat_named_t arcstat_duplicate_buffers;
357 kstat_named_t arcstat_duplicate_buffers_size;
358 kstat_named_t arcstat_duplicate_reads;
361 static arc_stats_t arc_stats = {
362 { "hits", KSTAT_DATA_UINT64 },
363 { "misses", KSTAT_DATA_UINT64 },
364 { "demand_data_hits", KSTAT_DATA_UINT64 },
365 { "demand_data_misses", KSTAT_DATA_UINT64 },
366 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
367 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
368 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
369 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
370 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
371 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
372 { "mru_hits", KSTAT_DATA_UINT64 },
373 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
374 { "mfu_hits", KSTAT_DATA_UINT64 },
375 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
376 { "allocated", KSTAT_DATA_UINT64 },
377 { "deleted", KSTAT_DATA_UINT64 },
378 { "stolen", KSTAT_DATA_UINT64 },
379 { "recycle_miss", KSTAT_DATA_UINT64 },
380 { "mutex_miss", KSTAT_DATA_UINT64 },
381 { "evict_skip", KSTAT_DATA_UINT64 },
382 { "evict_l2_cached", KSTAT_DATA_UINT64 },
383 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
384 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
385 { "hash_elements", KSTAT_DATA_UINT64 },
386 { "hash_elements_max", KSTAT_DATA_UINT64 },
387 { "hash_collisions", KSTAT_DATA_UINT64 },
388 { "hash_chains", KSTAT_DATA_UINT64 },
389 { "hash_chain_max", KSTAT_DATA_UINT64 },
390 { "p", KSTAT_DATA_UINT64 },
391 { "c", KSTAT_DATA_UINT64 },
392 { "c_min", KSTAT_DATA_UINT64 },
393 { "c_max", KSTAT_DATA_UINT64 },
394 { "size", KSTAT_DATA_UINT64 },
395 { "hdr_size", KSTAT_DATA_UINT64 },
396 { "data_size", KSTAT_DATA_UINT64 },
397 { "other_size", KSTAT_DATA_UINT64 },
398 { "l2_hits", KSTAT_DATA_UINT64 },
399 { "l2_misses", KSTAT_DATA_UINT64 },
400 { "l2_feeds", KSTAT_DATA_UINT64 },
401 { "l2_rw_clash", KSTAT_DATA_UINT64 },
402 { "l2_read_bytes", KSTAT_DATA_UINT64 },
403 { "l2_write_bytes", KSTAT_DATA_UINT64 },
404 { "l2_writes_sent", KSTAT_DATA_UINT64 },
405 { "l2_writes_done", KSTAT_DATA_UINT64 },
406 { "l2_writes_error", KSTAT_DATA_UINT64 },
407 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
408 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
409 { "l2_evict_reading", KSTAT_DATA_UINT64 },
410 { "l2_free_on_write", KSTAT_DATA_UINT64 },
411 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
412 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
413 { "l2_io_error", KSTAT_DATA_UINT64 },
414 { "l2_size", KSTAT_DATA_UINT64 },
415 { "l2_asize", KSTAT_DATA_UINT64 },
416 { "l2_hdr_size", KSTAT_DATA_UINT64 },
417 { "l2_compress_successes", KSTAT_DATA_UINT64 },
418 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
419 { "l2_compress_failures", KSTAT_DATA_UINT64 },
420 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
421 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
422 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
423 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
424 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
425 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
426 { "l2_write_full", KSTAT_DATA_UINT64 },
427 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
428 { "l2_write_pios", KSTAT_DATA_UINT64 },
429 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
430 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
431 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
432 { "memory_throttle_count", KSTAT_DATA_UINT64 },
433 { "duplicate_buffers", KSTAT_DATA_UINT64 },
434 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
435 { "duplicate_reads", KSTAT_DATA_UINT64 }
438 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
440 #define ARCSTAT_INCR(stat, val) \
441 atomic_add_64(&arc_stats.stat.value.ui64, (val))
443 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
444 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
446 #define ARCSTAT_MAX(stat, val) { \
448 while ((val) > (m = arc_stats.stat.value.ui64) && \
449 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
453 #define ARCSTAT_MAXSTAT(stat) \
454 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
457 * We define a macro to allow ARC hits/misses to be easily broken down by
458 * two separate conditions, giving a total of four different subtypes for
459 * each of hits and misses (so eight statistics total).
461 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
464 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
466 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
470 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
472 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
477 static arc_state_t *arc_anon;
478 static arc_state_t *arc_mru;
479 static arc_state_t *arc_mru_ghost;
480 static arc_state_t *arc_mfu;
481 static arc_state_t *arc_mfu_ghost;
482 static arc_state_t *arc_l2c_only;
485 * There are several ARC variables that are critical to export as kstats --
486 * but we don't want to have to grovel around in the kstat whenever we wish to
487 * manipulate them. For these variables, we therefore define them to be in
488 * terms of the statistic variable. This assures that we are not introducing
489 * the possibility of inconsistency by having shadow copies of the variables,
490 * while still allowing the code to be readable.
492 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
493 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
494 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
495 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
496 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
498 #define L2ARC_IS_VALID_COMPRESS(_c_) \
499 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
501 static int arc_no_grow; /* Don't try to grow cache size */
502 static uint64_t arc_tempreserve;
503 static uint64_t arc_loaned_bytes;
504 static uint64_t arc_meta_used;
505 static uint64_t arc_meta_limit;
506 static uint64_t arc_meta_max = 0;
507 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_used, CTLFLAG_RD, &arc_meta_used, 0,
508 "ARC metadata used");
509 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_limit, CTLFLAG_RW, &arc_meta_limit, 0,
510 "ARC metadata limit");
512 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
514 typedef struct arc_callback arc_callback_t;
516 struct arc_callback {
518 arc_done_func_t *acb_done;
520 zio_t *acb_zio_dummy;
521 arc_callback_t *acb_next;
524 typedef struct arc_write_callback arc_write_callback_t;
526 struct arc_write_callback {
528 arc_done_func_t *awcb_ready;
529 arc_done_func_t *awcb_done;
534 /* protected by hash lock */
539 kmutex_t b_freeze_lock;
540 zio_cksum_t *b_freeze_cksum;
543 arc_buf_hdr_t *b_hash_next;
548 arc_callback_t *b_acb;
552 arc_buf_contents_t b_type;
556 /* protected by arc state mutex */
557 arc_state_t *b_state;
558 list_node_t b_arc_node;
560 /* updated atomically */
561 clock_t b_arc_access;
563 /* self protecting */
566 l2arc_buf_hdr_t *b_l2hdr;
567 list_node_t b_l2node;
570 static arc_buf_t *arc_eviction_list;
571 static kmutex_t arc_eviction_mtx;
572 static arc_buf_hdr_t arc_eviction_hdr;
573 static void arc_get_data_buf(arc_buf_t *buf);
574 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
575 static int arc_evict_needed(arc_buf_contents_t type);
576 static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes);
578 static void arc_buf_watch(arc_buf_t *buf);
581 static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
583 #define GHOST_STATE(state) \
584 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
585 (state) == arc_l2c_only)
588 * Private ARC flags. These flags are private ARC only flags that will show up
589 * in b_flags in the arc_hdr_buf_t. Some flags are publicly declared, and can
590 * be passed in as arc_flags in things like arc_read. However, these flags
591 * should never be passed and should only be set by ARC code. When adding new
592 * public flags, make sure not to smash the private ones.
595 #define ARC_IN_HASH_TABLE (1 << 9) /* this buffer is hashed */
596 #define ARC_IO_IN_PROGRESS (1 << 10) /* I/O in progress for buf */
597 #define ARC_IO_ERROR (1 << 11) /* I/O failed for buf */
598 #define ARC_FREED_IN_READ (1 << 12) /* buf freed while in read */
599 #define ARC_BUF_AVAILABLE (1 << 13) /* block not in active use */
600 #define ARC_INDIRECT (1 << 14) /* this is an indirect block */
601 #define ARC_FREE_IN_PROGRESS (1 << 15) /* hdr about to be freed */
602 #define ARC_L2_WRITING (1 << 16) /* L2ARC write in progress */
603 #define ARC_L2_EVICTED (1 << 17) /* evicted during I/O */
604 #define ARC_L2_WRITE_HEAD (1 << 18) /* head of write list */
606 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_IN_HASH_TABLE)
607 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS)
608 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_IO_ERROR)
609 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_PREFETCH)
610 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FREED_IN_READ)
611 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_BUF_AVAILABLE)
612 #define HDR_FREE_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
613 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_L2CACHE)
614 #define HDR_L2_READING(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS && \
615 (hdr)->b_l2hdr != NULL)
616 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_L2_WRITING)
617 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_L2_EVICTED)
618 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_L2_WRITE_HEAD)
624 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
625 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
628 * Hash table routines
631 #define HT_LOCK_PAD CACHE_LINE_SIZE
636 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
640 #define BUF_LOCKS 256
641 typedef struct buf_hash_table {
643 arc_buf_hdr_t **ht_table;
644 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
647 static buf_hash_table_t buf_hash_table;
649 #define BUF_HASH_INDEX(spa, dva, birth) \
650 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
651 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
652 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
653 #define HDR_LOCK(hdr) \
654 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
656 uint64_t zfs_crc64_table[256];
662 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
663 #define L2ARC_HEADROOM 2 /* num of writes */
665 * If we discover during ARC scan any buffers to be compressed, we boost
666 * our headroom for the next scanning cycle by this percentage multiple.
668 #define L2ARC_HEADROOM_BOOST 200
669 #define L2ARC_FEED_SECS 1 /* caching interval secs */
670 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
672 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
673 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
675 /* L2ARC Performance Tunables */
676 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
677 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
678 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
679 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
680 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
681 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
682 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
683 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
684 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
686 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
687 &l2arc_write_max, 0, "max write size");
688 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
689 &l2arc_write_boost, 0, "extra write during warmup");
690 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
691 &l2arc_headroom, 0, "number of dev writes");
692 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
693 &l2arc_feed_secs, 0, "interval seconds");
694 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
695 &l2arc_feed_min_ms, 0, "min interval milliseconds");
697 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
698 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
699 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
700 &l2arc_feed_again, 0, "turbo warmup");
701 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
702 &l2arc_norw, 0, "no reads during writes");
704 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
705 &ARC_anon.arcs_size, 0, "size of anonymous state");
706 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
707 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
708 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
709 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
711 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
712 &ARC_mru.arcs_size, 0, "size of mru state");
713 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
714 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
715 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
716 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
718 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
719 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
720 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
721 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
722 "size of metadata in mru ghost state");
723 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
724 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
725 "size of data in mru ghost state");
727 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
728 &ARC_mfu.arcs_size, 0, "size of mfu state");
729 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
730 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
731 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
732 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
734 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
735 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
736 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
737 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
738 "size of metadata in mfu ghost state");
739 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
740 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
741 "size of data in mfu ghost state");
743 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
744 &ARC_l2c_only.arcs_size, 0, "size of mru state");
749 typedef struct l2arc_dev {
750 vdev_t *l2ad_vdev; /* vdev */
751 spa_t *l2ad_spa; /* spa */
752 uint64_t l2ad_hand; /* next write location */
753 uint64_t l2ad_start; /* first addr on device */
754 uint64_t l2ad_end; /* last addr on device */
755 uint64_t l2ad_evict; /* last addr eviction reached */
756 boolean_t l2ad_first; /* first sweep through */
757 boolean_t l2ad_writing; /* currently writing */
758 list_t *l2ad_buflist; /* buffer list */
759 list_node_t l2ad_node; /* device list node */
762 static list_t L2ARC_dev_list; /* device list */
763 static list_t *l2arc_dev_list; /* device list pointer */
764 static kmutex_t l2arc_dev_mtx; /* device list mutex */
765 static l2arc_dev_t *l2arc_dev_last; /* last device used */
766 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
767 static list_t L2ARC_free_on_write; /* free after write buf list */
768 static list_t *l2arc_free_on_write; /* free after write list ptr */
769 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
770 static uint64_t l2arc_ndev; /* number of devices */
772 typedef struct l2arc_read_callback {
773 arc_buf_t *l2rcb_buf; /* read buffer */
774 spa_t *l2rcb_spa; /* spa */
775 blkptr_t l2rcb_bp; /* original blkptr */
776 zbookmark_t l2rcb_zb; /* original bookmark */
777 int l2rcb_flags; /* original flags */
778 enum zio_compress l2rcb_compress; /* applied compress */
779 } l2arc_read_callback_t;
781 typedef struct l2arc_write_callback {
782 l2arc_dev_t *l2wcb_dev; /* device info */
783 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
784 } l2arc_write_callback_t;
786 struct l2arc_buf_hdr {
787 /* protected by arc_buf_hdr mutex */
788 l2arc_dev_t *b_dev; /* L2ARC device */
789 uint64_t b_daddr; /* disk address, offset byte */
790 /* compression applied to buffer data */
791 enum zio_compress b_compress;
792 /* real alloc'd buffer size depending on b_compress applied */
794 /* temporary buffer holder for in-flight compressed data */
798 typedef struct l2arc_data_free {
799 /* protected by l2arc_free_on_write_mtx */
802 void (*l2df_func)(void *, size_t);
803 list_node_t l2df_list_node;
806 static kmutex_t l2arc_feed_thr_lock;
807 static kcondvar_t l2arc_feed_thr_cv;
808 static uint8_t l2arc_thread_exit;
810 static void l2arc_read_done(zio_t *zio);
811 static void l2arc_hdr_stat_add(void);
812 static void l2arc_hdr_stat_remove(void);
814 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
815 static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
816 enum zio_compress c);
817 static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
820 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
822 uint8_t *vdva = (uint8_t *)dva;
823 uint64_t crc = -1ULL;
826 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
828 for (i = 0; i < sizeof (dva_t); i++)
829 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
831 crc ^= (spa>>8) ^ birth;
836 #define BUF_EMPTY(buf) \
837 ((buf)->b_dva.dva_word[0] == 0 && \
838 (buf)->b_dva.dva_word[1] == 0 && \
841 #define BUF_EQUAL(spa, dva, birth, buf) \
842 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
843 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
844 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
847 buf_discard_identity(arc_buf_hdr_t *hdr)
849 hdr->b_dva.dva_word[0] = 0;
850 hdr->b_dva.dva_word[1] = 0;
855 static arc_buf_hdr_t *
856 buf_hash_find(uint64_t spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
858 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
859 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
862 mutex_enter(hash_lock);
863 for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
864 buf = buf->b_hash_next) {
865 if (BUF_EQUAL(spa, dva, birth, buf)) {
870 mutex_exit(hash_lock);
876 * Insert an entry into the hash table. If there is already an element
877 * equal to elem in the hash table, then the already existing element
878 * will be returned and the new element will not be inserted.
879 * Otherwise returns NULL.
881 static arc_buf_hdr_t *
882 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
884 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
885 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
889 ASSERT(!HDR_IN_HASH_TABLE(buf));
891 mutex_enter(hash_lock);
892 for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
893 fbuf = fbuf->b_hash_next, i++) {
894 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
898 buf->b_hash_next = buf_hash_table.ht_table[idx];
899 buf_hash_table.ht_table[idx] = buf;
900 buf->b_flags |= ARC_IN_HASH_TABLE;
902 /* collect some hash table performance data */
904 ARCSTAT_BUMP(arcstat_hash_collisions);
906 ARCSTAT_BUMP(arcstat_hash_chains);
908 ARCSTAT_MAX(arcstat_hash_chain_max, i);
911 ARCSTAT_BUMP(arcstat_hash_elements);
912 ARCSTAT_MAXSTAT(arcstat_hash_elements);
918 buf_hash_remove(arc_buf_hdr_t *buf)
920 arc_buf_hdr_t *fbuf, **bufp;
921 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
923 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
924 ASSERT(HDR_IN_HASH_TABLE(buf));
926 bufp = &buf_hash_table.ht_table[idx];
927 while ((fbuf = *bufp) != buf) {
928 ASSERT(fbuf != NULL);
929 bufp = &fbuf->b_hash_next;
931 *bufp = buf->b_hash_next;
932 buf->b_hash_next = NULL;
933 buf->b_flags &= ~ARC_IN_HASH_TABLE;
935 /* collect some hash table performance data */
936 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
938 if (buf_hash_table.ht_table[idx] &&
939 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
940 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
944 * Global data structures and functions for the buf kmem cache.
946 static kmem_cache_t *hdr_cache;
947 static kmem_cache_t *buf_cache;
954 kmem_free(buf_hash_table.ht_table,
955 (buf_hash_table.ht_mask + 1) * sizeof (void *));
956 for (i = 0; i < BUF_LOCKS; i++)
957 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
958 kmem_cache_destroy(hdr_cache);
959 kmem_cache_destroy(buf_cache);
963 * Constructor callback - called when the cache is empty
964 * and a new buf is requested.
968 hdr_cons(void *vbuf, void *unused, int kmflag)
970 arc_buf_hdr_t *buf = vbuf;
972 bzero(buf, sizeof (arc_buf_hdr_t));
973 refcount_create(&buf->b_refcnt);
974 cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
975 mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
976 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
983 buf_cons(void *vbuf, void *unused, int kmflag)
985 arc_buf_t *buf = vbuf;
987 bzero(buf, sizeof (arc_buf_t));
988 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
989 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
995 * Destructor callback - called when a cached buf is
996 * no longer required.
1000 hdr_dest(void *vbuf, void *unused)
1002 arc_buf_hdr_t *buf = vbuf;
1004 ASSERT(BUF_EMPTY(buf));
1005 refcount_destroy(&buf->b_refcnt);
1006 cv_destroy(&buf->b_cv);
1007 mutex_destroy(&buf->b_freeze_lock);
1008 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1013 buf_dest(void *vbuf, void *unused)
1015 arc_buf_t *buf = vbuf;
1017 mutex_destroy(&buf->b_evict_lock);
1018 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1022 * Reclaim callback -- invoked when memory is low.
1026 hdr_recl(void *unused)
1028 dprintf("hdr_recl called\n");
1030 * umem calls the reclaim func when we destroy the buf cache,
1031 * which is after we do arc_fini().
1034 cv_signal(&arc_reclaim_thr_cv);
1041 uint64_t hsize = 1ULL << 12;
1045 * The hash table is big enough to fill all of physical memory
1046 * with an average 64K block size. The table will take up
1047 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
1049 while (hsize * 65536 < (uint64_t)physmem * PAGESIZE)
1052 buf_hash_table.ht_mask = hsize - 1;
1053 buf_hash_table.ht_table =
1054 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1055 if (buf_hash_table.ht_table == NULL) {
1056 ASSERT(hsize > (1ULL << 8));
1061 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1062 0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1063 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1064 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1066 for (i = 0; i < 256; i++)
1067 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1068 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1070 for (i = 0; i < BUF_LOCKS; i++) {
1071 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1072 NULL, MUTEX_DEFAULT, NULL);
1076 #define ARC_MINTIME (hz>>4) /* 62 ms */
1079 arc_cksum_verify(arc_buf_t *buf)
1083 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1086 mutex_enter(&buf->b_hdr->b_freeze_lock);
1087 if (buf->b_hdr->b_freeze_cksum == NULL ||
1088 (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1089 mutex_exit(&buf->b_hdr->b_freeze_lock);
1092 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1093 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1094 panic("buffer modified while frozen!");
1095 mutex_exit(&buf->b_hdr->b_freeze_lock);
1099 arc_cksum_equal(arc_buf_t *buf)
1104 mutex_enter(&buf->b_hdr->b_freeze_lock);
1105 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1106 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1107 mutex_exit(&buf->b_hdr->b_freeze_lock);
1113 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1115 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1118 mutex_enter(&buf->b_hdr->b_freeze_lock);
1119 if (buf->b_hdr->b_freeze_cksum != NULL) {
1120 mutex_exit(&buf->b_hdr->b_freeze_lock);
1123 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1124 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1125 buf->b_hdr->b_freeze_cksum);
1126 mutex_exit(&buf->b_hdr->b_freeze_lock);
1129 #endif /* illumos */
1134 typedef struct procctl {
1142 arc_buf_unwatch(arc_buf_t *buf)
1149 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1150 ctl.prwatch.pr_size = 0;
1151 ctl.prwatch.pr_wflags = 0;
1152 result = write(arc_procfd, &ctl, sizeof (ctl));
1153 ASSERT3U(result, ==, sizeof (ctl));
1160 arc_buf_watch(arc_buf_t *buf)
1167 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1168 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1169 ctl.prwatch.pr_wflags = WA_WRITE;
1170 result = write(arc_procfd, &ctl, sizeof (ctl));
1171 ASSERT3U(result, ==, sizeof (ctl));
1175 #endif /* illumos */
1178 arc_buf_thaw(arc_buf_t *buf)
1180 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1181 if (buf->b_hdr->b_state != arc_anon)
1182 panic("modifying non-anon buffer!");
1183 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1184 panic("modifying buffer while i/o in progress!");
1185 arc_cksum_verify(buf);
1188 mutex_enter(&buf->b_hdr->b_freeze_lock);
1189 if (buf->b_hdr->b_freeze_cksum != NULL) {
1190 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1191 buf->b_hdr->b_freeze_cksum = NULL;
1194 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1195 if (buf->b_hdr->b_thawed)
1196 kmem_free(buf->b_hdr->b_thawed, 1);
1197 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1200 mutex_exit(&buf->b_hdr->b_freeze_lock);
1203 arc_buf_unwatch(buf);
1204 #endif /* illumos */
1208 arc_buf_freeze(arc_buf_t *buf)
1210 kmutex_t *hash_lock;
1212 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1215 hash_lock = HDR_LOCK(buf->b_hdr);
1216 mutex_enter(hash_lock);
1218 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1219 buf->b_hdr->b_state == arc_anon);
1220 arc_cksum_compute(buf, B_FALSE);
1221 mutex_exit(hash_lock);
1226 get_buf_info(arc_buf_hdr_t *ab, arc_state_t *state, list_t **list, kmutex_t **lock)
1228 uint64_t buf_hashid = buf_hash(ab->b_spa, &ab->b_dva, ab->b_birth);
1230 if (ab->b_type == ARC_BUFC_METADATA)
1231 buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1233 buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1234 buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1237 *list = &state->arcs_lists[buf_hashid];
1238 *lock = ARCS_LOCK(state, buf_hashid);
1243 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1245 ASSERT(MUTEX_HELD(hash_lock));
1247 if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1248 (ab->b_state != arc_anon)) {
1249 uint64_t delta = ab->b_size * ab->b_datacnt;
1250 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1254 get_buf_info(ab, ab->b_state, &list, &lock);
1255 ASSERT(!MUTEX_HELD(lock));
1257 ASSERT(list_link_active(&ab->b_arc_node));
1258 list_remove(list, ab);
1259 if (GHOST_STATE(ab->b_state)) {
1260 ASSERT0(ab->b_datacnt);
1261 ASSERT3P(ab->b_buf, ==, NULL);
1265 ASSERT3U(*size, >=, delta);
1266 atomic_add_64(size, -delta);
1268 /* remove the prefetch flag if we get a reference */
1269 if (ab->b_flags & ARC_PREFETCH)
1270 ab->b_flags &= ~ARC_PREFETCH;
1275 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1278 arc_state_t *state = ab->b_state;
1280 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1281 ASSERT(!GHOST_STATE(state));
1283 if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1284 (state != arc_anon)) {
1285 uint64_t *size = &state->arcs_lsize[ab->b_type];
1289 get_buf_info(ab, state, &list, &lock);
1290 ASSERT(!MUTEX_HELD(lock));
1292 ASSERT(!list_link_active(&ab->b_arc_node));
1293 list_insert_head(list, ab);
1294 ASSERT(ab->b_datacnt > 0);
1295 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1302 * Move the supplied buffer to the indicated state. The mutex
1303 * for the buffer must be held by the caller.
1306 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1308 arc_state_t *old_state = ab->b_state;
1309 int64_t refcnt = refcount_count(&ab->b_refcnt);
1310 uint64_t from_delta, to_delta;
1314 ASSERT(MUTEX_HELD(hash_lock));
1315 ASSERT(new_state != old_state);
1316 ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1317 ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1318 ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1320 from_delta = to_delta = ab->b_datacnt * ab->b_size;
1323 * If this buffer is evictable, transfer it from the
1324 * old state list to the new state list.
1327 if (old_state != arc_anon) {
1329 uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1331 get_buf_info(ab, old_state, &list, &lock);
1332 use_mutex = !MUTEX_HELD(lock);
1336 ASSERT(list_link_active(&ab->b_arc_node));
1337 list_remove(list, ab);
1340 * If prefetching out of the ghost cache,
1341 * we will have a non-zero datacnt.
1343 if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1344 /* ghost elements have a ghost size */
1345 ASSERT(ab->b_buf == NULL);
1346 from_delta = ab->b_size;
1348 ASSERT3U(*size, >=, from_delta);
1349 atomic_add_64(size, -from_delta);
1354 if (new_state != arc_anon) {
1356 uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1358 get_buf_info(ab, new_state, &list, &lock);
1359 use_mutex = !MUTEX_HELD(lock);
1363 list_insert_head(list, ab);
1365 /* ghost elements have a ghost size */
1366 if (GHOST_STATE(new_state)) {
1367 ASSERT(ab->b_datacnt == 0);
1368 ASSERT(ab->b_buf == NULL);
1369 to_delta = ab->b_size;
1371 atomic_add_64(size, to_delta);
1378 ASSERT(!BUF_EMPTY(ab));
1379 if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1380 buf_hash_remove(ab);
1382 /* adjust state sizes */
1384 atomic_add_64(&new_state->arcs_size, to_delta);
1386 ASSERT3U(old_state->arcs_size, >=, from_delta);
1387 atomic_add_64(&old_state->arcs_size, -from_delta);
1389 ab->b_state = new_state;
1391 /* adjust l2arc hdr stats */
1392 if (new_state == arc_l2c_only)
1393 l2arc_hdr_stat_add();
1394 else if (old_state == arc_l2c_only)
1395 l2arc_hdr_stat_remove();
1399 arc_space_consume(uint64_t space, arc_space_type_t type)
1401 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1404 case ARC_SPACE_DATA:
1405 ARCSTAT_INCR(arcstat_data_size, space);
1407 case ARC_SPACE_OTHER:
1408 ARCSTAT_INCR(arcstat_other_size, space);
1410 case ARC_SPACE_HDRS:
1411 ARCSTAT_INCR(arcstat_hdr_size, space);
1413 case ARC_SPACE_L2HDRS:
1414 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1418 atomic_add_64(&arc_meta_used, space);
1419 atomic_add_64(&arc_size, space);
1423 arc_space_return(uint64_t space, arc_space_type_t type)
1425 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1428 case ARC_SPACE_DATA:
1429 ARCSTAT_INCR(arcstat_data_size, -space);
1431 case ARC_SPACE_OTHER:
1432 ARCSTAT_INCR(arcstat_other_size, -space);
1434 case ARC_SPACE_HDRS:
1435 ARCSTAT_INCR(arcstat_hdr_size, -space);
1437 case ARC_SPACE_L2HDRS:
1438 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1442 ASSERT(arc_meta_used >= space);
1443 if (arc_meta_max < arc_meta_used)
1444 arc_meta_max = arc_meta_used;
1445 atomic_add_64(&arc_meta_used, -space);
1446 ASSERT(arc_size >= space);
1447 atomic_add_64(&arc_size, -space);
1451 arc_data_buf_alloc(uint64_t size)
1453 if (arc_evict_needed(ARC_BUFC_DATA))
1454 cv_signal(&arc_reclaim_thr_cv);
1455 atomic_add_64(&arc_size, size);
1456 return (zio_data_buf_alloc(size));
1460 arc_data_buf_free(void *buf, uint64_t size)
1462 zio_data_buf_free(buf, size);
1463 ASSERT(arc_size >= size);
1464 atomic_add_64(&arc_size, -size);
1468 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1473 ASSERT3U(size, >, 0);
1474 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1475 ASSERT(BUF_EMPTY(hdr));
1478 hdr->b_spa = spa_load_guid(spa);
1479 hdr->b_state = arc_anon;
1480 hdr->b_arc_access = 0;
1481 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1484 buf->b_efunc = NULL;
1485 buf->b_private = NULL;
1488 arc_get_data_buf(buf);
1491 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1492 (void) refcount_add(&hdr->b_refcnt, tag);
1497 static char *arc_onloan_tag = "onloan";
1500 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1501 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1502 * buffers must be returned to the arc before they can be used by the DMU or
1506 arc_loan_buf(spa_t *spa, int size)
1510 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1512 atomic_add_64(&arc_loaned_bytes, size);
1517 * Return a loaned arc buffer to the arc.
1520 arc_return_buf(arc_buf_t *buf, void *tag)
1522 arc_buf_hdr_t *hdr = buf->b_hdr;
1524 ASSERT(buf->b_data != NULL);
1525 (void) refcount_add(&hdr->b_refcnt, tag);
1526 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1528 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1531 /* Detach an arc_buf from a dbuf (tag) */
1533 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1537 ASSERT(buf->b_data != NULL);
1539 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1540 (void) refcount_remove(&hdr->b_refcnt, tag);
1541 buf->b_efunc = NULL;
1542 buf->b_private = NULL;
1544 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1548 arc_buf_clone(arc_buf_t *from)
1551 arc_buf_hdr_t *hdr = from->b_hdr;
1552 uint64_t size = hdr->b_size;
1554 ASSERT(hdr->b_state != arc_anon);
1556 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1559 buf->b_efunc = NULL;
1560 buf->b_private = NULL;
1561 buf->b_next = hdr->b_buf;
1563 arc_get_data_buf(buf);
1564 bcopy(from->b_data, buf->b_data, size);
1567 * This buffer already exists in the arc so create a duplicate
1568 * copy for the caller. If the buffer is associated with user data
1569 * then track the size and number of duplicates. These stats will be
1570 * updated as duplicate buffers are created and destroyed.
1572 if (hdr->b_type == ARC_BUFC_DATA) {
1573 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1574 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1576 hdr->b_datacnt += 1;
1581 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1584 kmutex_t *hash_lock;
1587 * Check to see if this buffer is evicted. Callers
1588 * must verify b_data != NULL to know if the add_ref
1591 mutex_enter(&buf->b_evict_lock);
1592 if (buf->b_data == NULL) {
1593 mutex_exit(&buf->b_evict_lock);
1596 hash_lock = HDR_LOCK(buf->b_hdr);
1597 mutex_enter(hash_lock);
1599 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1600 mutex_exit(&buf->b_evict_lock);
1602 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1603 add_reference(hdr, hash_lock, tag);
1604 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1605 arc_access(hdr, hash_lock);
1606 mutex_exit(hash_lock);
1607 ARCSTAT_BUMP(arcstat_hits);
1608 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1609 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1610 data, metadata, hits);
1614 * Free the arc data buffer. If it is an l2arc write in progress,
1615 * the buffer is placed on l2arc_free_on_write to be freed later.
1618 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1620 arc_buf_hdr_t *hdr = buf->b_hdr;
1622 if (HDR_L2_WRITING(hdr)) {
1623 l2arc_data_free_t *df;
1624 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1625 df->l2df_data = buf->b_data;
1626 df->l2df_size = hdr->b_size;
1627 df->l2df_func = free_func;
1628 mutex_enter(&l2arc_free_on_write_mtx);
1629 list_insert_head(l2arc_free_on_write, df);
1630 mutex_exit(&l2arc_free_on_write_mtx);
1631 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1633 free_func(buf->b_data, hdr->b_size);
1638 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
1642 /* free up data associated with the buf */
1644 arc_state_t *state = buf->b_hdr->b_state;
1645 uint64_t size = buf->b_hdr->b_size;
1646 arc_buf_contents_t type = buf->b_hdr->b_type;
1648 arc_cksum_verify(buf);
1650 arc_buf_unwatch(buf);
1651 #endif /* illumos */
1654 if (type == ARC_BUFC_METADATA) {
1655 arc_buf_data_free(buf, zio_buf_free);
1656 arc_space_return(size, ARC_SPACE_DATA);
1658 ASSERT(type == ARC_BUFC_DATA);
1659 arc_buf_data_free(buf, zio_data_buf_free);
1660 ARCSTAT_INCR(arcstat_data_size, -size);
1661 atomic_add_64(&arc_size, -size);
1664 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1665 uint64_t *cnt = &state->arcs_lsize[type];
1667 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1668 ASSERT(state != arc_anon);
1670 ASSERT3U(*cnt, >=, size);
1671 atomic_add_64(cnt, -size);
1673 ASSERT3U(state->arcs_size, >=, size);
1674 atomic_add_64(&state->arcs_size, -size);
1678 * If we're destroying a duplicate buffer make sure
1679 * that the appropriate statistics are updated.
1681 if (buf->b_hdr->b_datacnt > 1 &&
1682 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1683 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1684 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1686 ASSERT(buf->b_hdr->b_datacnt > 0);
1687 buf->b_hdr->b_datacnt -= 1;
1690 /* only remove the buf if requested */
1694 /* remove the buf from the hdr list */
1695 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1697 *bufp = buf->b_next;
1700 ASSERT(buf->b_efunc == NULL);
1702 /* clean up the buf */
1704 kmem_cache_free(buf_cache, buf);
1708 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1710 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1711 ASSERT3P(hdr->b_state, ==, arc_anon);
1712 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1713 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1715 if (l2hdr != NULL) {
1716 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1718 * To prevent arc_free() and l2arc_evict() from
1719 * attempting to free the same buffer at the same time,
1720 * a FREE_IN_PROGRESS flag is given to arc_free() to
1721 * give it priority. l2arc_evict() can't destroy this
1722 * header while we are waiting on l2arc_buflist_mtx.
1724 * The hdr may be removed from l2ad_buflist before we
1725 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1727 if (!buflist_held) {
1728 mutex_enter(&l2arc_buflist_mtx);
1729 l2hdr = hdr->b_l2hdr;
1732 if (l2hdr != NULL) {
1733 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1735 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1736 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1737 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1738 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1739 if (hdr->b_state == arc_l2c_only)
1740 l2arc_hdr_stat_remove();
1741 hdr->b_l2hdr = NULL;
1745 mutex_exit(&l2arc_buflist_mtx);
1748 if (!BUF_EMPTY(hdr)) {
1749 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1750 buf_discard_identity(hdr);
1752 while (hdr->b_buf) {
1753 arc_buf_t *buf = hdr->b_buf;
1756 mutex_enter(&arc_eviction_mtx);
1757 mutex_enter(&buf->b_evict_lock);
1758 ASSERT(buf->b_hdr != NULL);
1759 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1760 hdr->b_buf = buf->b_next;
1761 buf->b_hdr = &arc_eviction_hdr;
1762 buf->b_next = arc_eviction_list;
1763 arc_eviction_list = buf;
1764 mutex_exit(&buf->b_evict_lock);
1765 mutex_exit(&arc_eviction_mtx);
1767 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1770 if (hdr->b_freeze_cksum != NULL) {
1771 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1772 hdr->b_freeze_cksum = NULL;
1774 if (hdr->b_thawed) {
1775 kmem_free(hdr->b_thawed, 1);
1776 hdr->b_thawed = NULL;
1779 ASSERT(!list_link_active(&hdr->b_arc_node));
1780 ASSERT3P(hdr->b_hash_next, ==, NULL);
1781 ASSERT3P(hdr->b_acb, ==, NULL);
1782 kmem_cache_free(hdr_cache, hdr);
1786 arc_buf_free(arc_buf_t *buf, void *tag)
1788 arc_buf_hdr_t *hdr = buf->b_hdr;
1789 int hashed = hdr->b_state != arc_anon;
1791 ASSERT(buf->b_efunc == NULL);
1792 ASSERT(buf->b_data != NULL);
1795 kmutex_t *hash_lock = HDR_LOCK(hdr);
1797 mutex_enter(hash_lock);
1799 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1801 (void) remove_reference(hdr, hash_lock, tag);
1802 if (hdr->b_datacnt > 1) {
1803 arc_buf_destroy(buf, FALSE, TRUE);
1805 ASSERT(buf == hdr->b_buf);
1806 ASSERT(buf->b_efunc == NULL);
1807 hdr->b_flags |= ARC_BUF_AVAILABLE;
1809 mutex_exit(hash_lock);
1810 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1813 * We are in the middle of an async write. Don't destroy
1814 * this buffer unless the write completes before we finish
1815 * decrementing the reference count.
1817 mutex_enter(&arc_eviction_mtx);
1818 (void) remove_reference(hdr, NULL, tag);
1819 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1820 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1821 mutex_exit(&arc_eviction_mtx);
1823 arc_hdr_destroy(hdr);
1825 if (remove_reference(hdr, NULL, tag) > 0)
1826 arc_buf_destroy(buf, FALSE, TRUE);
1828 arc_hdr_destroy(hdr);
1833 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1835 arc_buf_hdr_t *hdr = buf->b_hdr;
1836 kmutex_t *hash_lock = HDR_LOCK(hdr);
1837 boolean_t no_callback = (buf->b_efunc == NULL);
1839 if (hdr->b_state == arc_anon) {
1840 ASSERT(hdr->b_datacnt == 1);
1841 arc_buf_free(buf, tag);
1842 return (no_callback);
1845 mutex_enter(hash_lock);
1847 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1848 ASSERT(hdr->b_state != arc_anon);
1849 ASSERT(buf->b_data != NULL);
1851 (void) remove_reference(hdr, hash_lock, tag);
1852 if (hdr->b_datacnt > 1) {
1854 arc_buf_destroy(buf, FALSE, TRUE);
1855 } else if (no_callback) {
1856 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1857 ASSERT(buf->b_efunc == NULL);
1858 hdr->b_flags |= ARC_BUF_AVAILABLE;
1860 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1861 refcount_is_zero(&hdr->b_refcnt));
1862 mutex_exit(hash_lock);
1863 return (no_callback);
1867 arc_buf_size(arc_buf_t *buf)
1869 return (buf->b_hdr->b_size);
1873 * Called from the DMU to determine if the current buffer should be
1874 * evicted. In order to ensure proper locking, the eviction must be initiated
1875 * from the DMU. Return true if the buffer is associated with user data and
1876 * duplicate buffers still exist.
1879 arc_buf_eviction_needed(arc_buf_t *buf)
1882 boolean_t evict_needed = B_FALSE;
1884 if (zfs_disable_dup_eviction)
1887 mutex_enter(&buf->b_evict_lock);
1891 * We are in arc_do_user_evicts(); let that function
1892 * perform the eviction.
1894 ASSERT(buf->b_data == NULL);
1895 mutex_exit(&buf->b_evict_lock);
1897 } else if (buf->b_data == NULL) {
1899 * We have already been added to the arc eviction list;
1900 * recommend eviction.
1902 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1903 mutex_exit(&buf->b_evict_lock);
1907 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1908 evict_needed = B_TRUE;
1910 mutex_exit(&buf->b_evict_lock);
1911 return (evict_needed);
1915 * Evict buffers from list until we've removed the specified number of
1916 * bytes. Move the removed buffers to the appropriate evict state.
1917 * If the recycle flag is set, then attempt to "recycle" a buffer:
1918 * - look for a buffer to evict that is `bytes' long.
1919 * - return the data block from this buffer rather than freeing it.
1920 * This flag is used by callers that are trying to make space for a
1921 * new buffer in a full arc cache.
1923 * This function makes a "best effort". It skips over any buffers
1924 * it can't get a hash_lock on, and so may not catch all candidates.
1925 * It may also return without evicting as much space as requested.
1928 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1929 arc_buf_contents_t type)
1931 arc_state_t *evicted_state;
1932 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1933 int64_t bytes_remaining;
1934 arc_buf_hdr_t *ab, *ab_prev = NULL;
1935 list_t *evicted_list, *list, *evicted_list_start, *list_start;
1936 kmutex_t *lock, *evicted_lock;
1937 kmutex_t *hash_lock;
1938 boolean_t have_lock;
1939 void *stolen = NULL;
1940 static int evict_metadata_offset, evict_data_offset;
1941 int i, idx, offset, list_count, count;
1943 ASSERT(state == arc_mru || state == arc_mfu);
1945 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1947 if (type == ARC_BUFC_METADATA) {
1949 list_count = ARC_BUFC_NUMMETADATALISTS;
1950 list_start = &state->arcs_lists[0];
1951 evicted_list_start = &evicted_state->arcs_lists[0];
1952 idx = evict_metadata_offset;
1954 offset = ARC_BUFC_NUMMETADATALISTS;
1955 list_start = &state->arcs_lists[offset];
1956 evicted_list_start = &evicted_state->arcs_lists[offset];
1957 list_count = ARC_BUFC_NUMDATALISTS;
1958 idx = evict_data_offset;
1960 bytes_remaining = evicted_state->arcs_lsize[type];
1964 list = &list_start[idx];
1965 evicted_list = &evicted_list_start[idx];
1966 lock = ARCS_LOCK(state, (offset + idx));
1967 evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
1970 mutex_enter(evicted_lock);
1972 for (ab = list_tail(list); ab; ab = ab_prev) {
1973 ab_prev = list_prev(list, ab);
1974 bytes_remaining -= (ab->b_size * ab->b_datacnt);
1975 /* prefetch buffers have a minimum lifespan */
1976 if (HDR_IO_IN_PROGRESS(ab) ||
1977 (spa && ab->b_spa != spa) ||
1978 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1979 ddi_get_lbolt() - ab->b_arc_access <
1980 arc_min_prefetch_lifespan)) {
1984 /* "lookahead" for better eviction candidate */
1985 if (recycle && ab->b_size != bytes &&
1986 ab_prev && ab_prev->b_size == bytes)
1988 hash_lock = HDR_LOCK(ab);
1989 have_lock = MUTEX_HELD(hash_lock);
1990 if (have_lock || mutex_tryenter(hash_lock)) {
1991 ASSERT0(refcount_count(&ab->b_refcnt));
1992 ASSERT(ab->b_datacnt > 0);
1994 arc_buf_t *buf = ab->b_buf;
1995 if (!mutex_tryenter(&buf->b_evict_lock)) {
2000 bytes_evicted += ab->b_size;
2001 if (recycle && ab->b_type == type &&
2002 ab->b_size == bytes &&
2003 !HDR_L2_WRITING(ab)) {
2004 stolen = buf->b_data;
2009 mutex_enter(&arc_eviction_mtx);
2010 arc_buf_destroy(buf,
2011 buf->b_data == stolen, FALSE);
2012 ab->b_buf = buf->b_next;
2013 buf->b_hdr = &arc_eviction_hdr;
2014 buf->b_next = arc_eviction_list;
2015 arc_eviction_list = buf;
2016 mutex_exit(&arc_eviction_mtx);
2017 mutex_exit(&buf->b_evict_lock);
2019 mutex_exit(&buf->b_evict_lock);
2020 arc_buf_destroy(buf,
2021 buf->b_data == stolen, TRUE);
2026 ARCSTAT_INCR(arcstat_evict_l2_cached,
2029 if (l2arc_write_eligible(ab->b_spa, ab)) {
2030 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2034 arcstat_evict_l2_ineligible,
2039 if (ab->b_datacnt == 0) {
2040 arc_change_state(evicted_state, ab, hash_lock);
2041 ASSERT(HDR_IN_HASH_TABLE(ab));
2042 ab->b_flags |= ARC_IN_HASH_TABLE;
2043 ab->b_flags &= ~ARC_BUF_AVAILABLE;
2044 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2047 mutex_exit(hash_lock);
2048 if (bytes >= 0 && bytes_evicted >= bytes)
2050 if (bytes_remaining > 0) {
2051 mutex_exit(evicted_lock);
2053 idx = ((idx + 1) & (list_count - 1));
2062 mutex_exit(evicted_lock);
2065 idx = ((idx + 1) & (list_count - 1));
2068 if (bytes_evicted < bytes) {
2069 if (count < list_count)
2072 dprintf("only evicted %lld bytes from %x",
2073 (longlong_t)bytes_evicted, state);
2075 if (type == ARC_BUFC_METADATA)
2076 evict_metadata_offset = idx;
2078 evict_data_offset = idx;
2081 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2084 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2087 * We have just evicted some data into the ghost state, make
2088 * sure we also adjust the ghost state size if necessary.
2091 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
2092 int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
2093 arc_mru_ghost->arcs_size - arc_c;
2095 if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
2097 MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
2098 arc_evict_ghost(arc_mru_ghost, 0, todelete);
2099 } else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
2100 int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
2101 arc_mru_ghost->arcs_size +
2102 arc_mfu_ghost->arcs_size - arc_c);
2103 arc_evict_ghost(arc_mfu_ghost, 0, todelete);
2107 ARCSTAT_BUMP(arcstat_stolen);
2113 * Remove buffers from list until we've removed the specified number of
2114 * bytes. Destroy the buffers that are removed.
2117 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2119 arc_buf_hdr_t *ab, *ab_prev;
2120 arc_buf_hdr_t marker = { 0 };
2121 list_t *list, *list_start;
2122 kmutex_t *hash_lock, *lock;
2123 uint64_t bytes_deleted = 0;
2124 uint64_t bufs_skipped = 0;
2125 static int evict_offset;
2126 int list_count, idx = evict_offset;
2127 int offset, count = 0;
2129 ASSERT(GHOST_STATE(state));
2132 * data lists come after metadata lists
2134 list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2135 list_count = ARC_BUFC_NUMDATALISTS;
2136 offset = ARC_BUFC_NUMMETADATALISTS;
2139 list = &list_start[idx];
2140 lock = ARCS_LOCK(state, idx + offset);
2143 for (ab = list_tail(list); ab; ab = ab_prev) {
2144 ab_prev = list_prev(list, ab);
2145 if (spa && ab->b_spa != spa)
2148 /* ignore markers */
2152 hash_lock = HDR_LOCK(ab);
2153 /* caller may be trying to modify this buffer, skip it */
2154 if (MUTEX_HELD(hash_lock))
2156 if (mutex_tryenter(hash_lock)) {
2157 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2158 ASSERT(ab->b_buf == NULL);
2159 ARCSTAT_BUMP(arcstat_deleted);
2160 bytes_deleted += ab->b_size;
2162 if (ab->b_l2hdr != NULL) {
2164 * This buffer is cached on the 2nd Level ARC;
2165 * don't destroy the header.
2167 arc_change_state(arc_l2c_only, ab, hash_lock);
2168 mutex_exit(hash_lock);
2170 arc_change_state(arc_anon, ab, hash_lock);
2171 mutex_exit(hash_lock);
2172 arc_hdr_destroy(ab);
2175 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2176 if (bytes >= 0 && bytes_deleted >= bytes)
2178 } else if (bytes < 0) {
2180 * Insert a list marker and then wait for the
2181 * hash lock to become available. Once its
2182 * available, restart from where we left off.
2184 list_insert_after(list, ab, &marker);
2186 mutex_enter(hash_lock);
2187 mutex_exit(hash_lock);
2189 ab_prev = list_prev(list, &marker);
2190 list_remove(list, &marker);
2195 idx = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2198 if (count < list_count)
2202 if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2203 (bytes < 0 || bytes_deleted < bytes)) {
2204 list_start = &state->arcs_lists[0];
2205 list_count = ARC_BUFC_NUMMETADATALISTS;
2211 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2215 if (bytes_deleted < bytes)
2216 dprintf("only deleted %lld bytes from %p",
2217 (longlong_t)bytes_deleted, state);
2223 int64_t adjustment, delta;
2229 adjustment = MIN((int64_t)(arc_size - arc_c),
2230 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2233 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2234 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2235 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2236 adjustment -= delta;
2239 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2240 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2241 (void) arc_evict(arc_mru, 0, delta, FALSE,
2249 adjustment = arc_size - arc_c;
2251 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2252 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2253 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2254 adjustment -= delta;
2257 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2258 int64_t delta = MIN(adjustment,
2259 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2260 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2265 * Adjust ghost lists
2268 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2270 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2271 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2272 arc_evict_ghost(arc_mru_ghost, 0, delta);
2276 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2278 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2279 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2280 arc_evict_ghost(arc_mfu_ghost, 0, delta);
2285 arc_do_user_evicts(void)
2287 static arc_buf_t *tmp_arc_eviction_list;
2290 * Move list over to avoid LOR
2293 mutex_enter(&arc_eviction_mtx);
2294 tmp_arc_eviction_list = arc_eviction_list;
2295 arc_eviction_list = NULL;
2296 mutex_exit(&arc_eviction_mtx);
2298 while (tmp_arc_eviction_list != NULL) {
2299 arc_buf_t *buf = tmp_arc_eviction_list;
2300 tmp_arc_eviction_list = buf->b_next;
2301 mutex_enter(&buf->b_evict_lock);
2303 mutex_exit(&buf->b_evict_lock);
2305 if (buf->b_efunc != NULL)
2306 VERIFY(buf->b_efunc(buf) == 0);
2308 buf->b_efunc = NULL;
2309 buf->b_private = NULL;
2310 kmem_cache_free(buf_cache, buf);
2313 if (arc_eviction_list != NULL)
2318 * Flush all *evictable* data from the cache for the given spa.
2319 * NOTE: this will not touch "active" (i.e. referenced) data.
2322 arc_flush(spa_t *spa)
2327 guid = spa_load_guid(spa);
2329 while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2330 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2334 while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2335 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2339 while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2340 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2344 while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2345 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2350 arc_evict_ghost(arc_mru_ghost, guid, -1);
2351 arc_evict_ghost(arc_mfu_ghost, guid, -1);
2353 mutex_enter(&arc_reclaim_thr_lock);
2354 arc_do_user_evicts();
2355 mutex_exit(&arc_reclaim_thr_lock);
2356 ASSERT(spa || arc_eviction_list == NULL);
2362 if (arc_c > arc_c_min) {
2366 to_free = arc_c >> arc_shrink_shift;
2368 to_free = arc_c >> arc_shrink_shift;
2370 if (arc_c > arc_c_min + to_free)
2371 atomic_add_64(&arc_c, -to_free);
2375 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2376 if (arc_c > arc_size)
2377 arc_c = MAX(arc_size, arc_c_min);
2379 arc_p = (arc_c >> 1);
2380 ASSERT(arc_c >= arc_c_min);
2381 ASSERT((int64_t)arc_p >= 0);
2384 if (arc_size > arc_c)
2388 static int needfree = 0;
2391 arc_reclaim_needed(void)
2400 * Cooperate with pagedaemon when it's time for it to scan
2401 * and reclaim some pages.
2403 if (vm_paging_needed())
2408 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2413 * check that we're out of range of the pageout scanner. It starts to
2414 * schedule paging if freemem is less than lotsfree and needfree.
2415 * lotsfree is the high-water mark for pageout, and needfree is the
2416 * number of needed free pages. We add extra pages here to make sure
2417 * the scanner doesn't start up while we're freeing memory.
2419 if (freemem < lotsfree + needfree + extra)
2423 * check to make sure that swapfs has enough space so that anon
2424 * reservations can still succeed. anon_resvmem() checks that the
2425 * availrmem is greater than swapfs_minfree, and the number of reserved
2426 * swap pages. We also add a bit of extra here just to prevent
2427 * circumstances from getting really dire.
2429 if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2434 * If we're on an i386 platform, it's possible that we'll exhaust the
2435 * kernel heap space before we ever run out of available physical
2436 * memory. Most checks of the size of the heap_area compare against
2437 * tune.t_minarmem, which is the minimum available real memory that we
2438 * can have in the system. However, this is generally fixed at 25 pages
2439 * which is so low that it's useless. In this comparison, we seek to
2440 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2441 * heap is allocated. (Or, in the calculation, if less than 1/4th is
2444 if (btop(vmem_size(heap_arena, VMEM_FREE)) <
2445 (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
2449 if (kmem_used() > (kmem_size() * 3) / 4)
2454 if (spa_get_random(100) == 0)
2460 extern kmem_cache_t *zio_buf_cache[];
2461 extern kmem_cache_t *zio_data_buf_cache[];
2464 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2467 kmem_cache_t *prev_cache = NULL;
2468 kmem_cache_t *prev_data_cache = NULL;
2471 if (arc_meta_used >= arc_meta_limit) {
2473 * We are exceeding our meta-data cache limit.
2474 * Purge some DNLC entries to release holds on meta-data.
2476 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2480 * Reclaim unused memory from all kmem caches.
2487 * An aggressive reclamation will shrink the cache size as well as
2488 * reap free buffers from the arc kmem caches.
2490 if (strat == ARC_RECLAIM_AGGR)
2493 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2494 if (zio_buf_cache[i] != prev_cache) {
2495 prev_cache = zio_buf_cache[i];
2496 kmem_cache_reap_now(zio_buf_cache[i]);
2498 if (zio_data_buf_cache[i] != prev_data_cache) {
2499 prev_data_cache = zio_data_buf_cache[i];
2500 kmem_cache_reap_now(zio_data_buf_cache[i]);
2503 kmem_cache_reap_now(buf_cache);
2504 kmem_cache_reap_now(hdr_cache);
2508 arc_reclaim_thread(void *dummy __unused)
2510 clock_t growtime = 0;
2511 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2514 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2516 mutex_enter(&arc_reclaim_thr_lock);
2517 while (arc_thread_exit == 0) {
2518 if (arc_reclaim_needed()) {
2521 if (last_reclaim == ARC_RECLAIM_CONS) {
2522 last_reclaim = ARC_RECLAIM_AGGR;
2524 last_reclaim = ARC_RECLAIM_CONS;
2528 last_reclaim = ARC_RECLAIM_AGGR;
2532 /* reset the growth delay for every reclaim */
2533 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2535 if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2537 * If needfree is TRUE our vm_lowmem hook
2538 * was called and in that case we must free some
2539 * memory, so switch to aggressive mode.
2542 last_reclaim = ARC_RECLAIM_AGGR;
2544 arc_kmem_reap_now(last_reclaim);
2547 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2548 arc_no_grow = FALSE;
2553 if (arc_eviction_list != NULL)
2554 arc_do_user_evicts();
2563 /* block until needed, or one second, whichever is shorter */
2564 CALLB_CPR_SAFE_BEGIN(&cpr);
2565 (void) cv_timedwait(&arc_reclaim_thr_cv,
2566 &arc_reclaim_thr_lock, hz);
2567 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2570 arc_thread_exit = 0;
2571 cv_broadcast(&arc_reclaim_thr_cv);
2572 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2577 * Adapt arc info given the number of bytes we are trying to add and
2578 * the state that we are comming from. This function is only called
2579 * when we are adding new content to the cache.
2582 arc_adapt(int bytes, arc_state_t *state)
2585 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2587 if (state == arc_l2c_only)
2592 * Adapt the target size of the MRU list:
2593 * - if we just hit in the MRU ghost list, then increase
2594 * the target size of the MRU list.
2595 * - if we just hit in the MFU ghost list, then increase
2596 * the target size of the MFU list by decreasing the
2597 * target size of the MRU list.
2599 if (state == arc_mru_ghost) {
2600 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2601 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2602 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2604 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2605 } else if (state == arc_mfu_ghost) {
2608 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2609 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2610 mult = MIN(mult, 10);
2612 delta = MIN(bytes * mult, arc_p);
2613 arc_p = MAX(arc_p_min, arc_p - delta);
2615 ASSERT((int64_t)arc_p >= 0);
2617 if (arc_reclaim_needed()) {
2618 cv_signal(&arc_reclaim_thr_cv);
2625 if (arc_c >= arc_c_max)
2629 * If we're within (2 * maxblocksize) bytes of the target
2630 * cache size, increment the target cache size
2632 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2633 atomic_add_64(&arc_c, (int64_t)bytes);
2634 if (arc_c > arc_c_max)
2636 else if (state == arc_anon)
2637 atomic_add_64(&arc_p, (int64_t)bytes);
2641 ASSERT((int64_t)arc_p >= 0);
2645 * Check if the cache has reached its limits and eviction is required
2649 arc_evict_needed(arc_buf_contents_t type)
2651 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2657 * If zio data pages are being allocated out of a separate heap segment,
2658 * then enforce that the size of available vmem for this area remains
2659 * above about 1/32nd free.
2661 if (type == ARC_BUFC_DATA && zio_arena != NULL &&
2662 vmem_size(zio_arena, VMEM_FREE) <
2663 (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
2668 if (arc_reclaim_needed())
2671 return (arc_size > arc_c);
2675 * The buffer, supplied as the first argument, needs a data block.
2676 * So, if we are at cache max, determine which cache should be victimized.
2677 * We have the following cases:
2679 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2680 * In this situation if we're out of space, but the resident size of the MFU is
2681 * under the limit, victimize the MFU cache to satisfy this insertion request.
2683 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2684 * Here, we've used up all of the available space for the MRU, so we need to
2685 * evict from our own cache instead. Evict from the set of resident MRU
2688 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2689 * c minus p represents the MFU space in the cache, since p is the size of the
2690 * cache that is dedicated to the MRU. In this situation there's still space on
2691 * the MFU side, so the MRU side needs to be victimized.
2693 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2694 * MFU's resident set is consuming more space than it has been allotted. In
2695 * this situation, we must victimize our own cache, the MFU, for this insertion.
2698 arc_get_data_buf(arc_buf_t *buf)
2700 arc_state_t *state = buf->b_hdr->b_state;
2701 uint64_t size = buf->b_hdr->b_size;
2702 arc_buf_contents_t type = buf->b_hdr->b_type;
2704 arc_adapt(size, state);
2707 * We have not yet reached cache maximum size,
2708 * just allocate a new buffer.
2710 if (!arc_evict_needed(type)) {
2711 if (type == ARC_BUFC_METADATA) {
2712 buf->b_data = zio_buf_alloc(size);
2713 arc_space_consume(size, ARC_SPACE_DATA);
2715 ASSERT(type == ARC_BUFC_DATA);
2716 buf->b_data = zio_data_buf_alloc(size);
2717 ARCSTAT_INCR(arcstat_data_size, size);
2718 atomic_add_64(&arc_size, size);
2724 * If we are prefetching from the mfu ghost list, this buffer
2725 * will end up on the mru list; so steal space from there.
2727 if (state == arc_mfu_ghost)
2728 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2729 else if (state == arc_mru_ghost)
2732 if (state == arc_mru || state == arc_anon) {
2733 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2734 state = (arc_mfu->arcs_lsize[type] >= size &&
2735 arc_p > mru_used) ? arc_mfu : arc_mru;
2738 uint64_t mfu_space = arc_c - arc_p;
2739 state = (arc_mru->arcs_lsize[type] >= size &&
2740 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2742 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2743 if (type == ARC_BUFC_METADATA) {
2744 buf->b_data = zio_buf_alloc(size);
2745 arc_space_consume(size, ARC_SPACE_DATA);
2747 ASSERT(type == ARC_BUFC_DATA);
2748 buf->b_data = zio_data_buf_alloc(size);
2749 ARCSTAT_INCR(arcstat_data_size, size);
2750 atomic_add_64(&arc_size, size);
2752 ARCSTAT_BUMP(arcstat_recycle_miss);
2754 ASSERT(buf->b_data != NULL);
2757 * Update the state size. Note that ghost states have a
2758 * "ghost size" and so don't need to be updated.
2760 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2761 arc_buf_hdr_t *hdr = buf->b_hdr;
2763 atomic_add_64(&hdr->b_state->arcs_size, size);
2764 if (list_link_active(&hdr->b_arc_node)) {
2765 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2766 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2769 * If we are growing the cache, and we are adding anonymous
2770 * data, and we have outgrown arc_p, update arc_p
2772 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2773 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2774 arc_p = MIN(arc_c, arc_p + size);
2776 ARCSTAT_BUMP(arcstat_allocated);
2780 * This routine is called whenever a buffer is accessed.
2781 * NOTE: the hash lock is dropped in this function.
2784 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2788 ASSERT(MUTEX_HELD(hash_lock));
2790 if (buf->b_state == arc_anon) {
2792 * This buffer is not in the cache, and does not
2793 * appear in our "ghost" list. Add the new buffer
2797 ASSERT(buf->b_arc_access == 0);
2798 buf->b_arc_access = ddi_get_lbolt();
2799 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2800 arc_change_state(arc_mru, buf, hash_lock);
2802 } else if (buf->b_state == arc_mru) {
2803 now = ddi_get_lbolt();
2806 * If this buffer is here because of a prefetch, then either:
2807 * - clear the flag if this is a "referencing" read
2808 * (any subsequent access will bump this into the MFU state).
2810 * - move the buffer to the head of the list if this is
2811 * another prefetch (to make it less likely to be evicted).
2813 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2814 if (refcount_count(&buf->b_refcnt) == 0) {
2815 ASSERT(list_link_active(&buf->b_arc_node));
2817 buf->b_flags &= ~ARC_PREFETCH;
2818 ARCSTAT_BUMP(arcstat_mru_hits);
2820 buf->b_arc_access = now;
2825 * This buffer has been "accessed" only once so far,
2826 * but it is still in the cache. Move it to the MFU
2829 if (now > buf->b_arc_access + ARC_MINTIME) {
2831 * More than 125ms have passed since we
2832 * instantiated this buffer. Move it to the
2833 * most frequently used state.
2835 buf->b_arc_access = now;
2836 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2837 arc_change_state(arc_mfu, buf, hash_lock);
2839 ARCSTAT_BUMP(arcstat_mru_hits);
2840 } else if (buf->b_state == arc_mru_ghost) {
2841 arc_state_t *new_state;
2843 * This buffer has been "accessed" recently, but
2844 * was evicted from the cache. Move it to the
2848 if (buf->b_flags & ARC_PREFETCH) {
2849 new_state = arc_mru;
2850 if (refcount_count(&buf->b_refcnt) > 0)
2851 buf->b_flags &= ~ARC_PREFETCH;
2852 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2854 new_state = arc_mfu;
2855 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2858 buf->b_arc_access = ddi_get_lbolt();
2859 arc_change_state(new_state, buf, hash_lock);
2861 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2862 } else if (buf->b_state == arc_mfu) {
2864 * This buffer has been accessed more than once and is
2865 * still in the cache. Keep it in the MFU state.
2867 * NOTE: an add_reference() that occurred when we did
2868 * the arc_read() will have kicked this off the list.
2869 * If it was a prefetch, we will explicitly move it to
2870 * the head of the list now.
2872 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2873 ASSERT(refcount_count(&buf->b_refcnt) == 0);
2874 ASSERT(list_link_active(&buf->b_arc_node));
2876 ARCSTAT_BUMP(arcstat_mfu_hits);
2877 buf->b_arc_access = ddi_get_lbolt();
2878 } else if (buf->b_state == arc_mfu_ghost) {
2879 arc_state_t *new_state = arc_mfu;
2881 * This buffer has been accessed more than once but has
2882 * been evicted from the cache. Move it back to the
2886 if (buf->b_flags & ARC_PREFETCH) {
2888 * This is a prefetch access...
2889 * move this block back to the MRU state.
2891 ASSERT0(refcount_count(&buf->b_refcnt));
2892 new_state = arc_mru;
2895 buf->b_arc_access = ddi_get_lbolt();
2896 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2897 arc_change_state(new_state, buf, hash_lock);
2899 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2900 } else if (buf->b_state == arc_l2c_only) {
2902 * This buffer is on the 2nd Level ARC.
2905 buf->b_arc_access = ddi_get_lbolt();
2906 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2907 arc_change_state(arc_mfu, buf, hash_lock);
2909 ASSERT(!"invalid arc state");
2913 /* a generic arc_done_func_t which you can use */
2916 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2918 if (zio == NULL || zio->io_error == 0)
2919 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2920 VERIFY(arc_buf_remove_ref(buf, arg));
2923 /* a generic arc_done_func_t */
2925 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2927 arc_buf_t **bufp = arg;
2928 if (zio && zio->io_error) {
2929 VERIFY(arc_buf_remove_ref(buf, arg));
2933 ASSERT(buf->b_data);
2938 arc_read_done(zio_t *zio)
2940 arc_buf_hdr_t *hdr, *found;
2942 arc_buf_t *abuf; /* buffer we're assigning to callback */
2943 kmutex_t *hash_lock;
2944 arc_callback_t *callback_list, *acb;
2945 int freeable = FALSE;
2947 buf = zio->io_private;
2951 * The hdr was inserted into hash-table and removed from lists
2952 * prior to starting I/O. We should find this header, since
2953 * it's in the hash table, and it should be legit since it's
2954 * not possible to evict it during the I/O. The only possible
2955 * reason for it not to be found is if we were freed during the
2958 found = buf_hash_find(hdr->b_spa, &hdr->b_dva, hdr->b_birth,
2961 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
2962 (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2963 (found == hdr && HDR_L2_READING(hdr)));
2965 hdr->b_flags &= ~ARC_L2_EVICTED;
2966 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2967 hdr->b_flags &= ~ARC_L2CACHE;
2969 /* byteswap if necessary */
2970 callback_list = hdr->b_acb;
2971 ASSERT(callback_list != NULL);
2972 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
2973 dmu_object_byteswap_t bswap =
2974 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
2975 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2976 byteswap_uint64_array :
2977 dmu_ot_byteswap[bswap].ob_func;
2978 func(buf->b_data, hdr->b_size);
2981 arc_cksum_compute(buf, B_FALSE);
2984 #endif /* illumos */
2986 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
2988 * Only call arc_access on anonymous buffers. This is because
2989 * if we've issued an I/O for an evicted buffer, we've already
2990 * called arc_access (to prevent any simultaneous readers from
2991 * getting confused).
2993 arc_access(hdr, hash_lock);
2996 /* create copies of the data buffer for the callers */
2998 for (acb = callback_list; acb; acb = acb->acb_next) {
2999 if (acb->acb_done) {
3001 ARCSTAT_BUMP(arcstat_duplicate_reads);
3002 abuf = arc_buf_clone(buf);
3004 acb->acb_buf = abuf;
3009 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3010 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3012 ASSERT(buf->b_efunc == NULL);
3013 ASSERT(hdr->b_datacnt == 1);
3014 hdr->b_flags |= ARC_BUF_AVAILABLE;
3017 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3019 if (zio->io_error != 0) {
3020 hdr->b_flags |= ARC_IO_ERROR;
3021 if (hdr->b_state != arc_anon)
3022 arc_change_state(arc_anon, hdr, hash_lock);
3023 if (HDR_IN_HASH_TABLE(hdr))
3024 buf_hash_remove(hdr);
3025 freeable = refcount_is_zero(&hdr->b_refcnt);
3029 * Broadcast before we drop the hash_lock to avoid the possibility
3030 * that the hdr (and hence the cv) might be freed before we get to
3031 * the cv_broadcast().
3033 cv_broadcast(&hdr->b_cv);
3036 mutex_exit(hash_lock);
3039 * This block was freed while we waited for the read to
3040 * complete. It has been removed from the hash table and
3041 * moved to the anonymous state (so that it won't show up
3044 ASSERT3P(hdr->b_state, ==, arc_anon);
3045 freeable = refcount_is_zero(&hdr->b_refcnt);
3048 /* execute each callback and free its structure */
3049 while ((acb = callback_list) != NULL) {
3051 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3053 if (acb->acb_zio_dummy != NULL) {
3054 acb->acb_zio_dummy->io_error = zio->io_error;
3055 zio_nowait(acb->acb_zio_dummy);
3058 callback_list = acb->acb_next;
3059 kmem_free(acb, sizeof (arc_callback_t));
3063 arc_hdr_destroy(hdr);
3067 * "Read" the block block at the specified DVA (in bp) via the
3068 * cache. If the block is found in the cache, invoke the provided
3069 * callback immediately and return. Note that the `zio' parameter
3070 * in the callback will be NULL in this case, since no IO was
3071 * required. If the block is not in the cache pass the read request
3072 * on to the spa with a substitute callback function, so that the
3073 * requested block will be added to the cache.
3075 * If a read request arrives for a block that has a read in-progress,
3076 * either wait for the in-progress read to complete (and return the
3077 * results); or, if this is a read with a "done" func, add a record
3078 * to the read to invoke the "done" func when the read completes,
3079 * and return; or just return.
3081 * arc_read_done() will invoke all the requested "done" functions
3082 * for readers of this block.
3085 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3086 void *private, int priority, int zio_flags, uint32_t *arc_flags,
3087 const zbookmark_t *zb)
3090 arc_buf_t *buf = NULL;
3091 kmutex_t *hash_lock;
3093 uint64_t guid = spa_load_guid(spa);
3096 hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3098 if (hdr && hdr->b_datacnt > 0) {
3100 *arc_flags |= ARC_CACHED;
3102 if (HDR_IO_IN_PROGRESS(hdr)) {
3104 if (*arc_flags & ARC_WAIT) {
3105 cv_wait(&hdr->b_cv, hash_lock);
3106 mutex_exit(hash_lock);
3109 ASSERT(*arc_flags & ARC_NOWAIT);
3112 arc_callback_t *acb = NULL;
3114 acb = kmem_zalloc(sizeof (arc_callback_t),
3116 acb->acb_done = done;
3117 acb->acb_private = private;
3119 acb->acb_zio_dummy = zio_null(pio,
3120 spa, NULL, NULL, NULL, zio_flags);
3122 ASSERT(acb->acb_done != NULL);
3123 acb->acb_next = hdr->b_acb;
3125 add_reference(hdr, hash_lock, private);
3126 mutex_exit(hash_lock);
3129 mutex_exit(hash_lock);
3133 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3136 add_reference(hdr, hash_lock, private);
3138 * If this block is already in use, create a new
3139 * copy of the data so that we will be guaranteed
3140 * that arc_release() will always succeed.
3144 ASSERT(buf->b_data);
3145 if (HDR_BUF_AVAILABLE(hdr)) {
3146 ASSERT(buf->b_efunc == NULL);
3147 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3149 buf = arc_buf_clone(buf);
3152 } else if (*arc_flags & ARC_PREFETCH &&
3153 refcount_count(&hdr->b_refcnt) == 0) {
3154 hdr->b_flags |= ARC_PREFETCH;
3156 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3157 arc_access(hdr, hash_lock);
3158 if (*arc_flags & ARC_L2CACHE)
3159 hdr->b_flags |= ARC_L2CACHE;
3160 if (*arc_flags & ARC_L2COMPRESS)
3161 hdr->b_flags |= ARC_L2COMPRESS;
3162 mutex_exit(hash_lock);
3163 ARCSTAT_BUMP(arcstat_hits);
3164 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3165 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3166 data, metadata, hits);
3169 done(NULL, buf, private);
3171 uint64_t size = BP_GET_LSIZE(bp);
3172 arc_callback_t *acb;
3175 boolean_t devw = B_FALSE;
3176 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3177 uint64_t b_asize = 0;
3180 /* this block is not in the cache */
3181 arc_buf_hdr_t *exists;
3182 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3183 buf = arc_buf_alloc(spa, size, private, type);
3185 hdr->b_dva = *BP_IDENTITY(bp);
3186 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3187 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3188 exists = buf_hash_insert(hdr, &hash_lock);
3190 /* somebody beat us to the hash insert */
3191 mutex_exit(hash_lock);
3192 buf_discard_identity(hdr);
3193 (void) arc_buf_remove_ref(buf, private);
3194 goto top; /* restart the IO request */
3196 /* if this is a prefetch, we don't have a reference */
3197 if (*arc_flags & ARC_PREFETCH) {
3198 (void) remove_reference(hdr, hash_lock,
3200 hdr->b_flags |= ARC_PREFETCH;
3202 if (*arc_flags & ARC_L2CACHE)
3203 hdr->b_flags |= ARC_L2CACHE;
3204 if (*arc_flags & ARC_L2COMPRESS)
3205 hdr->b_flags |= ARC_L2COMPRESS;
3206 if (BP_GET_LEVEL(bp) > 0)
3207 hdr->b_flags |= ARC_INDIRECT;
3209 /* this block is in the ghost cache */
3210 ASSERT(GHOST_STATE(hdr->b_state));
3211 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3212 ASSERT0(refcount_count(&hdr->b_refcnt));
3213 ASSERT(hdr->b_buf == NULL);
3215 /* if this is a prefetch, we don't have a reference */
3216 if (*arc_flags & ARC_PREFETCH)
3217 hdr->b_flags |= ARC_PREFETCH;
3219 add_reference(hdr, hash_lock, private);
3220 if (*arc_flags & ARC_L2CACHE)
3221 hdr->b_flags |= ARC_L2CACHE;
3222 if (*arc_flags & ARC_L2COMPRESS)
3223 hdr->b_flags |= ARC_L2COMPRESS;
3224 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3227 buf->b_efunc = NULL;
3228 buf->b_private = NULL;
3231 ASSERT(hdr->b_datacnt == 0);
3233 arc_get_data_buf(buf);
3234 arc_access(hdr, hash_lock);
3237 ASSERT(!GHOST_STATE(hdr->b_state));
3239 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3240 acb->acb_done = done;
3241 acb->acb_private = private;
3243 ASSERT(hdr->b_acb == NULL);
3245 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3247 if (hdr->b_l2hdr != NULL &&
3248 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3249 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3250 addr = hdr->b_l2hdr->b_daddr;
3251 b_compress = hdr->b_l2hdr->b_compress;
3252 b_asize = hdr->b_l2hdr->b_asize;
3254 * Lock out device removal.
3256 if (vdev_is_dead(vd) ||
3257 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3261 mutex_exit(hash_lock);
3264 * At this point, we have a level 1 cache miss. Try again in
3265 * L2ARC if possible.
3267 ASSERT3U(hdr->b_size, ==, size);
3268 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3269 uint64_t, size, zbookmark_t *, zb);
3270 ARCSTAT_BUMP(arcstat_misses);
3271 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3272 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3273 data, metadata, misses);
3275 curthread->td_ru.ru_inblock++;
3278 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3280 * Read from the L2ARC if the following are true:
3281 * 1. The L2ARC vdev was previously cached.
3282 * 2. This buffer still has L2ARC metadata.
3283 * 3. This buffer isn't currently writing to the L2ARC.
3284 * 4. The L2ARC entry wasn't evicted, which may
3285 * also have invalidated the vdev.
3286 * 5. This isn't prefetch and l2arc_noprefetch is set.
3288 if (hdr->b_l2hdr != NULL &&
3289 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3290 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3291 l2arc_read_callback_t *cb;
3293 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3294 ARCSTAT_BUMP(arcstat_l2_hits);
3296 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3298 cb->l2rcb_buf = buf;
3299 cb->l2rcb_spa = spa;
3302 cb->l2rcb_flags = zio_flags;
3303 cb->l2rcb_compress = b_compress;
3305 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3306 addr + size < vd->vdev_psize -
3307 VDEV_LABEL_END_SIZE);
3310 * l2arc read. The SCL_L2ARC lock will be
3311 * released by l2arc_read_done().
3312 * Issue a null zio if the underlying buffer
3313 * was squashed to zero size by compression.
3315 if (b_compress == ZIO_COMPRESS_EMPTY) {
3316 rzio = zio_null(pio, spa, vd,
3317 l2arc_read_done, cb,
3318 zio_flags | ZIO_FLAG_DONT_CACHE |
3320 ZIO_FLAG_DONT_PROPAGATE |
3321 ZIO_FLAG_DONT_RETRY);
3323 rzio = zio_read_phys(pio, vd, addr,
3324 b_asize, buf->b_data,
3326 l2arc_read_done, cb, priority,
3327 zio_flags | ZIO_FLAG_DONT_CACHE |
3329 ZIO_FLAG_DONT_PROPAGATE |
3330 ZIO_FLAG_DONT_RETRY, B_FALSE);
3332 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3334 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3336 if (*arc_flags & ARC_NOWAIT) {
3341 ASSERT(*arc_flags & ARC_WAIT);
3342 if (zio_wait(rzio) == 0)
3345 /* l2arc read error; goto zio_read() */
3347 DTRACE_PROBE1(l2arc__miss,
3348 arc_buf_hdr_t *, hdr);
3349 ARCSTAT_BUMP(arcstat_l2_misses);
3350 if (HDR_L2_WRITING(hdr))
3351 ARCSTAT_BUMP(arcstat_l2_rw_clash);
3352 spa_config_exit(spa, SCL_L2ARC, vd);
3356 spa_config_exit(spa, SCL_L2ARC, vd);
3357 if (l2arc_ndev != 0) {
3358 DTRACE_PROBE1(l2arc__miss,
3359 arc_buf_hdr_t *, hdr);
3360 ARCSTAT_BUMP(arcstat_l2_misses);
3364 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3365 arc_read_done, buf, priority, zio_flags, zb);
3367 if (*arc_flags & ARC_WAIT)
3368 return (zio_wait(rzio));
3370 ASSERT(*arc_flags & ARC_NOWAIT);
3377 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3379 ASSERT(buf->b_hdr != NULL);
3380 ASSERT(buf->b_hdr->b_state != arc_anon);
3381 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3382 ASSERT(buf->b_efunc == NULL);
3383 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3385 buf->b_efunc = func;
3386 buf->b_private = private;
3390 * Notify the arc that a block was freed, and thus will never be used again.
3393 arc_freed(spa_t *spa, const blkptr_t *bp)
3396 kmutex_t *hash_lock;
3397 uint64_t guid = spa_load_guid(spa);
3399 hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3403 if (HDR_BUF_AVAILABLE(hdr)) {
3404 arc_buf_t *buf = hdr->b_buf;
3405 add_reference(hdr, hash_lock, FTAG);
3406 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3407 mutex_exit(hash_lock);
3409 arc_release(buf, FTAG);
3410 (void) arc_buf_remove_ref(buf, FTAG);
3412 mutex_exit(hash_lock);
3418 * This is used by the DMU to let the ARC know that a buffer is
3419 * being evicted, so the ARC should clean up. If this arc buf
3420 * is not yet in the evicted state, it will be put there.
3423 arc_buf_evict(arc_buf_t *buf)
3426 kmutex_t *hash_lock;
3428 list_t *list, *evicted_list;
3429 kmutex_t *lock, *evicted_lock;
3431 mutex_enter(&buf->b_evict_lock);
3435 * We are in arc_do_user_evicts().
3437 ASSERT(buf->b_data == NULL);
3438 mutex_exit(&buf->b_evict_lock);
3440 } else if (buf->b_data == NULL) {
3441 arc_buf_t copy = *buf; /* structure assignment */
3443 * We are on the eviction list; process this buffer now
3444 * but let arc_do_user_evicts() do the reaping.
3446 buf->b_efunc = NULL;
3447 mutex_exit(&buf->b_evict_lock);
3448 VERIFY(copy.b_efunc(©) == 0);
3451 hash_lock = HDR_LOCK(hdr);
3452 mutex_enter(hash_lock);
3454 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3456 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3457 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3460 * Pull this buffer off of the hdr
3463 while (*bufp != buf)
3464 bufp = &(*bufp)->b_next;
3465 *bufp = buf->b_next;
3467 ASSERT(buf->b_data != NULL);
3468 arc_buf_destroy(buf, FALSE, FALSE);
3470 if (hdr->b_datacnt == 0) {
3471 arc_state_t *old_state = hdr->b_state;
3472 arc_state_t *evicted_state;
3474 ASSERT(hdr->b_buf == NULL);
3475 ASSERT(refcount_is_zero(&hdr->b_refcnt));
3478 (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3480 get_buf_info(hdr, old_state, &list, &lock);
3481 get_buf_info(hdr, evicted_state, &evicted_list, &evicted_lock);
3483 mutex_enter(evicted_lock);
3485 arc_change_state(evicted_state, hdr, hash_lock);
3486 ASSERT(HDR_IN_HASH_TABLE(hdr));
3487 hdr->b_flags |= ARC_IN_HASH_TABLE;
3488 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3490 mutex_exit(evicted_lock);
3493 mutex_exit(hash_lock);
3494 mutex_exit(&buf->b_evict_lock);
3496 VERIFY(buf->b_efunc(buf) == 0);
3497 buf->b_efunc = NULL;
3498 buf->b_private = NULL;
3501 kmem_cache_free(buf_cache, buf);
3506 * Release this buffer from the cache, making it an anonymous buffer. This
3507 * must be done after a read and prior to modifying the buffer contents.
3508 * If the buffer has more than one reference, we must make
3509 * a new hdr for the buffer.
3512 arc_release(arc_buf_t *buf, void *tag)
3515 kmutex_t *hash_lock = NULL;
3516 l2arc_buf_hdr_t *l2hdr;
3520 * It would be nice to assert that if it's DMU metadata (level >
3521 * 0 || it's the dnode file), then it must be syncing context.
3522 * But we don't know that information at this level.
3525 mutex_enter(&buf->b_evict_lock);
3528 /* this buffer is not on any list */
3529 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3531 if (hdr->b_state == arc_anon) {
3532 /* this buffer is already released */
3533 ASSERT(buf->b_efunc == NULL);
3535 hash_lock = HDR_LOCK(hdr);
3536 mutex_enter(hash_lock);
3538 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3541 l2hdr = hdr->b_l2hdr;
3543 mutex_enter(&l2arc_buflist_mtx);
3544 hdr->b_l2hdr = NULL;
3545 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3547 buf_size = hdr->b_size;
3550 * Do we have more than one buf?
3552 if (hdr->b_datacnt > 1) {
3553 arc_buf_hdr_t *nhdr;
3555 uint64_t blksz = hdr->b_size;
3556 uint64_t spa = hdr->b_spa;
3557 arc_buf_contents_t type = hdr->b_type;
3558 uint32_t flags = hdr->b_flags;
3560 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3562 * Pull the data off of this hdr and attach it to
3563 * a new anonymous hdr.
3565 (void) remove_reference(hdr, hash_lock, tag);
3567 while (*bufp != buf)
3568 bufp = &(*bufp)->b_next;
3569 *bufp = buf->b_next;
3572 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3573 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3574 if (refcount_is_zero(&hdr->b_refcnt)) {
3575 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3576 ASSERT3U(*size, >=, hdr->b_size);
3577 atomic_add_64(size, -hdr->b_size);
3581 * We're releasing a duplicate user data buffer, update
3582 * our statistics accordingly.
3584 if (hdr->b_type == ARC_BUFC_DATA) {
3585 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3586 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3589 hdr->b_datacnt -= 1;
3590 arc_cksum_verify(buf);
3592 arc_buf_unwatch(buf);
3593 #endif /* illumos */
3595 mutex_exit(hash_lock);
3597 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3598 nhdr->b_size = blksz;
3600 nhdr->b_type = type;
3602 nhdr->b_state = arc_anon;
3603 nhdr->b_arc_access = 0;
3604 nhdr->b_flags = flags & ARC_L2_WRITING;
3605 nhdr->b_l2hdr = NULL;
3606 nhdr->b_datacnt = 1;
3607 nhdr->b_freeze_cksum = NULL;
3608 (void) refcount_add(&nhdr->b_refcnt, tag);
3610 mutex_exit(&buf->b_evict_lock);
3611 atomic_add_64(&arc_anon->arcs_size, blksz);
3613 mutex_exit(&buf->b_evict_lock);
3614 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3615 ASSERT(!list_link_active(&hdr->b_arc_node));
3616 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3617 if (hdr->b_state != arc_anon)
3618 arc_change_state(arc_anon, hdr, hash_lock);
3619 hdr->b_arc_access = 0;
3621 mutex_exit(hash_lock);
3623 buf_discard_identity(hdr);
3626 buf->b_efunc = NULL;
3627 buf->b_private = NULL;
3630 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3631 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3633 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3634 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3635 mutex_exit(&l2arc_buflist_mtx);
3640 arc_released(arc_buf_t *buf)
3644 mutex_enter(&buf->b_evict_lock);
3645 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3646 mutex_exit(&buf->b_evict_lock);
3651 arc_has_callback(arc_buf_t *buf)
3655 mutex_enter(&buf->b_evict_lock);
3656 callback = (buf->b_efunc != NULL);
3657 mutex_exit(&buf->b_evict_lock);
3663 arc_referenced(arc_buf_t *buf)
3667 mutex_enter(&buf->b_evict_lock);
3668 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3669 mutex_exit(&buf->b_evict_lock);
3670 return (referenced);
3675 arc_write_ready(zio_t *zio)
3677 arc_write_callback_t *callback = zio->io_private;
3678 arc_buf_t *buf = callback->awcb_buf;
3679 arc_buf_hdr_t *hdr = buf->b_hdr;
3681 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3682 callback->awcb_ready(zio, buf, callback->awcb_private);
3685 * If the IO is already in progress, then this is a re-write
3686 * attempt, so we need to thaw and re-compute the cksum.
3687 * It is the responsibility of the callback to handle the
3688 * accounting for any re-write attempt.
3690 if (HDR_IO_IN_PROGRESS(hdr)) {
3691 mutex_enter(&hdr->b_freeze_lock);
3692 if (hdr->b_freeze_cksum != NULL) {
3693 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3694 hdr->b_freeze_cksum = NULL;
3696 mutex_exit(&hdr->b_freeze_lock);
3698 arc_cksum_compute(buf, B_FALSE);
3699 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3703 arc_write_done(zio_t *zio)
3705 arc_write_callback_t *callback = zio->io_private;
3706 arc_buf_t *buf = callback->awcb_buf;
3707 arc_buf_hdr_t *hdr = buf->b_hdr;
3709 ASSERT(hdr->b_acb == NULL);
3711 if (zio->io_error == 0) {
3712 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3713 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3714 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3716 ASSERT(BUF_EMPTY(hdr));
3720 * If the block to be written was all-zero, we may have
3721 * compressed it away. In this case no write was performed
3722 * so there will be no dva/birth/checksum. The buffer must
3723 * therefore remain anonymous (and uncached).
3725 if (!BUF_EMPTY(hdr)) {
3726 arc_buf_hdr_t *exists;
3727 kmutex_t *hash_lock;
3729 ASSERT(zio->io_error == 0);
3731 arc_cksum_verify(buf);
3733 exists = buf_hash_insert(hdr, &hash_lock);
3736 * This can only happen if we overwrite for
3737 * sync-to-convergence, because we remove
3738 * buffers from the hash table when we arc_free().
3740 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3741 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3742 panic("bad overwrite, hdr=%p exists=%p",
3743 (void *)hdr, (void *)exists);
3744 ASSERT(refcount_is_zero(&exists->b_refcnt));
3745 arc_change_state(arc_anon, exists, hash_lock);
3746 mutex_exit(hash_lock);
3747 arc_hdr_destroy(exists);
3748 exists = buf_hash_insert(hdr, &hash_lock);
3749 ASSERT3P(exists, ==, NULL);
3750 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3752 ASSERT(zio->io_prop.zp_nopwrite);
3753 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3754 panic("bad nopwrite, hdr=%p exists=%p",
3755 (void *)hdr, (void *)exists);
3758 ASSERT(hdr->b_datacnt == 1);
3759 ASSERT(hdr->b_state == arc_anon);
3760 ASSERT(BP_GET_DEDUP(zio->io_bp));
3761 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3764 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3765 /* if it's not anon, we are doing a scrub */
3766 if (!exists && hdr->b_state == arc_anon)
3767 arc_access(hdr, hash_lock);
3768 mutex_exit(hash_lock);
3770 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3773 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3774 callback->awcb_done(zio, buf, callback->awcb_private);
3776 kmem_free(callback, sizeof (arc_write_callback_t));
3780 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3781 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3782 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *done,
3783 void *private, int priority, int zio_flags, const zbookmark_t *zb)
3785 arc_buf_hdr_t *hdr = buf->b_hdr;
3786 arc_write_callback_t *callback;
3789 ASSERT(ready != NULL);
3790 ASSERT(done != NULL);
3791 ASSERT(!HDR_IO_ERROR(hdr));
3792 ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3793 ASSERT(hdr->b_acb == NULL);
3795 hdr->b_flags |= ARC_L2CACHE;
3797 hdr->b_flags |= ARC_L2COMPRESS;
3798 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3799 callback->awcb_ready = ready;
3800 callback->awcb_done = done;
3801 callback->awcb_private = private;
3802 callback->awcb_buf = buf;
3804 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3805 arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3811 arc_memory_throttle(uint64_t reserve, uint64_t inflight_data, uint64_t txg)
3814 uint64_t available_memory =
3815 ptoa((uintmax_t)cnt.v_free_count + cnt.v_cache_count);
3816 static uint64_t page_load = 0;
3817 static uint64_t last_txg = 0;
3822 MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3825 if (available_memory >= zfs_write_limit_max)
3828 if (txg > last_txg) {
3833 * If we are in pageout, we know that memory is already tight,
3834 * the arc is already going to be evicting, so we just want to
3835 * continue to let page writes occur as quickly as possible.
3837 if (curproc == pageproc) {
3838 if (page_load > available_memory / 4)
3839 return (SET_ERROR(ERESTART));
3840 /* Note: reserve is inflated, so we deflate */
3841 page_load += reserve / 8;
3843 } else if (page_load > 0 && arc_reclaim_needed()) {
3844 /* memory is low, delay before restarting */
3845 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3846 return (SET_ERROR(EAGAIN));
3850 if (arc_size > arc_c_min) {
3851 uint64_t evictable_memory =
3852 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
3853 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
3854 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
3855 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
3856 available_memory += MIN(evictable_memory, arc_size - arc_c_min);
3859 if (inflight_data > available_memory / 4) {
3860 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3861 return (SET_ERROR(ERESTART));
3868 arc_tempreserve_clear(uint64_t reserve)
3870 atomic_add_64(&arc_tempreserve, -reserve);
3871 ASSERT((int64_t)arc_tempreserve >= 0);
3875 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3882 * Once in a while, fail for no reason. Everything should cope.
3884 if (spa_get_random(10000) == 0) {
3885 dprintf("forcing random failure\n");
3886 return (SET_ERROR(ERESTART));
3889 if (reserve > arc_c/4 && !arc_no_grow)
3890 arc_c = MIN(arc_c_max, reserve * 4);
3891 if (reserve > arc_c)
3892 return (SET_ERROR(ENOMEM));
3895 * Don't count loaned bufs as in flight dirty data to prevent long
3896 * network delays from blocking transactions that are ready to be
3897 * assigned to a txg.
3899 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3902 * Writes will, almost always, require additional memory allocations
3903 * in order to compress/encrypt/etc the data. We therefore need to
3904 * make sure that there is sufficient available memory for this.
3906 if (error = arc_memory_throttle(reserve, anon_size, txg))
3910 * Throttle writes when the amount of dirty data in the cache
3911 * gets too large. We try to keep the cache less than half full
3912 * of dirty blocks so that our sync times don't grow too large.
3913 * Note: if two requests come in concurrently, we might let them
3914 * both succeed, when one of them should fail. Not a huge deal.
3917 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3918 anon_size > arc_c / 4) {
3919 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3920 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3921 arc_tempreserve>>10,
3922 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3923 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3924 reserve>>10, arc_c>>10);
3925 return (SET_ERROR(ERESTART));
3927 atomic_add_64(&arc_tempreserve, reserve);
3931 static kmutex_t arc_lowmem_lock;
3933 static eventhandler_tag arc_event_lowmem = NULL;
3936 arc_lowmem(void *arg __unused, int howto __unused)
3939 /* Serialize access via arc_lowmem_lock. */
3940 mutex_enter(&arc_lowmem_lock);
3941 mutex_enter(&arc_reclaim_thr_lock);
3943 cv_signal(&arc_reclaim_thr_cv);
3946 * It is unsafe to block here in arbitrary threads, because we can come
3947 * here from ARC itself and may hold ARC locks and thus risk a deadlock
3948 * with ARC reclaim thread.
3950 if (curproc == pageproc) {
3952 msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
3954 mutex_exit(&arc_reclaim_thr_lock);
3955 mutex_exit(&arc_lowmem_lock);
3962 int i, prefetch_tunable_set = 0;
3964 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3965 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3966 mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
3968 /* Convert seconds to clock ticks */
3969 arc_min_prefetch_lifespan = 1 * hz;
3971 /* Start out with 1/8 of all memory */
3972 arc_c = kmem_size() / 8;
3977 * On architectures where the physical memory can be larger
3978 * than the addressable space (intel in 32-bit mode), we may
3979 * need to limit the cache to 1/8 of VM size.
3981 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3984 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
3985 arc_c_min = MAX(arc_c / 4, 64<<18);
3986 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
3987 if (arc_c * 8 >= 1<<30)
3988 arc_c_max = (arc_c * 8) - (1<<30);
3990 arc_c_max = arc_c_min;
3991 arc_c_max = MAX(arc_c * 5, arc_c_max);
3995 * Allow the tunables to override our calculations if they are
3996 * reasonable (ie. over 16MB)
3998 if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
3999 arc_c_max = zfs_arc_max;
4000 if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
4001 arc_c_min = zfs_arc_min;
4005 arc_p = (arc_c >> 1);
4007 /* limit meta-data to 1/4 of the arc capacity */
4008 arc_meta_limit = arc_c_max / 4;
4010 /* Allow the tunable to override if it is reasonable */
4011 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4012 arc_meta_limit = zfs_arc_meta_limit;
4014 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4015 arc_c_min = arc_meta_limit / 2;
4017 if (zfs_arc_grow_retry > 0)
4018 arc_grow_retry = zfs_arc_grow_retry;
4020 if (zfs_arc_shrink_shift > 0)
4021 arc_shrink_shift = zfs_arc_shrink_shift;
4023 if (zfs_arc_p_min_shift > 0)
4024 arc_p_min_shift = zfs_arc_p_min_shift;
4026 /* if kmem_flags are set, lets try to use less memory */
4027 if (kmem_debugging())
4029 if (arc_c < arc_c_min)
4032 zfs_arc_min = arc_c_min;
4033 zfs_arc_max = arc_c_max;
4035 arc_anon = &ARC_anon;
4037 arc_mru_ghost = &ARC_mru_ghost;
4039 arc_mfu_ghost = &ARC_mfu_ghost;
4040 arc_l2c_only = &ARC_l2c_only;
4043 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4044 mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4045 NULL, MUTEX_DEFAULT, NULL);
4046 mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4047 NULL, MUTEX_DEFAULT, NULL);
4048 mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4049 NULL, MUTEX_DEFAULT, NULL);
4050 mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4051 NULL, MUTEX_DEFAULT, NULL);
4052 mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4053 NULL, MUTEX_DEFAULT, NULL);
4054 mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4055 NULL, MUTEX_DEFAULT, NULL);
4057 list_create(&arc_mru->arcs_lists[i],
4058 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4059 list_create(&arc_mru_ghost->arcs_lists[i],
4060 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4061 list_create(&arc_mfu->arcs_lists[i],
4062 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4063 list_create(&arc_mfu_ghost->arcs_lists[i],
4064 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4065 list_create(&arc_mfu_ghost->arcs_lists[i],
4066 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4067 list_create(&arc_l2c_only->arcs_lists[i],
4068 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4073 arc_thread_exit = 0;
4074 arc_eviction_list = NULL;
4075 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4076 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4078 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4079 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4081 if (arc_ksp != NULL) {
4082 arc_ksp->ks_data = &arc_stats;
4083 kstat_install(arc_ksp);
4086 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4087 TS_RUN, minclsyspri);
4090 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4091 EVENTHANDLER_PRI_FIRST);
4097 if (zfs_write_limit_max == 0)
4098 zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
4100 zfs_write_limit_shift = 0;
4101 mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
4104 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4105 prefetch_tunable_set = 1;
4108 if (prefetch_tunable_set == 0) {
4109 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4111 printf(" add \"vfs.zfs.prefetch_disable=0\" "
4112 "to /boot/loader.conf.\n");
4113 zfs_prefetch_disable = 1;
4116 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4117 prefetch_tunable_set == 0) {
4118 printf("ZFS NOTICE: Prefetch is disabled by default if less "
4119 "than 4GB of RAM is present;\n"
4120 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
4121 "to /boot/loader.conf.\n");
4122 zfs_prefetch_disable = 1;
4125 /* Warn about ZFS memory and address space requirements. */
4126 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4127 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4128 "expect unstable behavior.\n");
4130 if (kmem_size() < 512 * (1 << 20)) {
4131 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4132 "expect unstable behavior.\n");
4133 printf(" Consider tuning vm.kmem_size and "
4134 "vm.kmem_size_max\n");
4135 printf(" in /boot/loader.conf.\n");
4145 mutex_enter(&arc_reclaim_thr_lock);
4146 arc_thread_exit = 1;
4147 cv_signal(&arc_reclaim_thr_cv);
4148 while (arc_thread_exit != 0)
4149 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4150 mutex_exit(&arc_reclaim_thr_lock);
4156 if (arc_ksp != NULL) {
4157 kstat_delete(arc_ksp);
4161 mutex_destroy(&arc_eviction_mtx);
4162 mutex_destroy(&arc_reclaim_thr_lock);
4163 cv_destroy(&arc_reclaim_thr_cv);
4165 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4166 list_destroy(&arc_mru->arcs_lists[i]);
4167 list_destroy(&arc_mru_ghost->arcs_lists[i]);
4168 list_destroy(&arc_mfu->arcs_lists[i]);
4169 list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4170 list_destroy(&arc_l2c_only->arcs_lists[i]);
4172 mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4173 mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4174 mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4175 mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4176 mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4177 mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4180 mutex_destroy(&zfs_write_limit_lock);
4184 ASSERT(arc_loaned_bytes == 0);
4186 mutex_destroy(&arc_lowmem_lock);
4188 if (arc_event_lowmem != NULL)
4189 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4196 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4197 * It uses dedicated storage devices to hold cached data, which are populated
4198 * using large infrequent writes. The main role of this cache is to boost
4199 * the performance of random read workloads. The intended L2ARC devices
4200 * include short-stroked disks, solid state disks, and other media with
4201 * substantially faster read latency than disk.
4203 * +-----------------------+
4205 * +-----------------------+
4208 * l2arc_feed_thread() arc_read()
4212 * +---------------+ |
4214 * +---------------+ |
4219 * +-------+ +-------+
4221 * | cache | | cache |
4222 * +-------+ +-------+
4223 * +=========+ .-----.
4224 * : L2ARC : |-_____-|
4225 * : devices : | Disks |
4226 * +=========+ `-_____-'
4228 * Read requests are satisfied from the following sources, in order:
4231 * 2) vdev cache of L2ARC devices
4233 * 4) vdev cache of disks
4236 * Some L2ARC device types exhibit extremely slow write performance.
4237 * To accommodate for this there are some significant differences between
4238 * the L2ARC and traditional cache design:
4240 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4241 * the ARC behave as usual, freeing buffers and placing headers on ghost
4242 * lists. The ARC does not send buffers to the L2ARC during eviction as
4243 * this would add inflated write latencies for all ARC memory pressure.
4245 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4246 * It does this by periodically scanning buffers from the eviction-end of
4247 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4248 * not already there. It scans until a headroom of buffers is satisfied,
4249 * which itself is a buffer for ARC eviction. If a compressible buffer is
4250 * found during scanning and selected for writing to an L2ARC device, we
4251 * temporarily boost scanning headroom during the next scan cycle to make
4252 * sure we adapt to compression effects (which might significantly reduce
4253 * the data volume we write to L2ARC). The thread that does this is
4254 * l2arc_feed_thread(), illustrated below; example sizes are included to
4255 * provide a better sense of ratio than this diagram:
4258 * +---------------------+----------+
4259 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4260 * +---------------------+----------+ | o L2ARC eligible
4261 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4262 * +---------------------+----------+ |
4263 * 15.9 Gbytes ^ 32 Mbytes |
4265 * l2arc_feed_thread()
4267 * l2arc write hand <--[oooo]--'
4271 * +==============================+
4272 * L2ARC dev |####|#|###|###| |####| ... |
4273 * +==============================+
4276 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4277 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4278 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4279 * safe to say that this is an uncommon case, since buffers at the end of
4280 * the ARC lists have moved there due to inactivity.
4282 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4283 * then the L2ARC simply misses copying some buffers. This serves as a
4284 * pressure valve to prevent heavy read workloads from both stalling the ARC
4285 * with waits and clogging the L2ARC with writes. This also helps prevent
4286 * the potential for the L2ARC to churn if it attempts to cache content too
4287 * quickly, such as during backups of the entire pool.
4289 * 5. After system boot and before the ARC has filled main memory, there are
4290 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4291 * lists can remain mostly static. Instead of searching from tail of these
4292 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4293 * for eligible buffers, greatly increasing its chance of finding them.
4295 * The L2ARC device write speed is also boosted during this time so that
4296 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4297 * there are no L2ARC reads, and no fear of degrading read performance
4298 * through increased writes.
4300 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4301 * the vdev queue can aggregate them into larger and fewer writes. Each
4302 * device is written to in a rotor fashion, sweeping writes through
4303 * available space then repeating.
4305 * 7. The L2ARC does not store dirty content. It never needs to flush
4306 * write buffers back to disk based storage.
4308 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4309 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4311 * The performance of the L2ARC can be tweaked by a number of tunables, which
4312 * may be necessary for different workloads:
4314 * l2arc_write_max max write bytes per interval
4315 * l2arc_write_boost extra write bytes during device warmup
4316 * l2arc_noprefetch skip caching prefetched buffers
4317 * l2arc_headroom number of max device writes to precache
4318 * l2arc_headroom_boost when we find compressed buffers during ARC
4319 * scanning, we multiply headroom by this
4320 * percentage factor for the next scan cycle,
4321 * since more compressed buffers are likely to
4323 * l2arc_feed_secs seconds between L2ARC writing
4325 * Tunables may be removed or added as future performance improvements are
4326 * integrated, and also may become zpool properties.
4328 * There are three key functions that control how the L2ARC warms up:
4330 * l2arc_write_eligible() check if a buffer is eligible to cache
4331 * l2arc_write_size() calculate how much to write
4332 * l2arc_write_interval() calculate sleep delay between writes
4334 * These three functions determine what to write, how much, and how quickly
4339 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4342 * A buffer is *not* eligible for the L2ARC if it:
4343 * 1. belongs to a different spa.
4344 * 2. is already cached on the L2ARC.
4345 * 3. has an I/O in progress (it may be an incomplete read).
4346 * 4. is flagged not eligible (zfs property).
4348 if (ab->b_spa != spa_guid) {
4349 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4352 if (ab->b_l2hdr != NULL) {
4353 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4356 if (HDR_IO_IN_PROGRESS(ab)) {
4357 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4360 if (!HDR_L2CACHE(ab)) {
4361 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4369 l2arc_write_size(void)
4374 * Make sure our globals have meaningful values in case the user
4377 size = l2arc_write_max;
4379 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4380 "be greater than zero, resetting it to the default (%d)",
4382 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4385 if (arc_warm == B_FALSE)
4386 size += l2arc_write_boost;
4393 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4395 clock_t interval, next, now;
4398 * If the ARC lists are busy, increase our write rate; if the
4399 * lists are stale, idle back. This is achieved by checking
4400 * how much we previously wrote - if it was more than half of
4401 * what we wanted, schedule the next write much sooner.
4403 if (l2arc_feed_again && wrote > (wanted / 2))
4404 interval = (hz * l2arc_feed_min_ms) / 1000;
4406 interval = hz * l2arc_feed_secs;
4408 now = ddi_get_lbolt();
4409 next = MAX(now, MIN(now + interval, began + interval));
4415 l2arc_hdr_stat_add(void)
4417 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4418 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4422 l2arc_hdr_stat_remove(void)
4424 ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4425 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4429 * Cycle through L2ARC devices. This is how L2ARC load balances.
4430 * If a device is returned, this also returns holding the spa config lock.
4432 static l2arc_dev_t *
4433 l2arc_dev_get_next(void)
4435 l2arc_dev_t *first, *next = NULL;
4438 * Lock out the removal of spas (spa_namespace_lock), then removal
4439 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4440 * both locks will be dropped and a spa config lock held instead.
4442 mutex_enter(&spa_namespace_lock);
4443 mutex_enter(&l2arc_dev_mtx);
4445 /* if there are no vdevs, there is nothing to do */
4446 if (l2arc_ndev == 0)
4450 next = l2arc_dev_last;
4452 /* loop around the list looking for a non-faulted vdev */
4454 next = list_head(l2arc_dev_list);
4456 next = list_next(l2arc_dev_list, next);
4458 next = list_head(l2arc_dev_list);
4461 /* if we have come back to the start, bail out */
4464 else if (next == first)
4467 } while (vdev_is_dead(next->l2ad_vdev));
4469 /* if we were unable to find any usable vdevs, return NULL */
4470 if (vdev_is_dead(next->l2ad_vdev))
4473 l2arc_dev_last = next;
4476 mutex_exit(&l2arc_dev_mtx);
4479 * Grab the config lock to prevent the 'next' device from being
4480 * removed while we are writing to it.
4483 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4484 mutex_exit(&spa_namespace_lock);
4490 * Free buffers that were tagged for destruction.
4493 l2arc_do_free_on_write()
4496 l2arc_data_free_t *df, *df_prev;
4498 mutex_enter(&l2arc_free_on_write_mtx);
4499 buflist = l2arc_free_on_write;
4501 for (df = list_tail(buflist); df; df = df_prev) {
4502 df_prev = list_prev(buflist, df);
4503 ASSERT(df->l2df_data != NULL);
4504 ASSERT(df->l2df_func != NULL);
4505 df->l2df_func(df->l2df_data, df->l2df_size);
4506 list_remove(buflist, df);
4507 kmem_free(df, sizeof (l2arc_data_free_t));
4510 mutex_exit(&l2arc_free_on_write_mtx);
4514 * A write to a cache device has completed. Update all headers to allow
4515 * reads from these buffers to begin.
4518 l2arc_write_done(zio_t *zio)
4520 l2arc_write_callback_t *cb;
4523 arc_buf_hdr_t *head, *ab, *ab_prev;
4524 l2arc_buf_hdr_t *abl2;
4525 kmutex_t *hash_lock;
4527 cb = zio->io_private;
4529 dev = cb->l2wcb_dev;
4530 ASSERT(dev != NULL);
4531 head = cb->l2wcb_head;
4532 ASSERT(head != NULL);
4533 buflist = dev->l2ad_buflist;
4534 ASSERT(buflist != NULL);
4535 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4536 l2arc_write_callback_t *, cb);
4538 if (zio->io_error != 0)
4539 ARCSTAT_BUMP(arcstat_l2_writes_error);
4541 mutex_enter(&l2arc_buflist_mtx);
4544 * All writes completed, or an error was hit.
4546 for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4547 ab_prev = list_prev(buflist, ab);
4549 hash_lock = HDR_LOCK(ab);
4550 if (!mutex_tryenter(hash_lock)) {
4552 * This buffer misses out. It may be in a stage
4553 * of eviction. Its ARC_L2_WRITING flag will be
4554 * left set, denying reads to this buffer.
4556 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4563 * Release the temporary compressed buffer as soon as possible.
4565 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4566 l2arc_release_cdata_buf(ab);
4568 if (zio->io_error != 0) {
4570 * Error - drop L2ARC entry.
4572 list_remove(buflist, ab);
4573 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4575 trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4577 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4578 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4582 * Allow ARC to begin reads to this L2ARC entry.
4584 ab->b_flags &= ~ARC_L2_WRITING;
4586 mutex_exit(hash_lock);
4589 atomic_inc_64(&l2arc_writes_done);
4590 list_remove(buflist, head);
4591 kmem_cache_free(hdr_cache, head);
4592 mutex_exit(&l2arc_buflist_mtx);
4594 l2arc_do_free_on_write();
4596 kmem_free(cb, sizeof (l2arc_write_callback_t));
4600 * A read to a cache device completed. Validate buffer contents before
4601 * handing over to the regular ARC routines.
4604 l2arc_read_done(zio_t *zio)
4606 l2arc_read_callback_t *cb;
4609 kmutex_t *hash_lock;
4612 ASSERT(zio->io_vd != NULL);
4613 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4615 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4617 cb = zio->io_private;
4619 buf = cb->l2rcb_buf;
4620 ASSERT(buf != NULL);
4622 hash_lock = HDR_LOCK(buf->b_hdr);
4623 mutex_enter(hash_lock);
4625 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4628 * If the buffer was compressed, decompress it first.
4630 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4631 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4632 ASSERT(zio->io_data != NULL);
4635 * Check this survived the L2ARC journey.
4637 equal = arc_cksum_equal(buf);
4638 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4639 mutex_exit(hash_lock);
4640 zio->io_private = buf;
4641 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4642 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
4645 mutex_exit(hash_lock);
4647 * Buffer didn't survive caching. Increment stats and
4648 * reissue to the original storage device.
4650 if (zio->io_error != 0) {
4651 ARCSTAT_BUMP(arcstat_l2_io_error);
4653 zio->io_error = SET_ERROR(EIO);
4656 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4659 * If there's no waiter, issue an async i/o to the primary
4660 * storage now. If there *is* a waiter, the caller must
4661 * issue the i/o in a context where it's OK to block.
4663 if (zio->io_waiter == NULL) {
4664 zio_t *pio = zio_unique_parent(zio);
4666 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4668 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4669 buf->b_data, zio->io_size, arc_read_done, buf,
4670 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4674 kmem_free(cb, sizeof (l2arc_read_callback_t));
4678 * This is the list priority from which the L2ARC will search for pages to
4679 * cache. This is used within loops (0..3) to cycle through lists in the
4680 * desired order. This order can have a significant effect on cache
4683 * Currently the metadata lists are hit first, MFU then MRU, followed by
4684 * the data lists. This function returns a locked list, and also returns
4688 l2arc_list_locked(int list_num, kmutex_t **lock)
4690 list_t *list = NULL;
4693 ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4695 if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4697 list = &arc_mfu->arcs_lists[idx];
4698 *lock = ARCS_LOCK(arc_mfu, idx);
4699 } else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4700 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4701 list = &arc_mru->arcs_lists[idx];
4702 *lock = ARCS_LOCK(arc_mru, idx);
4703 } else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4704 ARC_BUFC_NUMDATALISTS)) {
4705 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4706 list = &arc_mfu->arcs_lists[idx];
4707 *lock = ARCS_LOCK(arc_mfu, idx);
4709 idx = list_num - ARC_BUFC_NUMLISTS;
4710 list = &arc_mru->arcs_lists[idx];
4711 *lock = ARCS_LOCK(arc_mru, idx);
4714 ASSERT(!(MUTEX_HELD(*lock)));
4720 * Evict buffers from the device write hand to the distance specified in
4721 * bytes. This distance may span populated buffers, it may span nothing.
4722 * This is clearing a region on the L2ARC device ready for writing.
4723 * If the 'all' boolean is set, every buffer is evicted.
4726 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4729 l2arc_buf_hdr_t *abl2;
4730 arc_buf_hdr_t *ab, *ab_prev;
4731 kmutex_t *hash_lock;
4734 buflist = dev->l2ad_buflist;
4736 if (buflist == NULL)
4739 if (!all && dev->l2ad_first) {
4741 * This is the first sweep through the device. There is
4747 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4749 * When nearing the end of the device, evict to the end
4750 * before the device write hand jumps to the start.
4752 taddr = dev->l2ad_end;
4754 taddr = dev->l2ad_hand + distance;
4756 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4757 uint64_t, taddr, boolean_t, all);
4760 mutex_enter(&l2arc_buflist_mtx);
4761 for (ab = list_tail(buflist); ab; ab = ab_prev) {
4762 ab_prev = list_prev(buflist, ab);
4764 hash_lock = HDR_LOCK(ab);
4765 if (!mutex_tryenter(hash_lock)) {
4767 * Missed the hash lock. Retry.
4769 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4770 mutex_exit(&l2arc_buflist_mtx);
4771 mutex_enter(hash_lock);
4772 mutex_exit(hash_lock);
4776 if (HDR_L2_WRITE_HEAD(ab)) {
4778 * We hit a write head node. Leave it for
4779 * l2arc_write_done().
4781 list_remove(buflist, ab);
4782 mutex_exit(hash_lock);
4786 if (!all && ab->b_l2hdr != NULL &&
4787 (ab->b_l2hdr->b_daddr > taddr ||
4788 ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4790 * We've evicted to the target address,
4791 * or the end of the device.
4793 mutex_exit(hash_lock);
4797 if (HDR_FREE_IN_PROGRESS(ab)) {
4799 * Already on the path to destruction.
4801 mutex_exit(hash_lock);
4805 if (ab->b_state == arc_l2c_only) {
4806 ASSERT(!HDR_L2_READING(ab));
4808 * This doesn't exist in the ARC. Destroy.
4809 * arc_hdr_destroy() will call list_remove()
4810 * and decrement arcstat_l2_size.
4812 arc_change_state(arc_anon, ab, hash_lock);
4813 arc_hdr_destroy(ab);
4816 * Invalidate issued or about to be issued
4817 * reads, since we may be about to write
4818 * over this location.
4820 if (HDR_L2_READING(ab)) {
4821 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4822 ab->b_flags |= ARC_L2_EVICTED;
4826 * Tell ARC this no longer exists in L2ARC.
4828 if (ab->b_l2hdr != NULL) {
4830 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4832 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4833 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4835 list_remove(buflist, ab);
4838 * This may have been leftover after a
4841 ab->b_flags &= ~ARC_L2_WRITING;
4843 mutex_exit(hash_lock);
4845 mutex_exit(&l2arc_buflist_mtx);
4847 vdev_space_update(dev->l2ad_vdev, -(taddr - dev->l2ad_evict), 0, 0);
4848 dev->l2ad_evict = taddr;
4852 * Find and write ARC buffers to the L2ARC device.
4854 * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4855 * for reading until they have completed writing.
4856 * The headroom_boost is an in-out parameter used to maintain headroom boost
4857 * state between calls to this function.
4859 * Returns the number of bytes actually written (which may be smaller than
4860 * the delta by which the device hand has changed due to alignment).
4863 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4864 boolean_t *headroom_boost)
4866 arc_buf_hdr_t *ab, *ab_prev, *head;
4868 uint64_t write_asize, write_psize, write_sz, headroom,
4871 kmutex_t *list_lock;
4873 l2arc_write_callback_t *cb;
4875 uint64_t guid = spa_load_guid(spa);
4876 const boolean_t do_headroom_boost = *headroom_boost;
4879 ASSERT(dev->l2ad_vdev != NULL);
4881 /* Lower the flag now, we might want to raise it again later. */
4882 *headroom_boost = B_FALSE;
4885 write_sz = write_asize = write_psize = 0;
4887 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4888 head->b_flags |= ARC_L2_WRITE_HEAD;
4890 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
4892 * We will want to try to compress buffers that are at least 2x the
4893 * device sector size.
4895 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4898 * Copy buffers for L2ARC writing.
4900 mutex_enter(&l2arc_buflist_mtx);
4901 for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
4902 uint64_t passed_sz = 0;
4904 list = l2arc_list_locked(try, &list_lock);
4905 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
4908 * L2ARC fast warmup.
4910 * Until the ARC is warm and starts to evict, read from the
4911 * head of the ARC lists rather than the tail.
4913 if (arc_warm == B_FALSE)
4914 ab = list_head(list);
4916 ab = list_tail(list);
4918 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
4920 headroom = target_sz * l2arc_headroom;
4921 if (do_headroom_boost)
4922 headroom = (headroom * l2arc_headroom_boost) / 100;
4924 for (; ab; ab = ab_prev) {
4925 l2arc_buf_hdr_t *l2hdr;
4926 kmutex_t *hash_lock;
4929 if (arc_warm == B_FALSE)
4930 ab_prev = list_next(list, ab);
4932 ab_prev = list_prev(list, ab);
4933 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, ab->b_size);
4935 hash_lock = HDR_LOCK(ab);
4936 if (!mutex_tryenter(hash_lock)) {
4937 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
4939 * Skip this buffer rather than waiting.
4944 passed_sz += ab->b_size;
4945 if (passed_sz > headroom) {
4949 mutex_exit(hash_lock);
4950 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
4954 if (!l2arc_write_eligible(guid, ab)) {
4955 mutex_exit(hash_lock);
4959 if ((write_sz + ab->b_size) > target_sz) {
4961 mutex_exit(hash_lock);
4962 ARCSTAT_BUMP(arcstat_l2_write_full);
4968 * Insert a dummy header on the buflist so
4969 * l2arc_write_done() can find where the
4970 * write buffers begin without searching.
4972 list_insert_head(dev->l2ad_buflist, head);
4975 sizeof (l2arc_write_callback_t), KM_SLEEP);
4976 cb->l2wcb_dev = dev;
4977 cb->l2wcb_head = head;
4978 pio = zio_root(spa, l2arc_write_done, cb,
4980 ARCSTAT_BUMP(arcstat_l2_write_pios);
4984 * Create and add a new L2ARC header.
4986 l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
4988 ab->b_flags |= ARC_L2_WRITING;
4991 * Temporarily stash the data buffer in b_tmp_cdata.
4992 * The subsequent write step will pick it up from
4993 * there. This is because can't access ab->b_buf
4994 * without holding the hash_lock, which we in turn
4995 * can't access without holding the ARC list locks
4996 * (which we want to avoid during compression/writing).
4998 l2hdr->b_compress = ZIO_COMPRESS_OFF;
4999 l2hdr->b_asize = ab->b_size;
5000 l2hdr->b_tmp_cdata = ab->b_buf->b_data;
5002 buf_sz = ab->b_size;
5003 ab->b_l2hdr = l2hdr;
5005 list_insert_head(dev->l2ad_buflist, ab);
5008 * Compute and store the buffer cksum before
5009 * writing. On debug the cksum is verified first.
5011 arc_cksum_verify(ab->b_buf);
5012 arc_cksum_compute(ab->b_buf, B_TRUE);
5014 mutex_exit(hash_lock);
5019 mutex_exit(list_lock);
5025 /* No buffers selected for writing? */
5028 mutex_exit(&l2arc_buflist_mtx);
5029 kmem_cache_free(hdr_cache, head);
5034 * Now start writing the buffers. We're starting at the write head
5035 * and work backwards, retracing the course of the buffer selector
5038 for (ab = list_prev(dev->l2ad_buflist, head); ab;
5039 ab = list_prev(dev->l2ad_buflist, ab)) {
5040 l2arc_buf_hdr_t *l2hdr;
5044 * We shouldn't need to lock the buffer here, since we flagged
5045 * it as ARC_L2_WRITING in the previous step, but we must take
5046 * care to only access its L2 cache parameters. In particular,
5047 * ab->b_buf may be invalid by now due to ARC eviction.
5049 l2hdr = ab->b_l2hdr;
5050 l2hdr->b_daddr = dev->l2ad_hand;
5052 if ((ab->b_flags & ARC_L2COMPRESS) &&
5053 l2hdr->b_asize >= buf_compress_minsz) {
5054 if (l2arc_compress_buf(l2hdr)) {
5056 * If compression succeeded, enable headroom
5057 * boost on the next scan cycle.
5059 *headroom_boost = B_TRUE;
5064 * Pick up the buffer data we had previously stashed away
5065 * (and now potentially also compressed).
5067 buf_data = l2hdr->b_tmp_cdata;
5068 buf_sz = l2hdr->b_asize;
5070 /* Compression may have squashed the buffer to zero length. */
5074 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5075 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5076 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5077 ZIO_FLAG_CANFAIL, B_FALSE);
5079 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5081 (void) zio_nowait(wzio);
5083 write_asize += buf_sz;
5085 * Keep the clock hand suitably device-aligned.
5087 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5088 write_psize += buf_p_sz;
5089 dev->l2ad_hand += buf_p_sz;
5093 mutex_exit(&l2arc_buflist_mtx);
5095 ASSERT3U(write_asize, <=, target_sz);
5096 ARCSTAT_BUMP(arcstat_l2_writes_sent);
5097 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5098 ARCSTAT_INCR(arcstat_l2_size, write_sz);
5099 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5100 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
5103 * Bump device hand to the device start if it is approaching the end.
5104 * l2arc_evict() will already have evicted ahead for this case.
5106 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5107 vdev_space_update(dev->l2ad_vdev,
5108 dev->l2ad_end - dev->l2ad_hand, 0, 0);
5109 dev->l2ad_hand = dev->l2ad_start;
5110 dev->l2ad_evict = dev->l2ad_start;
5111 dev->l2ad_first = B_FALSE;
5114 dev->l2ad_writing = B_TRUE;
5115 (void) zio_wait(pio);
5116 dev->l2ad_writing = B_FALSE;
5118 return (write_asize);
5122 * Compresses an L2ARC buffer.
5123 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5124 * size in l2hdr->b_asize. This routine tries to compress the data and
5125 * depending on the compression result there are three possible outcomes:
5126 * *) The buffer was incompressible. The original l2hdr contents were left
5127 * untouched and are ready for writing to an L2 device.
5128 * *) The buffer was all-zeros, so there is no need to write it to an L2
5129 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5130 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5131 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5132 * data buffer which holds the compressed data to be written, and b_asize
5133 * tells us how much data there is. b_compress is set to the appropriate
5134 * compression algorithm. Once writing is done, invoke
5135 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5137 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5138 * buffer was incompressible).
5141 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5146 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5147 ASSERT(l2hdr->b_tmp_cdata != NULL);
5149 len = l2hdr->b_asize;
5150 cdata = zio_data_buf_alloc(len);
5151 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5152 cdata, l2hdr->b_asize);
5155 /* zero block, indicate that there's nothing to write */
5156 zio_data_buf_free(cdata, len);
5157 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5159 l2hdr->b_tmp_cdata = NULL;
5160 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5162 } else if (csize > 0 && csize < len) {
5164 * Compression succeeded, we'll keep the cdata around for
5165 * writing and release it afterwards.
5167 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5168 l2hdr->b_asize = csize;
5169 l2hdr->b_tmp_cdata = cdata;
5170 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5174 * Compression failed, release the compressed buffer.
5175 * l2hdr will be left unmodified.
5177 zio_data_buf_free(cdata, len);
5178 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5184 * Decompresses a zio read back from an l2arc device. On success, the
5185 * underlying zio's io_data buffer is overwritten by the uncompressed
5186 * version. On decompression error (corrupt compressed stream), the
5187 * zio->io_error value is set to signal an I/O error.
5189 * Please note that the compressed data stream is not checksummed, so
5190 * if the underlying device is experiencing data corruption, we may feed
5191 * corrupt data to the decompressor, so the decompressor needs to be
5192 * able to handle this situation (LZ4 does).
5195 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5197 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5199 if (zio->io_error != 0) {
5201 * An io error has occured, just restore the original io
5202 * size in preparation for a main pool read.
5204 zio->io_orig_size = zio->io_size = hdr->b_size;
5208 if (c == ZIO_COMPRESS_EMPTY) {
5210 * An empty buffer results in a null zio, which means we
5211 * need to fill its io_data after we're done restoring the
5212 * buffer's contents.
5214 ASSERT(hdr->b_buf != NULL);
5215 bzero(hdr->b_buf->b_data, hdr->b_size);
5216 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5218 ASSERT(zio->io_data != NULL);
5220 * We copy the compressed data from the start of the arc buffer
5221 * (the zio_read will have pulled in only what we need, the
5222 * rest is garbage which we will overwrite at decompression)
5223 * and then decompress back to the ARC data buffer. This way we
5224 * can minimize copying by simply decompressing back over the
5225 * original compressed data (rather than decompressing to an
5226 * aux buffer and then copying back the uncompressed buffer,
5227 * which is likely to be much larger).
5232 csize = zio->io_size;
5233 cdata = zio_data_buf_alloc(csize);
5234 bcopy(zio->io_data, cdata, csize);
5235 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5237 zio->io_error = EIO;
5238 zio_data_buf_free(cdata, csize);
5241 /* Restore the expected uncompressed IO size. */
5242 zio->io_orig_size = zio->io_size = hdr->b_size;
5246 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5247 * This buffer serves as a temporary holder of compressed data while
5248 * the buffer entry is being written to an l2arc device. Once that is
5249 * done, we can dispose of it.
5252 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5254 l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5256 if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5258 * If the data was compressed, then we've allocated a
5259 * temporary buffer for it, so now we need to release it.
5261 ASSERT(l2hdr->b_tmp_cdata != NULL);
5262 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5264 l2hdr->b_tmp_cdata = NULL;
5268 * This thread feeds the L2ARC at regular intervals. This is the beating
5269 * heart of the L2ARC.
5272 l2arc_feed_thread(void *dummy __unused)
5277 uint64_t size, wrote;
5278 clock_t begin, next = ddi_get_lbolt();
5279 boolean_t headroom_boost = B_FALSE;
5281 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5283 mutex_enter(&l2arc_feed_thr_lock);
5285 while (l2arc_thread_exit == 0) {
5286 CALLB_CPR_SAFE_BEGIN(&cpr);
5287 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5288 next - ddi_get_lbolt());
5289 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5290 next = ddi_get_lbolt() + hz;
5293 * Quick check for L2ARC devices.
5295 mutex_enter(&l2arc_dev_mtx);
5296 if (l2arc_ndev == 0) {
5297 mutex_exit(&l2arc_dev_mtx);
5300 mutex_exit(&l2arc_dev_mtx);
5301 begin = ddi_get_lbolt();
5304 * This selects the next l2arc device to write to, and in
5305 * doing so the next spa to feed from: dev->l2ad_spa. This
5306 * will return NULL if there are now no l2arc devices or if
5307 * they are all faulted.
5309 * If a device is returned, its spa's config lock is also
5310 * held to prevent device removal. l2arc_dev_get_next()
5311 * will grab and release l2arc_dev_mtx.
5313 if ((dev = l2arc_dev_get_next()) == NULL)
5316 spa = dev->l2ad_spa;
5317 ASSERT(spa != NULL);
5320 * If the pool is read-only then force the feed thread to
5321 * sleep a little longer.
5323 if (!spa_writeable(spa)) {
5324 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5325 spa_config_exit(spa, SCL_L2ARC, dev);
5330 * Avoid contributing to memory pressure.
5332 if (arc_reclaim_needed()) {
5333 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5334 spa_config_exit(spa, SCL_L2ARC, dev);
5338 ARCSTAT_BUMP(arcstat_l2_feeds);
5340 size = l2arc_write_size();
5343 * Evict L2ARC buffers that will be overwritten.
5345 l2arc_evict(dev, size, B_FALSE);
5348 * Write ARC buffers.
5350 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5353 * Calculate interval between writes.
5355 next = l2arc_write_interval(begin, size, wrote);
5356 spa_config_exit(spa, SCL_L2ARC, dev);
5359 l2arc_thread_exit = 0;
5360 cv_broadcast(&l2arc_feed_thr_cv);
5361 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5366 l2arc_vdev_present(vdev_t *vd)
5370 mutex_enter(&l2arc_dev_mtx);
5371 for (dev = list_head(l2arc_dev_list); dev != NULL;
5372 dev = list_next(l2arc_dev_list, dev)) {
5373 if (dev->l2ad_vdev == vd)
5376 mutex_exit(&l2arc_dev_mtx);
5378 return (dev != NULL);
5382 * Add a vdev for use by the L2ARC. By this point the spa has already
5383 * validated the vdev and opened it.
5386 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5388 l2arc_dev_t *adddev;
5390 ASSERT(!l2arc_vdev_present(vd));
5393 * Create a new l2arc device entry.
5395 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5396 adddev->l2ad_spa = spa;
5397 adddev->l2ad_vdev = vd;
5398 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5399 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5400 adddev->l2ad_hand = adddev->l2ad_start;
5401 adddev->l2ad_evict = adddev->l2ad_start;
5402 adddev->l2ad_first = B_TRUE;
5403 adddev->l2ad_writing = B_FALSE;
5406 * This is a list of all ARC buffers that are still valid on the
5409 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5410 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5411 offsetof(arc_buf_hdr_t, b_l2node));
5413 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5416 * Add device to global list
5418 mutex_enter(&l2arc_dev_mtx);
5419 list_insert_head(l2arc_dev_list, adddev);
5420 atomic_inc_64(&l2arc_ndev);
5421 mutex_exit(&l2arc_dev_mtx);
5425 * Remove a vdev from the L2ARC.
5428 l2arc_remove_vdev(vdev_t *vd)
5430 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5433 * Find the device by vdev
5435 mutex_enter(&l2arc_dev_mtx);
5436 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5437 nextdev = list_next(l2arc_dev_list, dev);
5438 if (vd == dev->l2ad_vdev) {
5443 ASSERT(remdev != NULL);
5446 * Remove device from global list
5448 list_remove(l2arc_dev_list, remdev);
5449 l2arc_dev_last = NULL; /* may have been invalidated */
5450 atomic_dec_64(&l2arc_ndev);
5451 mutex_exit(&l2arc_dev_mtx);
5454 * Clear all buflists and ARC references. L2ARC device flush.
5456 l2arc_evict(remdev, 0, B_TRUE);
5457 list_destroy(remdev->l2ad_buflist);
5458 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5459 kmem_free(remdev, sizeof (l2arc_dev_t));
5465 l2arc_thread_exit = 0;
5467 l2arc_writes_sent = 0;
5468 l2arc_writes_done = 0;
5470 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5471 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5472 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5473 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5474 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5476 l2arc_dev_list = &L2ARC_dev_list;
5477 l2arc_free_on_write = &L2ARC_free_on_write;
5478 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5479 offsetof(l2arc_dev_t, l2ad_node));
5480 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5481 offsetof(l2arc_data_free_t, l2df_list_node));
5488 * This is called from dmu_fini(), which is called from spa_fini();
5489 * Because of this, we can assume that all l2arc devices have
5490 * already been removed when the pools themselves were removed.
5493 l2arc_do_free_on_write();
5495 mutex_destroy(&l2arc_feed_thr_lock);
5496 cv_destroy(&l2arc_feed_thr_cv);
5497 mutex_destroy(&l2arc_dev_mtx);
5498 mutex_destroy(&l2arc_buflist_mtx);
5499 mutex_destroy(&l2arc_free_on_write_mtx);
5501 list_destroy(l2arc_dev_list);
5502 list_destroy(l2arc_free_on_write);
5508 if (!(spa_mode_global & FWRITE))
5511 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5512 TS_RUN, minclsyspri);
5518 if (!(spa_mode_global & FWRITE))
5521 mutex_enter(&l2arc_feed_thr_lock);
5522 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5523 l2arc_thread_exit = 1;
5524 while (l2arc_thread_exit != 0)
5525 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5526 mutex_exit(&l2arc_feed_thr_lock);