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 2011 Nexenta Systems, Inc. All rights reserved.
24 * Copyright (c) 2013 by Delphix. All rights reserved.
25 * Copyright (c) 2013 by Saso Kiselkov. 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 therefor 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 therefor 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 therefor 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_RDTUN,
508 &arc_meta_used, 0, "ARC metadata used");
509 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_meta_limit, CTLFLAG_RDTUN,
510 &arc_meta_limit, 0, "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)
676 * L2ARC Performance Tunables
678 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
679 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
680 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
681 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
682 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
683 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
684 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
685 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
686 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
688 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
689 &l2arc_write_max, 0, "max write size");
690 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
691 &l2arc_write_boost, 0, "extra write during warmup");
692 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
693 &l2arc_headroom, 0, "number of dev writes");
694 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
695 &l2arc_feed_secs, 0, "interval seconds");
696 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
697 &l2arc_feed_min_ms, 0, "min interval milliseconds");
699 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
700 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
701 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
702 &l2arc_feed_again, 0, "turbo warmup");
703 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
704 &l2arc_norw, 0, "no reads during writes");
706 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
707 &ARC_anon.arcs_size, 0, "size of anonymous state");
708 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
709 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
710 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
711 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
713 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
714 &ARC_mru.arcs_size, 0, "size of mru state");
715 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
716 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
717 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
718 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
720 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
721 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
722 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
723 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
724 "size of metadata in mru ghost state");
725 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
726 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
727 "size of data in mru ghost state");
729 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
730 &ARC_mfu.arcs_size, 0, "size of mfu state");
731 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
732 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
733 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
734 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
736 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
737 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
738 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
739 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
740 "size of metadata in mfu ghost state");
741 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
742 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
743 "size of data in mfu ghost state");
745 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
746 &ARC_l2c_only.arcs_size, 0, "size of mru state");
751 typedef struct l2arc_dev {
752 vdev_t *l2ad_vdev; /* vdev */
753 spa_t *l2ad_spa; /* spa */
754 uint64_t l2ad_hand; /* next write location */
755 uint64_t l2ad_start; /* first addr on device */
756 uint64_t l2ad_end; /* last addr on device */
757 uint64_t l2ad_evict; /* last addr eviction reached */
758 boolean_t l2ad_first; /* first sweep through */
759 boolean_t l2ad_writing; /* currently writing */
760 list_t *l2ad_buflist; /* buffer list */
761 list_node_t l2ad_node; /* device list node */
764 static list_t L2ARC_dev_list; /* device list */
765 static list_t *l2arc_dev_list; /* device list pointer */
766 static kmutex_t l2arc_dev_mtx; /* device list mutex */
767 static l2arc_dev_t *l2arc_dev_last; /* last device used */
768 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
769 static list_t L2ARC_free_on_write; /* free after write buf list */
770 static list_t *l2arc_free_on_write; /* free after write list ptr */
771 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
772 static uint64_t l2arc_ndev; /* number of devices */
774 typedef struct l2arc_read_callback {
775 arc_buf_t *l2rcb_buf; /* read buffer */
776 spa_t *l2rcb_spa; /* spa */
777 blkptr_t l2rcb_bp; /* original blkptr */
778 zbookmark_t l2rcb_zb; /* original bookmark */
779 int l2rcb_flags; /* original flags */
780 enum zio_compress l2rcb_compress; /* applied compress */
781 } l2arc_read_callback_t;
783 typedef struct l2arc_write_callback {
784 l2arc_dev_t *l2wcb_dev; /* device info */
785 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
786 } l2arc_write_callback_t;
788 struct l2arc_buf_hdr {
789 /* protected by arc_buf_hdr mutex */
790 l2arc_dev_t *b_dev; /* L2ARC device */
791 uint64_t b_daddr; /* disk address, offset byte */
792 /* compression applied to buffer data */
793 enum zio_compress b_compress;
794 /* real alloc'd buffer size depending on b_compress applied */
796 /* temporary buffer holder for in-flight compressed data */
800 typedef struct l2arc_data_free {
801 /* protected by l2arc_free_on_write_mtx */
804 void (*l2df_func)(void *, size_t);
805 list_node_t l2df_list_node;
808 static kmutex_t l2arc_feed_thr_lock;
809 static kcondvar_t l2arc_feed_thr_cv;
810 static uint8_t l2arc_thread_exit;
812 static void l2arc_read_done(zio_t *zio);
813 static void l2arc_hdr_stat_add(void);
814 static void l2arc_hdr_stat_remove(void);
816 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
817 static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
818 enum zio_compress c);
819 static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
822 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
824 uint8_t *vdva = (uint8_t *)dva;
825 uint64_t crc = -1ULL;
828 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
830 for (i = 0; i < sizeof (dva_t); i++)
831 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
833 crc ^= (spa>>8) ^ birth;
838 #define BUF_EMPTY(buf) \
839 ((buf)->b_dva.dva_word[0] == 0 && \
840 (buf)->b_dva.dva_word[1] == 0 && \
843 #define BUF_EQUAL(spa, dva, birth, buf) \
844 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
845 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
846 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
849 buf_discard_identity(arc_buf_hdr_t *hdr)
851 hdr->b_dva.dva_word[0] = 0;
852 hdr->b_dva.dva_word[1] = 0;
857 static arc_buf_hdr_t *
858 buf_hash_find(uint64_t spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
860 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
861 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
864 mutex_enter(hash_lock);
865 for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
866 buf = buf->b_hash_next) {
867 if (BUF_EQUAL(spa, dva, birth, buf)) {
872 mutex_exit(hash_lock);
878 * Insert an entry into the hash table. If there is already an element
879 * equal to elem in the hash table, then the already existing element
880 * will be returned and the new element will not be inserted.
881 * Otherwise returns NULL.
883 static arc_buf_hdr_t *
884 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
886 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
887 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
891 ASSERT(!HDR_IN_HASH_TABLE(buf));
893 mutex_enter(hash_lock);
894 for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
895 fbuf = fbuf->b_hash_next, i++) {
896 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
900 buf->b_hash_next = buf_hash_table.ht_table[idx];
901 buf_hash_table.ht_table[idx] = buf;
902 buf->b_flags |= ARC_IN_HASH_TABLE;
904 /* collect some hash table performance data */
906 ARCSTAT_BUMP(arcstat_hash_collisions);
908 ARCSTAT_BUMP(arcstat_hash_chains);
910 ARCSTAT_MAX(arcstat_hash_chain_max, i);
913 ARCSTAT_BUMP(arcstat_hash_elements);
914 ARCSTAT_MAXSTAT(arcstat_hash_elements);
920 buf_hash_remove(arc_buf_hdr_t *buf)
922 arc_buf_hdr_t *fbuf, **bufp;
923 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
925 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
926 ASSERT(HDR_IN_HASH_TABLE(buf));
928 bufp = &buf_hash_table.ht_table[idx];
929 while ((fbuf = *bufp) != buf) {
930 ASSERT(fbuf != NULL);
931 bufp = &fbuf->b_hash_next;
933 *bufp = buf->b_hash_next;
934 buf->b_hash_next = NULL;
935 buf->b_flags &= ~ARC_IN_HASH_TABLE;
937 /* collect some hash table performance data */
938 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
940 if (buf_hash_table.ht_table[idx] &&
941 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
942 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
946 * Global data structures and functions for the buf kmem cache.
948 static kmem_cache_t *hdr_cache;
949 static kmem_cache_t *buf_cache;
956 kmem_free(buf_hash_table.ht_table,
957 (buf_hash_table.ht_mask + 1) * sizeof (void *));
958 for (i = 0; i < BUF_LOCKS; i++)
959 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
960 kmem_cache_destroy(hdr_cache);
961 kmem_cache_destroy(buf_cache);
965 * Constructor callback - called when the cache is empty
966 * and a new buf is requested.
970 hdr_cons(void *vbuf, void *unused, int kmflag)
972 arc_buf_hdr_t *buf = vbuf;
974 bzero(buf, sizeof (arc_buf_hdr_t));
975 refcount_create(&buf->b_refcnt);
976 cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
977 mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
978 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
985 buf_cons(void *vbuf, void *unused, int kmflag)
987 arc_buf_t *buf = vbuf;
989 bzero(buf, sizeof (arc_buf_t));
990 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
991 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
997 * Destructor callback - called when a cached buf is
998 * no longer required.
1002 hdr_dest(void *vbuf, void *unused)
1004 arc_buf_hdr_t *buf = vbuf;
1006 ASSERT(BUF_EMPTY(buf));
1007 refcount_destroy(&buf->b_refcnt);
1008 cv_destroy(&buf->b_cv);
1009 mutex_destroy(&buf->b_freeze_lock);
1010 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1015 buf_dest(void *vbuf, void *unused)
1017 arc_buf_t *buf = vbuf;
1019 mutex_destroy(&buf->b_evict_lock);
1020 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1024 * Reclaim callback -- invoked when memory is low.
1028 hdr_recl(void *unused)
1030 dprintf("hdr_recl called\n");
1032 * umem calls the reclaim func when we destroy the buf cache,
1033 * which is after we do arc_fini().
1036 cv_signal(&arc_reclaim_thr_cv);
1043 uint64_t hsize = 1ULL << 12;
1047 * The hash table is big enough to fill all of physical memory
1048 * with an average 64K block size. The table will take up
1049 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
1051 while (hsize * 65536 < (uint64_t)physmem * PAGESIZE)
1054 buf_hash_table.ht_mask = hsize - 1;
1055 buf_hash_table.ht_table =
1056 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1057 if (buf_hash_table.ht_table == NULL) {
1058 ASSERT(hsize > (1ULL << 8));
1063 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1064 0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1065 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1066 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1068 for (i = 0; i < 256; i++)
1069 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1070 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1072 for (i = 0; i < BUF_LOCKS; i++) {
1073 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1074 NULL, MUTEX_DEFAULT, NULL);
1078 #define ARC_MINTIME (hz>>4) /* 62 ms */
1081 arc_cksum_verify(arc_buf_t *buf)
1085 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1088 mutex_enter(&buf->b_hdr->b_freeze_lock);
1089 if (buf->b_hdr->b_freeze_cksum == NULL ||
1090 (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1091 mutex_exit(&buf->b_hdr->b_freeze_lock);
1094 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1095 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1096 panic("buffer modified while frozen!");
1097 mutex_exit(&buf->b_hdr->b_freeze_lock);
1101 arc_cksum_equal(arc_buf_t *buf)
1106 mutex_enter(&buf->b_hdr->b_freeze_lock);
1107 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1108 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1109 mutex_exit(&buf->b_hdr->b_freeze_lock);
1115 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1117 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1120 mutex_enter(&buf->b_hdr->b_freeze_lock);
1121 if (buf->b_hdr->b_freeze_cksum != NULL) {
1122 mutex_exit(&buf->b_hdr->b_freeze_lock);
1125 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1126 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1127 buf->b_hdr->b_freeze_cksum);
1128 mutex_exit(&buf->b_hdr->b_freeze_lock);
1131 #endif /* illumos */
1136 typedef struct procctl {
1144 arc_buf_unwatch(arc_buf_t *buf)
1151 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1152 ctl.prwatch.pr_size = 0;
1153 ctl.prwatch.pr_wflags = 0;
1154 result = write(arc_procfd, &ctl, sizeof (ctl));
1155 ASSERT3U(result, ==, sizeof (ctl));
1162 arc_buf_watch(arc_buf_t *buf)
1169 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1170 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1171 ctl.prwatch.pr_wflags = WA_WRITE;
1172 result = write(arc_procfd, &ctl, sizeof (ctl));
1173 ASSERT3U(result, ==, sizeof (ctl));
1177 #endif /* illumos */
1180 arc_buf_thaw(arc_buf_t *buf)
1182 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1183 if (buf->b_hdr->b_state != arc_anon)
1184 panic("modifying non-anon buffer!");
1185 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1186 panic("modifying buffer while i/o in progress!");
1187 arc_cksum_verify(buf);
1190 mutex_enter(&buf->b_hdr->b_freeze_lock);
1191 if (buf->b_hdr->b_freeze_cksum != NULL) {
1192 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1193 buf->b_hdr->b_freeze_cksum = NULL;
1196 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1197 if (buf->b_hdr->b_thawed)
1198 kmem_free(buf->b_hdr->b_thawed, 1);
1199 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1202 mutex_exit(&buf->b_hdr->b_freeze_lock);
1205 arc_buf_unwatch(buf);
1206 #endif /* illumos */
1210 arc_buf_freeze(arc_buf_t *buf)
1212 kmutex_t *hash_lock;
1214 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1217 hash_lock = HDR_LOCK(buf->b_hdr);
1218 mutex_enter(hash_lock);
1220 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1221 buf->b_hdr->b_state == arc_anon);
1222 arc_cksum_compute(buf, B_FALSE);
1223 mutex_exit(hash_lock);
1228 get_buf_info(arc_buf_hdr_t *ab, arc_state_t *state, list_t **list, kmutex_t **lock)
1230 uint64_t buf_hashid = buf_hash(ab->b_spa, &ab->b_dva, ab->b_birth);
1232 if (ab->b_type == ARC_BUFC_METADATA)
1233 buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1235 buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1236 buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1239 *list = &state->arcs_lists[buf_hashid];
1240 *lock = ARCS_LOCK(state, buf_hashid);
1245 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1247 ASSERT(MUTEX_HELD(hash_lock));
1249 if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1250 (ab->b_state != arc_anon)) {
1251 uint64_t delta = ab->b_size * ab->b_datacnt;
1252 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1256 get_buf_info(ab, ab->b_state, &list, &lock);
1257 ASSERT(!MUTEX_HELD(lock));
1259 ASSERT(list_link_active(&ab->b_arc_node));
1260 list_remove(list, ab);
1261 if (GHOST_STATE(ab->b_state)) {
1262 ASSERT0(ab->b_datacnt);
1263 ASSERT3P(ab->b_buf, ==, NULL);
1267 ASSERT3U(*size, >=, delta);
1268 atomic_add_64(size, -delta);
1270 /* remove the prefetch flag if we get a reference */
1271 if (ab->b_flags & ARC_PREFETCH)
1272 ab->b_flags &= ~ARC_PREFETCH;
1277 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1280 arc_state_t *state = ab->b_state;
1282 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1283 ASSERT(!GHOST_STATE(state));
1285 if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1286 (state != arc_anon)) {
1287 uint64_t *size = &state->arcs_lsize[ab->b_type];
1291 get_buf_info(ab, state, &list, &lock);
1292 ASSERT(!MUTEX_HELD(lock));
1294 ASSERT(!list_link_active(&ab->b_arc_node));
1295 list_insert_head(list, ab);
1296 ASSERT(ab->b_datacnt > 0);
1297 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1304 * Move the supplied buffer to the indicated state. The mutex
1305 * for the buffer must be held by the caller.
1308 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1310 arc_state_t *old_state = ab->b_state;
1311 int64_t refcnt = refcount_count(&ab->b_refcnt);
1312 uint64_t from_delta, to_delta;
1316 ASSERT(MUTEX_HELD(hash_lock));
1317 ASSERT(new_state != old_state);
1318 ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1319 ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1320 ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1322 from_delta = to_delta = ab->b_datacnt * ab->b_size;
1325 * If this buffer is evictable, transfer it from the
1326 * old state list to the new state list.
1329 if (old_state != arc_anon) {
1331 uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1333 get_buf_info(ab, old_state, &list, &lock);
1334 use_mutex = !MUTEX_HELD(lock);
1338 ASSERT(list_link_active(&ab->b_arc_node));
1339 list_remove(list, ab);
1342 * If prefetching out of the ghost cache,
1343 * we will have a non-zero datacnt.
1345 if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1346 /* ghost elements have a ghost size */
1347 ASSERT(ab->b_buf == NULL);
1348 from_delta = ab->b_size;
1350 ASSERT3U(*size, >=, from_delta);
1351 atomic_add_64(size, -from_delta);
1356 if (new_state != arc_anon) {
1358 uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1360 get_buf_info(ab, new_state, &list, &lock);
1361 use_mutex = !MUTEX_HELD(lock);
1365 list_insert_head(list, ab);
1367 /* ghost elements have a ghost size */
1368 if (GHOST_STATE(new_state)) {
1369 ASSERT(ab->b_datacnt == 0);
1370 ASSERT(ab->b_buf == NULL);
1371 to_delta = ab->b_size;
1373 atomic_add_64(size, to_delta);
1380 ASSERT(!BUF_EMPTY(ab));
1381 if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1382 buf_hash_remove(ab);
1384 /* adjust state sizes */
1386 atomic_add_64(&new_state->arcs_size, to_delta);
1388 ASSERT3U(old_state->arcs_size, >=, from_delta);
1389 atomic_add_64(&old_state->arcs_size, -from_delta);
1391 ab->b_state = new_state;
1393 /* adjust l2arc hdr stats */
1394 if (new_state == arc_l2c_only)
1395 l2arc_hdr_stat_add();
1396 else if (old_state == arc_l2c_only)
1397 l2arc_hdr_stat_remove();
1401 arc_space_consume(uint64_t space, arc_space_type_t type)
1403 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1406 case ARC_SPACE_DATA:
1407 ARCSTAT_INCR(arcstat_data_size, space);
1409 case ARC_SPACE_OTHER:
1410 ARCSTAT_INCR(arcstat_other_size, space);
1412 case ARC_SPACE_HDRS:
1413 ARCSTAT_INCR(arcstat_hdr_size, space);
1415 case ARC_SPACE_L2HDRS:
1416 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1420 atomic_add_64(&arc_meta_used, space);
1421 atomic_add_64(&arc_size, space);
1425 arc_space_return(uint64_t space, arc_space_type_t type)
1427 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1430 case ARC_SPACE_DATA:
1431 ARCSTAT_INCR(arcstat_data_size, -space);
1433 case ARC_SPACE_OTHER:
1434 ARCSTAT_INCR(arcstat_other_size, -space);
1436 case ARC_SPACE_HDRS:
1437 ARCSTAT_INCR(arcstat_hdr_size, -space);
1439 case ARC_SPACE_L2HDRS:
1440 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1444 ASSERT(arc_meta_used >= space);
1445 if (arc_meta_max < arc_meta_used)
1446 arc_meta_max = arc_meta_used;
1447 atomic_add_64(&arc_meta_used, -space);
1448 ASSERT(arc_size >= space);
1449 atomic_add_64(&arc_size, -space);
1453 arc_data_buf_alloc(uint64_t size)
1455 if (arc_evict_needed(ARC_BUFC_DATA))
1456 cv_signal(&arc_reclaim_thr_cv);
1457 atomic_add_64(&arc_size, size);
1458 return (zio_data_buf_alloc(size));
1462 arc_data_buf_free(void *buf, uint64_t size)
1464 zio_data_buf_free(buf, size);
1465 ASSERT(arc_size >= size);
1466 atomic_add_64(&arc_size, -size);
1470 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1475 ASSERT3U(size, >, 0);
1476 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1477 ASSERT(BUF_EMPTY(hdr));
1480 hdr->b_spa = spa_load_guid(spa);
1481 hdr->b_state = arc_anon;
1482 hdr->b_arc_access = 0;
1483 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1486 buf->b_efunc = NULL;
1487 buf->b_private = NULL;
1490 arc_get_data_buf(buf);
1493 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1494 (void) refcount_add(&hdr->b_refcnt, tag);
1499 static char *arc_onloan_tag = "onloan";
1502 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1503 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1504 * buffers must be returned to the arc before they can be used by the DMU or
1508 arc_loan_buf(spa_t *spa, int size)
1512 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1514 atomic_add_64(&arc_loaned_bytes, size);
1519 * Return a loaned arc buffer to the arc.
1522 arc_return_buf(arc_buf_t *buf, void *tag)
1524 arc_buf_hdr_t *hdr = buf->b_hdr;
1526 ASSERT(buf->b_data != NULL);
1527 (void) refcount_add(&hdr->b_refcnt, tag);
1528 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1530 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1533 /* Detach an arc_buf from a dbuf (tag) */
1535 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1539 ASSERT(buf->b_data != NULL);
1541 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1542 (void) refcount_remove(&hdr->b_refcnt, tag);
1543 buf->b_efunc = NULL;
1544 buf->b_private = NULL;
1546 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1550 arc_buf_clone(arc_buf_t *from)
1553 arc_buf_hdr_t *hdr = from->b_hdr;
1554 uint64_t size = hdr->b_size;
1556 ASSERT(hdr->b_state != arc_anon);
1558 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1561 buf->b_efunc = NULL;
1562 buf->b_private = NULL;
1563 buf->b_next = hdr->b_buf;
1565 arc_get_data_buf(buf);
1566 bcopy(from->b_data, buf->b_data, size);
1569 * This buffer already exists in the arc so create a duplicate
1570 * copy for the caller. If the buffer is associated with user data
1571 * then track the size and number of duplicates. These stats will be
1572 * updated as duplicate buffers are created and destroyed.
1574 if (hdr->b_type == ARC_BUFC_DATA) {
1575 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1576 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1578 hdr->b_datacnt += 1;
1583 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1586 kmutex_t *hash_lock;
1589 * Check to see if this buffer is evicted. Callers
1590 * must verify b_data != NULL to know if the add_ref
1593 mutex_enter(&buf->b_evict_lock);
1594 if (buf->b_data == NULL) {
1595 mutex_exit(&buf->b_evict_lock);
1598 hash_lock = HDR_LOCK(buf->b_hdr);
1599 mutex_enter(hash_lock);
1601 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1602 mutex_exit(&buf->b_evict_lock);
1604 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1605 add_reference(hdr, hash_lock, tag);
1606 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1607 arc_access(hdr, hash_lock);
1608 mutex_exit(hash_lock);
1609 ARCSTAT_BUMP(arcstat_hits);
1610 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1611 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1612 data, metadata, hits);
1616 * Free the arc data buffer. If it is an l2arc write in progress,
1617 * the buffer is placed on l2arc_free_on_write to be freed later.
1620 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1622 arc_buf_hdr_t *hdr = buf->b_hdr;
1624 if (HDR_L2_WRITING(hdr)) {
1625 l2arc_data_free_t *df;
1626 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1627 df->l2df_data = buf->b_data;
1628 df->l2df_size = hdr->b_size;
1629 df->l2df_func = free_func;
1630 mutex_enter(&l2arc_free_on_write_mtx);
1631 list_insert_head(l2arc_free_on_write, df);
1632 mutex_exit(&l2arc_free_on_write_mtx);
1633 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1635 free_func(buf->b_data, hdr->b_size);
1640 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
1644 /* free up data associated with the buf */
1646 arc_state_t *state = buf->b_hdr->b_state;
1647 uint64_t size = buf->b_hdr->b_size;
1648 arc_buf_contents_t type = buf->b_hdr->b_type;
1650 arc_cksum_verify(buf);
1652 arc_buf_unwatch(buf);
1653 #endif /* illumos */
1656 if (type == ARC_BUFC_METADATA) {
1657 arc_buf_data_free(buf, zio_buf_free);
1658 arc_space_return(size, ARC_SPACE_DATA);
1660 ASSERT(type == ARC_BUFC_DATA);
1661 arc_buf_data_free(buf, zio_data_buf_free);
1662 ARCSTAT_INCR(arcstat_data_size, -size);
1663 atomic_add_64(&arc_size, -size);
1666 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1667 uint64_t *cnt = &state->arcs_lsize[type];
1669 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1670 ASSERT(state != arc_anon);
1672 ASSERT3U(*cnt, >=, size);
1673 atomic_add_64(cnt, -size);
1675 ASSERT3U(state->arcs_size, >=, size);
1676 atomic_add_64(&state->arcs_size, -size);
1680 * If we're destroying a duplicate buffer make sure
1681 * that the appropriate statistics are updated.
1683 if (buf->b_hdr->b_datacnt > 1 &&
1684 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1685 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1686 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1688 ASSERT(buf->b_hdr->b_datacnt > 0);
1689 buf->b_hdr->b_datacnt -= 1;
1692 /* only remove the buf if requested */
1696 /* remove the buf from the hdr list */
1697 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1699 *bufp = buf->b_next;
1702 ASSERT(buf->b_efunc == NULL);
1704 /* clean up the buf */
1706 kmem_cache_free(buf_cache, buf);
1710 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1712 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1713 ASSERT3P(hdr->b_state, ==, arc_anon);
1714 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1715 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1717 if (l2hdr != NULL) {
1718 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1720 * To prevent arc_free() and l2arc_evict() from
1721 * attempting to free the same buffer at the same time,
1722 * a FREE_IN_PROGRESS flag is given to arc_free() to
1723 * give it priority. l2arc_evict() can't destroy this
1724 * header while we are waiting on l2arc_buflist_mtx.
1726 * The hdr may be removed from l2ad_buflist before we
1727 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1729 if (!buflist_held) {
1730 mutex_enter(&l2arc_buflist_mtx);
1731 l2hdr = hdr->b_l2hdr;
1734 if (l2hdr != NULL) {
1735 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1737 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1738 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1739 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1740 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1741 if (hdr->b_state == arc_l2c_only)
1742 l2arc_hdr_stat_remove();
1743 hdr->b_l2hdr = NULL;
1747 mutex_exit(&l2arc_buflist_mtx);
1750 if (!BUF_EMPTY(hdr)) {
1751 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1752 buf_discard_identity(hdr);
1754 while (hdr->b_buf) {
1755 arc_buf_t *buf = hdr->b_buf;
1758 mutex_enter(&arc_eviction_mtx);
1759 mutex_enter(&buf->b_evict_lock);
1760 ASSERT(buf->b_hdr != NULL);
1761 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1762 hdr->b_buf = buf->b_next;
1763 buf->b_hdr = &arc_eviction_hdr;
1764 buf->b_next = arc_eviction_list;
1765 arc_eviction_list = buf;
1766 mutex_exit(&buf->b_evict_lock);
1767 mutex_exit(&arc_eviction_mtx);
1769 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1772 if (hdr->b_freeze_cksum != NULL) {
1773 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1774 hdr->b_freeze_cksum = NULL;
1776 if (hdr->b_thawed) {
1777 kmem_free(hdr->b_thawed, 1);
1778 hdr->b_thawed = NULL;
1781 ASSERT(!list_link_active(&hdr->b_arc_node));
1782 ASSERT3P(hdr->b_hash_next, ==, NULL);
1783 ASSERT3P(hdr->b_acb, ==, NULL);
1784 kmem_cache_free(hdr_cache, hdr);
1788 arc_buf_free(arc_buf_t *buf, void *tag)
1790 arc_buf_hdr_t *hdr = buf->b_hdr;
1791 int hashed = hdr->b_state != arc_anon;
1793 ASSERT(buf->b_efunc == NULL);
1794 ASSERT(buf->b_data != NULL);
1797 kmutex_t *hash_lock = HDR_LOCK(hdr);
1799 mutex_enter(hash_lock);
1801 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1803 (void) remove_reference(hdr, hash_lock, tag);
1804 if (hdr->b_datacnt > 1) {
1805 arc_buf_destroy(buf, FALSE, TRUE);
1807 ASSERT(buf == hdr->b_buf);
1808 ASSERT(buf->b_efunc == NULL);
1809 hdr->b_flags |= ARC_BUF_AVAILABLE;
1811 mutex_exit(hash_lock);
1812 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1815 * We are in the middle of an async write. Don't destroy
1816 * this buffer unless the write completes before we finish
1817 * decrementing the reference count.
1819 mutex_enter(&arc_eviction_mtx);
1820 (void) remove_reference(hdr, NULL, tag);
1821 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1822 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1823 mutex_exit(&arc_eviction_mtx);
1825 arc_hdr_destroy(hdr);
1827 if (remove_reference(hdr, NULL, tag) > 0)
1828 arc_buf_destroy(buf, FALSE, TRUE);
1830 arc_hdr_destroy(hdr);
1835 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1837 arc_buf_hdr_t *hdr = buf->b_hdr;
1838 kmutex_t *hash_lock = HDR_LOCK(hdr);
1839 boolean_t no_callback = (buf->b_efunc == NULL);
1841 if (hdr->b_state == arc_anon) {
1842 ASSERT(hdr->b_datacnt == 1);
1843 arc_buf_free(buf, tag);
1844 return (no_callback);
1847 mutex_enter(hash_lock);
1849 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1850 ASSERT(hdr->b_state != arc_anon);
1851 ASSERT(buf->b_data != NULL);
1853 (void) remove_reference(hdr, hash_lock, tag);
1854 if (hdr->b_datacnt > 1) {
1856 arc_buf_destroy(buf, FALSE, TRUE);
1857 } else if (no_callback) {
1858 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1859 ASSERT(buf->b_efunc == NULL);
1860 hdr->b_flags |= ARC_BUF_AVAILABLE;
1862 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1863 refcount_is_zero(&hdr->b_refcnt));
1864 mutex_exit(hash_lock);
1865 return (no_callback);
1869 arc_buf_size(arc_buf_t *buf)
1871 return (buf->b_hdr->b_size);
1875 * Called from the DMU to determine if the current buffer should be
1876 * evicted. In order to ensure proper locking, the eviction must be initiated
1877 * from the DMU. Return true if the buffer is associated with user data and
1878 * duplicate buffers still exist.
1881 arc_buf_eviction_needed(arc_buf_t *buf)
1884 boolean_t evict_needed = B_FALSE;
1886 if (zfs_disable_dup_eviction)
1889 mutex_enter(&buf->b_evict_lock);
1893 * We are in arc_do_user_evicts(); let that function
1894 * perform the eviction.
1896 ASSERT(buf->b_data == NULL);
1897 mutex_exit(&buf->b_evict_lock);
1899 } else if (buf->b_data == NULL) {
1901 * We have already been added to the arc eviction list;
1902 * recommend eviction.
1904 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1905 mutex_exit(&buf->b_evict_lock);
1909 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1910 evict_needed = B_TRUE;
1912 mutex_exit(&buf->b_evict_lock);
1913 return (evict_needed);
1917 * Evict buffers from list until we've removed the specified number of
1918 * bytes. Move the removed buffers to the appropriate evict state.
1919 * If the recycle flag is set, then attempt to "recycle" a buffer:
1920 * - look for a buffer to evict that is `bytes' long.
1921 * - return the data block from this buffer rather than freeing it.
1922 * This flag is used by callers that are trying to make space for a
1923 * new buffer in a full arc cache.
1925 * This function makes a "best effort". It skips over any buffers
1926 * it can't get a hash_lock on, and so may not catch all candidates.
1927 * It may also return without evicting as much space as requested.
1930 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1931 arc_buf_contents_t type)
1933 arc_state_t *evicted_state;
1934 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1935 int64_t bytes_remaining;
1936 arc_buf_hdr_t *ab, *ab_prev = NULL;
1937 list_t *evicted_list, *list, *evicted_list_start, *list_start;
1938 kmutex_t *lock, *evicted_lock;
1939 kmutex_t *hash_lock;
1940 boolean_t have_lock;
1941 void *stolen = NULL;
1942 static int evict_metadata_offset, evict_data_offset;
1943 int i, idx, offset, list_count, count;
1945 ASSERT(state == arc_mru || state == arc_mfu);
1947 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1949 if (type == ARC_BUFC_METADATA) {
1951 list_count = ARC_BUFC_NUMMETADATALISTS;
1952 list_start = &state->arcs_lists[0];
1953 evicted_list_start = &evicted_state->arcs_lists[0];
1954 idx = evict_metadata_offset;
1956 offset = ARC_BUFC_NUMMETADATALISTS;
1957 list_start = &state->arcs_lists[offset];
1958 evicted_list_start = &evicted_state->arcs_lists[offset];
1959 list_count = ARC_BUFC_NUMDATALISTS;
1960 idx = evict_data_offset;
1962 bytes_remaining = evicted_state->arcs_lsize[type];
1966 list = &list_start[idx];
1967 evicted_list = &evicted_list_start[idx];
1968 lock = ARCS_LOCK(state, (offset + idx));
1969 evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
1972 mutex_enter(evicted_lock);
1974 for (ab = list_tail(list); ab; ab = ab_prev) {
1975 ab_prev = list_prev(list, ab);
1976 bytes_remaining -= (ab->b_size * ab->b_datacnt);
1977 /* prefetch buffers have a minimum lifespan */
1978 if (HDR_IO_IN_PROGRESS(ab) ||
1979 (spa && ab->b_spa != spa) ||
1980 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1981 ddi_get_lbolt() - ab->b_arc_access <
1982 arc_min_prefetch_lifespan)) {
1986 /* "lookahead" for better eviction candidate */
1987 if (recycle && ab->b_size != bytes &&
1988 ab_prev && ab_prev->b_size == bytes)
1990 hash_lock = HDR_LOCK(ab);
1991 have_lock = MUTEX_HELD(hash_lock);
1992 if (have_lock || mutex_tryenter(hash_lock)) {
1993 ASSERT0(refcount_count(&ab->b_refcnt));
1994 ASSERT(ab->b_datacnt > 0);
1996 arc_buf_t *buf = ab->b_buf;
1997 if (!mutex_tryenter(&buf->b_evict_lock)) {
2002 bytes_evicted += ab->b_size;
2003 if (recycle && ab->b_type == type &&
2004 ab->b_size == bytes &&
2005 !HDR_L2_WRITING(ab)) {
2006 stolen = buf->b_data;
2011 mutex_enter(&arc_eviction_mtx);
2012 arc_buf_destroy(buf,
2013 buf->b_data == stolen, FALSE);
2014 ab->b_buf = buf->b_next;
2015 buf->b_hdr = &arc_eviction_hdr;
2016 buf->b_next = arc_eviction_list;
2017 arc_eviction_list = buf;
2018 mutex_exit(&arc_eviction_mtx);
2019 mutex_exit(&buf->b_evict_lock);
2021 mutex_exit(&buf->b_evict_lock);
2022 arc_buf_destroy(buf,
2023 buf->b_data == stolen, TRUE);
2028 ARCSTAT_INCR(arcstat_evict_l2_cached,
2031 if (l2arc_write_eligible(ab->b_spa, ab)) {
2032 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2036 arcstat_evict_l2_ineligible,
2041 if (ab->b_datacnt == 0) {
2042 arc_change_state(evicted_state, ab, hash_lock);
2043 ASSERT(HDR_IN_HASH_TABLE(ab));
2044 ab->b_flags |= ARC_IN_HASH_TABLE;
2045 ab->b_flags &= ~ARC_BUF_AVAILABLE;
2046 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
2049 mutex_exit(hash_lock);
2050 if (bytes >= 0 && bytes_evicted >= bytes)
2052 if (bytes_remaining > 0) {
2053 mutex_exit(evicted_lock);
2055 idx = ((idx + 1) & (list_count - 1));
2064 mutex_exit(evicted_lock);
2067 idx = ((idx + 1) & (list_count - 1));
2070 if (bytes_evicted < bytes) {
2071 if (count < list_count)
2074 dprintf("only evicted %lld bytes from %x",
2075 (longlong_t)bytes_evicted, state);
2077 if (type == ARC_BUFC_METADATA)
2078 evict_metadata_offset = idx;
2080 evict_data_offset = idx;
2083 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2086 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2089 * We have just evicted some data into the ghost state, make
2090 * sure we also adjust the ghost state size if necessary.
2093 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
2094 int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
2095 arc_mru_ghost->arcs_size - arc_c;
2097 if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
2099 MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
2100 arc_evict_ghost(arc_mru_ghost, 0, todelete);
2101 } else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
2102 int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
2103 arc_mru_ghost->arcs_size +
2104 arc_mfu_ghost->arcs_size - arc_c);
2105 arc_evict_ghost(arc_mfu_ghost, 0, todelete);
2109 ARCSTAT_BUMP(arcstat_stolen);
2115 * Remove buffers from list until we've removed the specified number of
2116 * bytes. Destroy the buffers that are removed.
2119 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2121 arc_buf_hdr_t *ab, *ab_prev;
2122 arc_buf_hdr_t marker = { 0 };
2123 list_t *list, *list_start;
2124 kmutex_t *hash_lock, *lock;
2125 uint64_t bytes_deleted = 0;
2126 uint64_t bufs_skipped = 0;
2127 static int evict_offset;
2128 int list_count, idx = evict_offset;
2129 int offset, count = 0;
2131 ASSERT(GHOST_STATE(state));
2134 * data lists come after metadata lists
2136 list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2137 list_count = ARC_BUFC_NUMDATALISTS;
2138 offset = ARC_BUFC_NUMMETADATALISTS;
2141 list = &list_start[idx];
2142 lock = ARCS_LOCK(state, idx + offset);
2145 for (ab = list_tail(list); ab; ab = ab_prev) {
2146 ab_prev = list_prev(list, ab);
2147 if (spa && ab->b_spa != spa)
2150 /* ignore markers */
2154 hash_lock = HDR_LOCK(ab);
2155 /* caller may be trying to modify this buffer, skip it */
2156 if (MUTEX_HELD(hash_lock))
2158 if (mutex_tryenter(hash_lock)) {
2159 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2160 ASSERT(ab->b_buf == NULL);
2161 ARCSTAT_BUMP(arcstat_deleted);
2162 bytes_deleted += ab->b_size;
2164 if (ab->b_l2hdr != NULL) {
2166 * This buffer is cached on the 2nd Level ARC;
2167 * don't destroy the header.
2169 arc_change_state(arc_l2c_only, ab, hash_lock);
2170 mutex_exit(hash_lock);
2172 arc_change_state(arc_anon, ab, hash_lock);
2173 mutex_exit(hash_lock);
2174 arc_hdr_destroy(ab);
2177 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2178 if (bytes >= 0 && bytes_deleted >= bytes)
2180 } else if (bytes < 0) {
2182 * Insert a list marker and then wait for the
2183 * hash lock to become available. Once its
2184 * available, restart from where we left off.
2186 list_insert_after(list, ab, &marker);
2188 mutex_enter(hash_lock);
2189 mutex_exit(hash_lock);
2191 ab_prev = list_prev(list, &marker);
2192 list_remove(list, &marker);
2197 idx = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2200 if (count < list_count)
2204 if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2205 (bytes < 0 || bytes_deleted < bytes)) {
2206 list_start = &state->arcs_lists[0];
2207 list_count = ARC_BUFC_NUMMETADATALISTS;
2213 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2217 if (bytes_deleted < bytes)
2218 dprintf("only deleted %lld bytes from %p",
2219 (longlong_t)bytes_deleted, state);
2225 int64_t adjustment, delta;
2231 adjustment = MIN((int64_t)(arc_size - arc_c),
2232 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2235 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2236 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2237 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2238 adjustment -= delta;
2241 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2242 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2243 (void) arc_evict(arc_mru, 0, delta, FALSE,
2251 adjustment = arc_size - arc_c;
2253 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2254 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2255 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2256 adjustment -= delta;
2259 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2260 int64_t delta = MIN(adjustment,
2261 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2262 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2267 * Adjust ghost lists
2270 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2272 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2273 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2274 arc_evict_ghost(arc_mru_ghost, 0, delta);
2278 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2280 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2281 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2282 arc_evict_ghost(arc_mfu_ghost, 0, delta);
2287 arc_do_user_evicts(void)
2289 static arc_buf_t *tmp_arc_eviction_list;
2292 * Move list over to avoid LOR
2295 mutex_enter(&arc_eviction_mtx);
2296 tmp_arc_eviction_list = arc_eviction_list;
2297 arc_eviction_list = NULL;
2298 mutex_exit(&arc_eviction_mtx);
2300 while (tmp_arc_eviction_list != NULL) {
2301 arc_buf_t *buf = tmp_arc_eviction_list;
2302 tmp_arc_eviction_list = buf->b_next;
2303 mutex_enter(&buf->b_evict_lock);
2305 mutex_exit(&buf->b_evict_lock);
2307 if (buf->b_efunc != NULL)
2308 VERIFY(buf->b_efunc(buf) == 0);
2310 buf->b_efunc = NULL;
2311 buf->b_private = NULL;
2312 kmem_cache_free(buf_cache, buf);
2315 if (arc_eviction_list != NULL)
2320 * Flush all *evictable* data from the cache for the given spa.
2321 * NOTE: this will not touch "active" (i.e. referenced) data.
2324 arc_flush(spa_t *spa)
2329 guid = spa_load_guid(spa);
2331 while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2332 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2336 while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2337 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2341 while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2342 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2346 while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2347 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2352 arc_evict_ghost(arc_mru_ghost, guid, -1);
2353 arc_evict_ghost(arc_mfu_ghost, guid, -1);
2355 mutex_enter(&arc_reclaim_thr_lock);
2356 arc_do_user_evicts();
2357 mutex_exit(&arc_reclaim_thr_lock);
2358 ASSERT(spa || arc_eviction_list == NULL);
2364 if (arc_c > arc_c_min) {
2368 to_free = arc_c >> arc_shrink_shift;
2370 to_free = arc_c >> arc_shrink_shift;
2372 if (arc_c > arc_c_min + to_free)
2373 atomic_add_64(&arc_c, -to_free);
2377 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2378 if (arc_c > arc_size)
2379 arc_c = MAX(arc_size, arc_c_min);
2381 arc_p = (arc_c >> 1);
2382 ASSERT(arc_c >= arc_c_min);
2383 ASSERT((int64_t)arc_p >= 0);
2386 if (arc_size > arc_c)
2390 static int needfree = 0;
2393 arc_reclaim_needed(void)
2402 * Cooperate with pagedaemon when it's time for it to scan
2403 * and reclaim some pages.
2405 if (vm_paging_needed())
2410 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2415 * check that we're out of range of the pageout scanner. It starts to
2416 * schedule paging if freemem is less than lotsfree and needfree.
2417 * lotsfree is the high-water mark for pageout, and needfree is the
2418 * number of needed free pages. We add extra pages here to make sure
2419 * the scanner doesn't start up while we're freeing memory.
2421 if (freemem < lotsfree + needfree + extra)
2425 * check to make sure that swapfs has enough space so that anon
2426 * reservations can still succeed. anon_resvmem() checks that the
2427 * availrmem is greater than swapfs_minfree, and the number of reserved
2428 * swap pages. We also add a bit of extra here just to prevent
2429 * circumstances from getting really dire.
2431 if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2436 * If we're on an i386 platform, it's possible that we'll exhaust the
2437 * kernel heap space before we ever run out of available physical
2438 * memory. Most checks of the size of the heap_area compare against
2439 * tune.t_minarmem, which is the minimum available real memory that we
2440 * can have in the system. However, this is generally fixed at 25 pages
2441 * which is so low that it's useless. In this comparison, we seek to
2442 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2443 * heap is allocated. (Or, in the calculation, if less than 1/4th is
2446 if (btop(vmem_size(heap_arena, VMEM_FREE)) <
2447 (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
2451 if (kmem_used() > (kmem_size() * 3) / 4)
2456 if (spa_get_random(100) == 0)
2462 extern kmem_cache_t *zio_buf_cache[];
2463 extern kmem_cache_t *zio_data_buf_cache[];
2466 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2469 kmem_cache_t *prev_cache = NULL;
2470 kmem_cache_t *prev_data_cache = NULL;
2473 if (arc_meta_used >= arc_meta_limit) {
2475 * We are exceeding our meta-data cache limit.
2476 * Purge some DNLC entries to release holds on meta-data.
2478 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2482 * Reclaim unused memory from all kmem caches.
2489 * An aggressive reclamation will shrink the cache size as well as
2490 * reap free buffers from the arc kmem caches.
2492 if (strat == ARC_RECLAIM_AGGR)
2495 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2496 if (zio_buf_cache[i] != prev_cache) {
2497 prev_cache = zio_buf_cache[i];
2498 kmem_cache_reap_now(zio_buf_cache[i]);
2500 if (zio_data_buf_cache[i] != prev_data_cache) {
2501 prev_data_cache = zio_data_buf_cache[i];
2502 kmem_cache_reap_now(zio_data_buf_cache[i]);
2505 kmem_cache_reap_now(buf_cache);
2506 kmem_cache_reap_now(hdr_cache);
2510 arc_reclaim_thread(void *dummy __unused)
2512 clock_t growtime = 0;
2513 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2516 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2518 mutex_enter(&arc_reclaim_thr_lock);
2519 while (arc_thread_exit == 0) {
2520 if (arc_reclaim_needed()) {
2523 if (last_reclaim == ARC_RECLAIM_CONS) {
2524 last_reclaim = ARC_RECLAIM_AGGR;
2526 last_reclaim = ARC_RECLAIM_CONS;
2530 last_reclaim = ARC_RECLAIM_AGGR;
2534 /* reset the growth delay for every reclaim */
2535 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2537 if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2539 * If needfree is TRUE our vm_lowmem hook
2540 * was called and in that case we must free some
2541 * memory, so switch to aggressive mode.
2544 last_reclaim = ARC_RECLAIM_AGGR;
2546 arc_kmem_reap_now(last_reclaim);
2549 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2550 arc_no_grow = FALSE;
2555 if (arc_eviction_list != NULL)
2556 arc_do_user_evicts();
2565 /* block until needed, or one second, whichever is shorter */
2566 CALLB_CPR_SAFE_BEGIN(&cpr);
2567 (void) cv_timedwait(&arc_reclaim_thr_cv,
2568 &arc_reclaim_thr_lock, hz);
2569 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2572 arc_thread_exit = 0;
2573 cv_broadcast(&arc_reclaim_thr_cv);
2574 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2579 * Adapt arc info given the number of bytes we are trying to add and
2580 * the state that we are comming from. This function is only called
2581 * when we are adding new content to the cache.
2584 arc_adapt(int bytes, arc_state_t *state)
2587 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2589 if (state == arc_l2c_only)
2594 * Adapt the target size of the MRU list:
2595 * - if we just hit in the MRU ghost list, then increase
2596 * the target size of the MRU list.
2597 * - if we just hit in the MFU ghost list, then increase
2598 * the target size of the MFU list by decreasing the
2599 * target size of the MRU list.
2601 if (state == arc_mru_ghost) {
2602 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2603 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2604 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2606 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2607 } else if (state == arc_mfu_ghost) {
2610 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2611 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2612 mult = MIN(mult, 10);
2614 delta = MIN(bytes * mult, arc_p);
2615 arc_p = MAX(arc_p_min, arc_p - delta);
2617 ASSERT((int64_t)arc_p >= 0);
2619 if (arc_reclaim_needed()) {
2620 cv_signal(&arc_reclaim_thr_cv);
2627 if (arc_c >= arc_c_max)
2631 * If we're within (2 * maxblocksize) bytes of the target
2632 * cache size, increment the target cache size
2634 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2635 atomic_add_64(&arc_c, (int64_t)bytes);
2636 if (arc_c > arc_c_max)
2638 else if (state == arc_anon)
2639 atomic_add_64(&arc_p, (int64_t)bytes);
2643 ASSERT((int64_t)arc_p >= 0);
2647 * Check if the cache has reached its limits and eviction is required
2651 arc_evict_needed(arc_buf_contents_t type)
2653 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2659 * If zio data pages are being allocated out of a separate heap segment,
2660 * then enforce that the size of available vmem for this area remains
2661 * above about 1/32nd free.
2663 if (type == ARC_BUFC_DATA && zio_arena != NULL &&
2664 vmem_size(zio_arena, VMEM_FREE) <
2665 (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
2670 if (arc_reclaim_needed())
2673 return (arc_size > arc_c);
2677 * The buffer, supplied as the first argument, needs a data block.
2678 * So, if we are at cache max, determine which cache should be victimized.
2679 * We have the following cases:
2681 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2682 * In this situation if we're out of space, but the resident size of the MFU is
2683 * under the limit, victimize the MFU cache to satisfy this insertion request.
2685 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2686 * Here, we've used up all of the available space for the MRU, so we need to
2687 * evict from our own cache instead. Evict from the set of resident MRU
2690 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2691 * c minus p represents the MFU space in the cache, since p is the size of the
2692 * cache that is dedicated to the MRU. In this situation there's still space on
2693 * the MFU side, so the MRU side needs to be victimized.
2695 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2696 * MFU's resident set is consuming more space than it has been allotted. In
2697 * this situation, we must victimize our own cache, the MFU, for this insertion.
2700 arc_get_data_buf(arc_buf_t *buf)
2702 arc_state_t *state = buf->b_hdr->b_state;
2703 uint64_t size = buf->b_hdr->b_size;
2704 arc_buf_contents_t type = buf->b_hdr->b_type;
2706 arc_adapt(size, state);
2709 * We have not yet reached cache maximum size,
2710 * just allocate a new buffer.
2712 if (!arc_evict_needed(type)) {
2713 if (type == ARC_BUFC_METADATA) {
2714 buf->b_data = zio_buf_alloc(size);
2715 arc_space_consume(size, ARC_SPACE_DATA);
2717 ASSERT(type == ARC_BUFC_DATA);
2718 buf->b_data = zio_data_buf_alloc(size);
2719 ARCSTAT_INCR(arcstat_data_size, size);
2720 atomic_add_64(&arc_size, size);
2726 * If we are prefetching from the mfu ghost list, this buffer
2727 * will end up on the mru list; so steal space from there.
2729 if (state == arc_mfu_ghost)
2730 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2731 else if (state == arc_mru_ghost)
2734 if (state == arc_mru || state == arc_anon) {
2735 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2736 state = (arc_mfu->arcs_lsize[type] >= size &&
2737 arc_p > mru_used) ? arc_mfu : arc_mru;
2740 uint64_t mfu_space = arc_c - arc_p;
2741 state = (arc_mru->arcs_lsize[type] >= size &&
2742 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2744 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2745 if (type == ARC_BUFC_METADATA) {
2746 buf->b_data = zio_buf_alloc(size);
2747 arc_space_consume(size, ARC_SPACE_DATA);
2749 ASSERT(type == ARC_BUFC_DATA);
2750 buf->b_data = zio_data_buf_alloc(size);
2751 ARCSTAT_INCR(arcstat_data_size, size);
2752 atomic_add_64(&arc_size, size);
2754 ARCSTAT_BUMP(arcstat_recycle_miss);
2756 ASSERT(buf->b_data != NULL);
2759 * Update the state size. Note that ghost states have a
2760 * "ghost size" and so don't need to be updated.
2762 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2763 arc_buf_hdr_t *hdr = buf->b_hdr;
2765 atomic_add_64(&hdr->b_state->arcs_size, size);
2766 if (list_link_active(&hdr->b_arc_node)) {
2767 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2768 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2771 * If we are growing the cache, and we are adding anonymous
2772 * data, and we have outgrown arc_p, update arc_p
2774 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2775 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2776 arc_p = MIN(arc_c, arc_p + size);
2778 ARCSTAT_BUMP(arcstat_allocated);
2782 * This routine is called whenever a buffer is accessed.
2783 * NOTE: the hash lock is dropped in this function.
2786 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2790 ASSERT(MUTEX_HELD(hash_lock));
2792 if (buf->b_state == arc_anon) {
2794 * This buffer is not in the cache, and does not
2795 * appear in our "ghost" list. Add the new buffer
2799 ASSERT(buf->b_arc_access == 0);
2800 buf->b_arc_access = ddi_get_lbolt();
2801 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2802 arc_change_state(arc_mru, buf, hash_lock);
2804 } else if (buf->b_state == arc_mru) {
2805 now = ddi_get_lbolt();
2808 * If this buffer is here because of a prefetch, then either:
2809 * - clear the flag if this is a "referencing" read
2810 * (any subsequent access will bump this into the MFU state).
2812 * - move the buffer to the head of the list if this is
2813 * another prefetch (to make it less likely to be evicted).
2815 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2816 if (refcount_count(&buf->b_refcnt) == 0) {
2817 ASSERT(list_link_active(&buf->b_arc_node));
2819 buf->b_flags &= ~ARC_PREFETCH;
2820 ARCSTAT_BUMP(arcstat_mru_hits);
2822 buf->b_arc_access = now;
2827 * This buffer has been "accessed" only once so far,
2828 * but it is still in the cache. Move it to the MFU
2831 if (now > buf->b_arc_access + ARC_MINTIME) {
2833 * More than 125ms have passed since we
2834 * instantiated this buffer. Move it to the
2835 * most frequently used state.
2837 buf->b_arc_access = now;
2838 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2839 arc_change_state(arc_mfu, buf, hash_lock);
2841 ARCSTAT_BUMP(arcstat_mru_hits);
2842 } else if (buf->b_state == arc_mru_ghost) {
2843 arc_state_t *new_state;
2845 * This buffer has been "accessed" recently, but
2846 * was evicted from the cache. Move it to the
2850 if (buf->b_flags & ARC_PREFETCH) {
2851 new_state = arc_mru;
2852 if (refcount_count(&buf->b_refcnt) > 0)
2853 buf->b_flags &= ~ARC_PREFETCH;
2854 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2856 new_state = arc_mfu;
2857 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2860 buf->b_arc_access = ddi_get_lbolt();
2861 arc_change_state(new_state, buf, hash_lock);
2863 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2864 } else if (buf->b_state == arc_mfu) {
2866 * This buffer has been accessed more than once and is
2867 * still in the cache. Keep it in the MFU state.
2869 * NOTE: an add_reference() that occurred when we did
2870 * the arc_read() will have kicked this off the list.
2871 * If it was a prefetch, we will explicitly move it to
2872 * the head of the list now.
2874 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2875 ASSERT(refcount_count(&buf->b_refcnt) == 0);
2876 ASSERT(list_link_active(&buf->b_arc_node));
2878 ARCSTAT_BUMP(arcstat_mfu_hits);
2879 buf->b_arc_access = ddi_get_lbolt();
2880 } else if (buf->b_state == arc_mfu_ghost) {
2881 arc_state_t *new_state = arc_mfu;
2883 * This buffer has been accessed more than once but has
2884 * been evicted from the cache. Move it back to the
2888 if (buf->b_flags & ARC_PREFETCH) {
2890 * This is a prefetch access...
2891 * move this block back to the MRU state.
2893 ASSERT0(refcount_count(&buf->b_refcnt));
2894 new_state = arc_mru;
2897 buf->b_arc_access = ddi_get_lbolt();
2898 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2899 arc_change_state(new_state, buf, hash_lock);
2901 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2902 } else if (buf->b_state == arc_l2c_only) {
2904 * This buffer is on the 2nd Level ARC.
2907 buf->b_arc_access = ddi_get_lbolt();
2908 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2909 arc_change_state(arc_mfu, buf, hash_lock);
2911 ASSERT(!"invalid arc state");
2915 /* a generic arc_done_func_t which you can use */
2918 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2920 if (zio == NULL || zio->io_error == 0)
2921 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2922 VERIFY(arc_buf_remove_ref(buf, arg));
2925 /* a generic arc_done_func_t */
2927 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2929 arc_buf_t **bufp = arg;
2930 if (zio && zio->io_error) {
2931 VERIFY(arc_buf_remove_ref(buf, arg));
2935 ASSERT(buf->b_data);
2940 arc_read_done(zio_t *zio)
2942 arc_buf_hdr_t *hdr, *found;
2944 arc_buf_t *abuf; /* buffer we're assigning to callback */
2945 kmutex_t *hash_lock;
2946 arc_callback_t *callback_list, *acb;
2947 int freeable = FALSE;
2949 buf = zio->io_private;
2953 * The hdr was inserted into hash-table and removed from lists
2954 * prior to starting I/O. We should find this header, since
2955 * it's in the hash table, and it should be legit since it's
2956 * not possible to evict it during the I/O. The only possible
2957 * reason for it not to be found is if we were freed during the
2960 found = buf_hash_find(hdr->b_spa, &hdr->b_dva, hdr->b_birth,
2963 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
2964 (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2965 (found == hdr && HDR_L2_READING(hdr)));
2967 hdr->b_flags &= ~ARC_L2_EVICTED;
2968 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2969 hdr->b_flags &= ~ARC_L2CACHE;
2971 /* byteswap if necessary */
2972 callback_list = hdr->b_acb;
2973 ASSERT(callback_list != NULL);
2974 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
2975 dmu_object_byteswap_t bswap =
2976 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
2977 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2978 byteswap_uint64_array :
2979 dmu_ot_byteswap[bswap].ob_func;
2980 func(buf->b_data, hdr->b_size);
2983 arc_cksum_compute(buf, B_FALSE);
2986 #endif /* illumos */
2988 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
2990 * Only call arc_access on anonymous buffers. This is because
2991 * if we've issued an I/O for an evicted buffer, we've already
2992 * called arc_access (to prevent any simultaneous readers from
2993 * getting confused).
2995 arc_access(hdr, hash_lock);
2998 /* create copies of the data buffer for the callers */
3000 for (acb = callback_list; acb; acb = acb->acb_next) {
3001 if (acb->acb_done) {
3003 ARCSTAT_BUMP(arcstat_duplicate_reads);
3004 abuf = arc_buf_clone(buf);
3006 acb->acb_buf = abuf;
3011 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3012 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3014 ASSERT(buf->b_efunc == NULL);
3015 ASSERT(hdr->b_datacnt == 1);
3016 hdr->b_flags |= ARC_BUF_AVAILABLE;
3019 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3021 if (zio->io_error != 0) {
3022 hdr->b_flags |= ARC_IO_ERROR;
3023 if (hdr->b_state != arc_anon)
3024 arc_change_state(arc_anon, hdr, hash_lock);
3025 if (HDR_IN_HASH_TABLE(hdr))
3026 buf_hash_remove(hdr);
3027 freeable = refcount_is_zero(&hdr->b_refcnt);
3031 * Broadcast before we drop the hash_lock to avoid the possibility
3032 * that the hdr (and hence the cv) might be freed before we get to
3033 * the cv_broadcast().
3035 cv_broadcast(&hdr->b_cv);
3038 mutex_exit(hash_lock);
3041 * This block was freed while we waited for the read to
3042 * complete. It has been removed from the hash table and
3043 * moved to the anonymous state (so that it won't show up
3046 ASSERT3P(hdr->b_state, ==, arc_anon);
3047 freeable = refcount_is_zero(&hdr->b_refcnt);
3050 /* execute each callback and free its structure */
3051 while ((acb = callback_list) != NULL) {
3053 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3055 if (acb->acb_zio_dummy != NULL) {
3056 acb->acb_zio_dummy->io_error = zio->io_error;
3057 zio_nowait(acb->acb_zio_dummy);
3060 callback_list = acb->acb_next;
3061 kmem_free(acb, sizeof (arc_callback_t));
3065 arc_hdr_destroy(hdr);
3069 * "Read" the block block at the specified DVA (in bp) via the
3070 * cache. If the block is found in the cache, invoke the provided
3071 * callback immediately and return. Note that the `zio' parameter
3072 * in the callback will be NULL in this case, since no IO was
3073 * required. If the block is not in the cache pass the read request
3074 * on to the spa with a substitute callback function, so that the
3075 * requested block will be added to the cache.
3077 * If a read request arrives for a block that has a read in-progress,
3078 * either wait for the in-progress read to complete (and return the
3079 * results); or, if this is a read with a "done" func, add a record
3080 * to the read to invoke the "done" func when the read completes,
3081 * and return; or just return.
3083 * arc_read_done() will invoke all the requested "done" functions
3084 * for readers of this block.
3087 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3088 void *private, int priority, int zio_flags, uint32_t *arc_flags,
3089 const zbookmark_t *zb)
3092 arc_buf_t *buf = NULL;
3093 kmutex_t *hash_lock;
3095 uint64_t guid = spa_load_guid(spa);
3098 hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3100 if (hdr && hdr->b_datacnt > 0) {
3102 *arc_flags |= ARC_CACHED;
3104 if (HDR_IO_IN_PROGRESS(hdr)) {
3106 if (*arc_flags & ARC_WAIT) {
3107 cv_wait(&hdr->b_cv, hash_lock);
3108 mutex_exit(hash_lock);
3111 ASSERT(*arc_flags & ARC_NOWAIT);
3114 arc_callback_t *acb = NULL;
3116 acb = kmem_zalloc(sizeof (arc_callback_t),
3118 acb->acb_done = done;
3119 acb->acb_private = private;
3121 acb->acb_zio_dummy = zio_null(pio,
3122 spa, NULL, NULL, NULL, zio_flags);
3124 ASSERT(acb->acb_done != NULL);
3125 acb->acb_next = hdr->b_acb;
3127 add_reference(hdr, hash_lock, private);
3128 mutex_exit(hash_lock);
3131 mutex_exit(hash_lock);
3135 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3138 add_reference(hdr, hash_lock, private);
3140 * If this block is already in use, create a new
3141 * copy of the data so that we will be guaranteed
3142 * that arc_release() will always succeed.
3146 ASSERT(buf->b_data);
3147 if (HDR_BUF_AVAILABLE(hdr)) {
3148 ASSERT(buf->b_efunc == NULL);
3149 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3151 buf = arc_buf_clone(buf);
3154 } else if (*arc_flags & ARC_PREFETCH &&
3155 refcount_count(&hdr->b_refcnt) == 0) {
3156 hdr->b_flags |= ARC_PREFETCH;
3158 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3159 arc_access(hdr, hash_lock);
3160 if (*arc_flags & ARC_L2CACHE)
3161 hdr->b_flags |= ARC_L2CACHE;
3162 if (*arc_flags & ARC_L2COMPRESS)
3163 hdr->b_flags |= ARC_L2COMPRESS;
3164 mutex_exit(hash_lock);
3165 ARCSTAT_BUMP(arcstat_hits);
3166 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3167 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3168 data, metadata, hits);
3171 done(NULL, buf, private);
3173 uint64_t size = BP_GET_LSIZE(bp);
3174 arc_callback_t *acb;
3177 boolean_t devw = B_FALSE;
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_L2CACHE(hdr) && 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;
3252 * Lock out device removal.
3254 if (vdev_is_dead(vd) ||
3255 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3259 mutex_exit(hash_lock);
3262 * At this point, we have a level 1 cache miss. Try again in
3263 * L2ARC if possible.
3265 ASSERT3U(hdr->b_size, ==, size);
3266 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3267 uint64_t, size, zbookmark_t *, zb);
3268 ARCSTAT_BUMP(arcstat_misses);
3269 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3270 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3271 data, metadata, misses);
3273 curthread->td_ru.ru_inblock++;
3276 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3278 * Read from the L2ARC if the following are true:
3279 * 1. The L2ARC vdev was previously cached.
3280 * 2. This buffer still has L2ARC metadata.
3281 * 3. This buffer isn't currently writing to the L2ARC.
3282 * 4. The L2ARC entry wasn't evicted, which may
3283 * also have invalidated the vdev.
3284 * 5. This isn't prefetch and l2arc_noprefetch is set.
3286 if (hdr->b_l2hdr != NULL &&
3287 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3288 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3289 l2arc_read_callback_t *cb;
3291 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3292 ARCSTAT_BUMP(arcstat_l2_hits);
3294 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3296 cb->l2rcb_buf = buf;
3297 cb->l2rcb_spa = spa;
3300 cb->l2rcb_flags = zio_flags;
3301 cb->l2rcb_compress = hdr->b_l2hdr->b_compress;
3303 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3304 addr + size < vd->vdev_psize -
3305 VDEV_LABEL_END_SIZE);
3308 * l2arc read. The SCL_L2ARC lock will be
3309 * released by l2arc_read_done().
3310 * Issue a null zio if the underlying buffer
3311 * was squashed to zero size by compression.
3313 if (hdr->b_l2hdr->b_compress ==
3314 ZIO_COMPRESS_EMPTY) {
3315 rzio = zio_null(pio, spa, vd,
3316 l2arc_read_done, cb,
3317 zio_flags | ZIO_FLAG_DONT_CACHE |
3319 ZIO_FLAG_DONT_PROPAGATE |
3320 ZIO_FLAG_DONT_RETRY);
3322 rzio = zio_read_phys(pio, vd, addr,
3323 hdr->b_l2hdr->b_asize,
3324 buf->b_data, ZIO_CHECKSUM_OFF,
3325 l2arc_read_done, cb, priority,
3326 zio_flags | ZIO_FLAG_DONT_CACHE |
3328 ZIO_FLAG_DONT_PROPAGATE |
3329 ZIO_FLAG_DONT_RETRY, B_FALSE);
3331 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3333 ARCSTAT_INCR(arcstat_l2_read_bytes,
3334 hdr->b_l2hdr->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;
3546 buf_size = hdr->b_size;
3549 * Do we have more than one buf?
3551 if (hdr->b_datacnt > 1) {
3552 arc_buf_hdr_t *nhdr;
3554 uint64_t blksz = hdr->b_size;
3555 uint64_t spa = hdr->b_spa;
3556 arc_buf_contents_t type = hdr->b_type;
3557 uint32_t flags = hdr->b_flags;
3559 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3561 * Pull the data off of this hdr and attach it to
3562 * a new anonymous hdr.
3564 (void) remove_reference(hdr, hash_lock, tag);
3566 while (*bufp != buf)
3567 bufp = &(*bufp)->b_next;
3568 *bufp = buf->b_next;
3571 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3572 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3573 if (refcount_is_zero(&hdr->b_refcnt)) {
3574 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3575 ASSERT3U(*size, >=, hdr->b_size);
3576 atomic_add_64(size, -hdr->b_size);
3580 * We're releasing a duplicate user data buffer, update
3581 * our statistics accordingly.
3583 if (hdr->b_type == ARC_BUFC_DATA) {
3584 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3585 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3588 hdr->b_datacnt -= 1;
3589 arc_cksum_verify(buf);
3591 arc_buf_unwatch(buf);
3592 #endif /* illumos */
3594 mutex_exit(hash_lock);
3596 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3597 nhdr->b_size = blksz;
3599 nhdr->b_type = type;
3601 nhdr->b_state = arc_anon;
3602 nhdr->b_arc_access = 0;
3603 nhdr->b_flags = flags & ARC_L2_WRITING;
3604 nhdr->b_l2hdr = NULL;
3605 nhdr->b_datacnt = 1;
3606 nhdr->b_freeze_cksum = NULL;
3607 (void) refcount_add(&nhdr->b_refcnt, tag);
3609 mutex_exit(&buf->b_evict_lock);
3610 atomic_add_64(&arc_anon->arcs_size, blksz);
3612 mutex_exit(&buf->b_evict_lock);
3613 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3614 ASSERT(!list_link_active(&hdr->b_arc_node));
3615 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3616 if (hdr->b_state != arc_anon)
3617 arc_change_state(arc_anon, hdr, hash_lock);
3618 hdr->b_arc_access = 0;
3620 mutex_exit(hash_lock);
3622 buf_discard_identity(hdr);
3625 buf->b_efunc = NULL;
3626 buf->b_private = NULL;
3629 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3630 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3632 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
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 therefor 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);