4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
24 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
25 * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
29 * DVA-based Adjustable Replacement Cache
31 * While much of the theory of operation used here is
32 * based on the self-tuning, low overhead replacement cache
33 * presented by Megiddo and Modha at FAST 2003, there are some
34 * significant differences:
36 * 1. The Megiddo and Modha model assumes any page is evictable.
37 * Pages in its cache cannot be "locked" into memory. This makes
38 * the eviction algorithm simple: evict the last page in the list.
39 * This also make the performance characteristics easy to reason
40 * about. Our cache is not so simple. At any given moment, some
41 * subset of the blocks in the cache are un-evictable because we
42 * have handed out a reference to them. Blocks are only evictable
43 * when there are no external references active. This makes
44 * eviction far more problematic: we choose to evict the evictable
45 * blocks that are the "lowest" in the list.
47 * There are times when it is not possible to evict the requested
48 * space. In these circumstances we are unable to adjust the cache
49 * size. To prevent the cache growing unbounded at these times we
50 * implement a "cache throttle" that slows the flow of new data
51 * into the cache until we can make space available.
53 * 2. The Megiddo and Modha model assumes a fixed cache size.
54 * Pages are evicted when the cache is full and there is a cache
55 * miss. Our model has a variable sized cache. It grows with
56 * high use, but also tries to react to memory pressure from the
57 * operating system: decreasing its size when system memory is
60 * 3. The Megiddo and Modha model assumes a fixed page size. All
61 * elements of the cache are therefore exactly the same size. So
62 * when adjusting the cache size following a cache miss, its simply
63 * a matter of choosing a single page to evict. In our model, we
64 * have variable sized cache blocks (rangeing from 512 bytes to
65 * 128K bytes). We therefore choose a set of blocks to evict to make
66 * space for a cache miss that approximates as closely as possible
67 * the space used by the new block.
69 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70 * by N. Megiddo & D. Modha, FAST 2003
76 * A new reference to a cache buffer can be obtained in two
77 * ways: 1) via a hash table lookup using the DVA as a key,
78 * or 2) via one of the ARC lists. The arc_read() interface
79 * uses method 1, while the internal arc algorithms for
80 * adjusting the cache use method 2. We therefore provide two
81 * types of locks: 1) the hash table lock array, and 2) the
84 * Buffers do not have their own mutexs, rather they rely on the
85 * hash table mutexs for the bulk of their protection (i.e. most
86 * fields in the arc_buf_hdr_t are protected by these mutexs).
88 * buf_hash_find() returns the appropriate mutex (held) when it
89 * locates the requested buffer in the hash table. It returns
90 * NULL for the mutex if the buffer was not in the table.
92 * buf_hash_remove() expects the appropriate hash mutex to be
93 * already held before it is invoked.
95 * Each arc state also has a mutex which is used to protect the
96 * buffer list associated with the state. When attempting to
97 * obtain a hash table lock while holding an arc list lock you
98 * must use: mutex_tryenter() to avoid deadlock. Also note that
99 * the active state mutex must be held before the ghost state mutex.
101 * Arc buffers may have an associated eviction callback function.
102 * This function will be invoked prior to removing the buffer (e.g.
103 * in arc_do_user_evicts()). Note however that the data associated
104 * with the buffer may be evicted prior to the callback. The callback
105 * must be made with *no locks held* (to prevent deadlock). Additionally,
106 * the users of callbacks must ensure that their private data is
107 * protected from simultaneous callbacks from arc_clear_callback()
108 * and arc_do_user_evicts().
110 * Note that the majority of the performance stats are manipulated
111 * with atomic operations.
113 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
115 * - L2ARC buflist creation
116 * - L2ARC buflist eviction
117 * - L2ARC write completion, which walks L2ARC buflists
118 * - ARC header destruction, as it removes from L2ARC buflists
119 * - ARC header release, as it removes from L2ARC buflists
124 #include <sys/zio_compress.h>
125 #include <sys/zfs_context.h>
127 #include <sys/refcount.h>
128 #include <sys/vdev.h>
129 #include <sys/vdev_impl.h>
130 #include <sys/dsl_pool.h>
132 #include <sys/dnlc.h>
134 #include <sys/callb.h>
135 #include <sys/kstat.h>
136 #include <sys/trim_map.h>
137 #include <zfs_fletcher.h>
140 #include <vm/vm_pageout.h>
141 #include <machine/vmparam.h>
145 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
146 boolean_t arc_watch = B_FALSE;
151 static kmutex_t arc_reclaim_thr_lock;
152 static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
153 static uint8_t arc_thread_exit;
155 #define ARC_REDUCE_DNLC_PERCENT 3
156 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
158 typedef enum arc_reclaim_strategy {
159 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
160 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
161 } arc_reclaim_strategy_t;
164 * The number of iterations through arc_evict_*() before we
165 * drop & reacquire the lock.
167 int arc_evict_iterations = 100;
169 /* number of seconds before growing cache again */
170 static int arc_grow_retry = 60;
172 /* shift of arc_c for calculating both min and max arc_p */
173 static int arc_p_min_shift = 4;
175 /* log2(fraction of arc to reclaim) */
176 static int arc_shrink_shift = 5;
179 * minimum lifespan of a prefetch block in clock ticks
180 * (initialized in arc_init())
182 static int arc_min_prefetch_lifespan;
185 * If this percent of memory is free, don't throttle.
187 int arc_lotsfree_percent = 10;
190 extern int zfs_prefetch_disable;
193 * The arc has filled available memory and has now warmed up.
195 static boolean_t arc_warm;
197 uint64_t zfs_arc_max;
198 uint64_t zfs_arc_min;
199 uint64_t zfs_arc_meta_limit = 0;
200 int zfs_arc_grow_retry = 0;
201 int zfs_arc_shrink_shift = 0;
202 int zfs_arc_p_min_shift = 0;
203 int zfs_disable_dup_eviction = 0;
204 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
205 u_int zfs_arc_free_target = 0;
207 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
208 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
212 arc_free_target_init(void *unused __unused)
215 zfs_arc_free_target = vm_pageout_wakeup_thresh;
217 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
218 arc_free_target_init, NULL);
220 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
221 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
222 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
223 TUNABLE_QUAD("vfs.zfs.arc_average_blocksize", &zfs_arc_average_blocksize);
224 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
225 SYSCTL_DECL(_vfs_zfs);
226 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
228 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
230 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
231 &zfs_arc_average_blocksize, 0,
232 "ARC average blocksize");
233 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
234 &arc_shrink_shift, 0,
235 "log2(fraction of arc to reclaim)");
238 * We don't have a tunable for arc_free_target due to the dependency on
239 * pagedaemon initialisation.
241 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
242 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
243 sysctl_vfs_zfs_arc_free_target, "IU",
244 "Desired number of free pages below which ARC triggers reclaim");
247 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
252 val = zfs_arc_free_target;
253 err = sysctl_handle_int(oidp, &val, 0, req);
254 if (err != 0 || req->newptr == NULL)
259 if (val > cnt.v_page_count)
262 zfs_arc_free_target = val;
268 * Must be declared here, before the definition of corresponding kstat
269 * macro which uses the same names will confuse the compiler.
271 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
272 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
273 sysctl_vfs_zfs_arc_meta_limit, "QU",
274 "ARC metadata limit");
278 * Note that buffers can be in one of 6 states:
279 * ARC_anon - anonymous (discussed below)
280 * ARC_mru - recently used, currently cached
281 * ARC_mru_ghost - recentely used, no longer in cache
282 * ARC_mfu - frequently used, currently cached
283 * ARC_mfu_ghost - frequently used, no longer in cache
284 * ARC_l2c_only - exists in L2ARC but not other states
285 * When there are no active references to the buffer, they are
286 * are linked onto a list in one of these arc states. These are
287 * the only buffers that can be evicted or deleted. Within each
288 * state there are multiple lists, one for meta-data and one for
289 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
290 * etc.) is tracked separately so that it can be managed more
291 * explicitly: favored over data, limited explicitly.
293 * Anonymous buffers are buffers that are not associated with
294 * a DVA. These are buffers that hold dirty block copies
295 * before they are written to stable storage. By definition,
296 * they are "ref'd" and are considered part of arc_mru
297 * that cannot be freed. Generally, they will aquire a DVA
298 * as they are written and migrate onto the arc_mru list.
300 * The ARC_l2c_only state is for buffers that are in the second
301 * level ARC but no longer in any of the ARC_m* lists. The second
302 * level ARC itself may also contain buffers that are in any of
303 * the ARC_m* states - meaning that a buffer can exist in two
304 * places. The reason for the ARC_l2c_only state is to keep the
305 * buffer header in the hash table, so that reads that hit the
306 * second level ARC benefit from these fast lookups.
309 #define ARCS_LOCK_PAD CACHE_LINE_SIZE
313 unsigned char pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
318 * must be power of two for mask use to work
321 #define ARC_BUFC_NUMDATALISTS 16
322 #define ARC_BUFC_NUMMETADATALISTS 16
323 #define ARC_BUFC_NUMLISTS (ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
325 typedef struct arc_state {
326 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
327 uint64_t arcs_size; /* total amount of data in this state */
328 list_t arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
329 struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
332 #define ARCS_LOCK(s, i) (&((s)->arcs_locks[(i)].arcs_lock))
335 static arc_state_t ARC_anon;
336 static arc_state_t ARC_mru;
337 static arc_state_t ARC_mru_ghost;
338 static arc_state_t ARC_mfu;
339 static arc_state_t ARC_mfu_ghost;
340 static arc_state_t ARC_l2c_only;
342 typedef struct arc_stats {
343 kstat_named_t arcstat_hits;
344 kstat_named_t arcstat_misses;
345 kstat_named_t arcstat_demand_data_hits;
346 kstat_named_t arcstat_demand_data_misses;
347 kstat_named_t arcstat_demand_metadata_hits;
348 kstat_named_t arcstat_demand_metadata_misses;
349 kstat_named_t arcstat_prefetch_data_hits;
350 kstat_named_t arcstat_prefetch_data_misses;
351 kstat_named_t arcstat_prefetch_metadata_hits;
352 kstat_named_t arcstat_prefetch_metadata_misses;
353 kstat_named_t arcstat_mru_hits;
354 kstat_named_t arcstat_mru_ghost_hits;
355 kstat_named_t arcstat_mfu_hits;
356 kstat_named_t arcstat_mfu_ghost_hits;
357 kstat_named_t arcstat_allocated;
358 kstat_named_t arcstat_deleted;
359 kstat_named_t arcstat_stolen;
360 kstat_named_t arcstat_recycle_miss;
362 * Number of buffers that could not be evicted because the hash lock
363 * was held by another thread. The lock may not necessarily be held
364 * by something using the same buffer, since hash locks are shared
365 * by multiple buffers.
367 kstat_named_t arcstat_mutex_miss;
369 * Number of buffers skipped because they have I/O in progress, are
370 * indrect prefetch buffers that have not lived long enough, or are
371 * not from the spa we're trying to evict from.
373 kstat_named_t arcstat_evict_skip;
374 kstat_named_t arcstat_evict_l2_cached;
375 kstat_named_t arcstat_evict_l2_eligible;
376 kstat_named_t arcstat_evict_l2_ineligible;
377 kstat_named_t arcstat_hash_elements;
378 kstat_named_t arcstat_hash_elements_max;
379 kstat_named_t arcstat_hash_collisions;
380 kstat_named_t arcstat_hash_chains;
381 kstat_named_t arcstat_hash_chain_max;
382 kstat_named_t arcstat_p;
383 kstat_named_t arcstat_c;
384 kstat_named_t arcstat_c_min;
385 kstat_named_t arcstat_c_max;
386 kstat_named_t arcstat_size;
387 kstat_named_t arcstat_hdr_size;
388 kstat_named_t arcstat_data_size;
389 kstat_named_t arcstat_other_size;
390 kstat_named_t arcstat_l2_hits;
391 kstat_named_t arcstat_l2_misses;
392 kstat_named_t arcstat_l2_feeds;
393 kstat_named_t arcstat_l2_rw_clash;
394 kstat_named_t arcstat_l2_read_bytes;
395 kstat_named_t arcstat_l2_write_bytes;
396 kstat_named_t arcstat_l2_writes_sent;
397 kstat_named_t arcstat_l2_writes_done;
398 kstat_named_t arcstat_l2_writes_error;
399 kstat_named_t arcstat_l2_writes_hdr_miss;
400 kstat_named_t arcstat_l2_evict_lock_retry;
401 kstat_named_t arcstat_l2_evict_reading;
402 kstat_named_t arcstat_l2_free_on_write;
403 kstat_named_t arcstat_l2_cdata_free_on_write;
404 kstat_named_t arcstat_l2_abort_lowmem;
405 kstat_named_t arcstat_l2_cksum_bad;
406 kstat_named_t arcstat_l2_io_error;
407 kstat_named_t arcstat_l2_size;
408 kstat_named_t arcstat_l2_asize;
409 kstat_named_t arcstat_l2_hdr_size;
410 kstat_named_t arcstat_l2_compress_successes;
411 kstat_named_t arcstat_l2_compress_zeros;
412 kstat_named_t arcstat_l2_compress_failures;
413 kstat_named_t arcstat_l2_write_trylock_fail;
414 kstat_named_t arcstat_l2_write_passed_headroom;
415 kstat_named_t arcstat_l2_write_spa_mismatch;
416 kstat_named_t arcstat_l2_write_in_l2;
417 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
418 kstat_named_t arcstat_l2_write_not_cacheable;
419 kstat_named_t arcstat_l2_write_full;
420 kstat_named_t arcstat_l2_write_buffer_iter;
421 kstat_named_t arcstat_l2_write_pios;
422 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
423 kstat_named_t arcstat_l2_write_buffer_list_iter;
424 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
425 kstat_named_t arcstat_memory_throttle_count;
426 kstat_named_t arcstat_duplicate_buffers;
427 kstat_named_t arcstat_duplicate_buffers_size;
428 kstat_named_t arcstat_duplicate_reads;
429 kstat_named_t arcstat_meta_used;
430 kstat_named_t arcstat_meta_limit;
431 kstat_named_t arcstat_meta_max;
434 static arc_stats_t arc_stats = {
435 { "hits", KSTAT_DATA_UINT64 },
436 { "misses", KSTAT_DATA_UINT64 },
437 { "demand_data_hits", KSTAT_DATA_UINT64 },
438 { "demand_data_misses", KSTAT_DATA_UINT64 },
439 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
440 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
441 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
442 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
443 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
444 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
445 { "mru_hits", KSTAT_DATA_UINT64 },
446 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
447 { "mfu_hits", KSTAT_DATA_UINT64 },
448 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
449 { "allocated", KSTAT_DATA_UINT64 },
450 { "deleted", KSTAT_DATA_UINT64 },
451 { "stolen", KSTAT_DATA_UINT64 },
452 { "recycle_miss", KSTAT_DATA_UINT64 },
453 { "mutex_miss", KSTAT_DATA_UINT64 },
454 { "evict_skip", KSTAT_DATA_UINT64 },
455 { "evict_l2_cached", KSTAT_DATA_UINT64 },
456 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
457 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
458 { "hash_elements", KSTAT_DATA_UINT64 },
459 { "hash_elements_max", KSTAT_DATA_UINT64 },
460 { "hash_collisions", KSTAT_DATA_UINT64 },
461 { "hash_chains", KSTAT_DATA_UINT64 },
462 { "hash_chain_max", KSTAT_DATA_UINT64 },
463 { "p", KSTAT_DATA_UINT64 },
464 { "c", KSTAT_DATA_UINT64 },
465 { "c_min", KSTAT_DATA_UINT64 },
466 { "c_max", KSTAT_DATA_UINT64 },
467 { "size", KSTAT_DATA_UINT64 },
468 { "hdr_size", KSTAT_DATA_UINT64 },
469 { "data_size", KSTAT_DATA_UINT64 },
470 { "other_size", KSTAT_DATA_UINT64 },
471 { "l2_hits", KSTAT_DATA_UINT64 },
472 { "l2_misses", KSTAT_DATA_UINT64 },
473 { "l2_feeds", KSTAT_DATA_UINT64 },
474 { "l2_rw_clash", KSTAT_DATA_UINT64 },
475 { "l2_read_bytes", KSTAT_DATA_UINT64 },
476 { "l2_write_bytes", KSTAT_DATA_UINT64 },
477 { "l2_writes_sent", KSTAT_DATA_UINT64 },
478 { "l2_writes_done", KSTAT_DATA_UINT64 },
479 { "l2_writes_error", KSTAT_DATA_UINT64 },
480 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
481 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
482 { "l2_evict_reading", KSTAT_DATA_UINT64 },
483 { "l2_free_on_write", KSTAT_DATA_UINT64 },
484 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
485 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
486 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
487 { "l2_io_error", KSTAT_DATA_UINT64 },
488 { "l2_size", KSTAT_DATA_UINT64 },
489 { "l2_asize", KSTAT_DATA_UINT64 },
490 { "l2_hdr_size", KSTAT_DATA_UINT64 },
491 { "l2_compress_successes", KSTAT_DATA_UINT64 },
492 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
493 { "l2_compress_failures", KSTAT_DATA_UINT64 },
494 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
495 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
496 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
497 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
498 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
499 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
500 { "l2_write_full", KSTAT_DATA_UINT64 },
501 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
502 { "l2_write_pios", KSTAT_DATA_UINT64 },
503 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
504 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
505 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
506 { "memory_throttle_count", KSTAT_DATA_UINT64 },
507 { "duplicate_buffers", KSTAT_DATA_UINT64 },
508 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
509 { "duplicate_reads", KSTAT_DATA_UINT64 },
510 { "arc_meta_used", KSTAT_DATA_UINT64 },
511 { "arc_meta_limit", KSTAT_DATA_UINT64 },
512 { "arc_meta_max", KSTAT_DATA_UINT64 }
515 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
517 #define ARCSTAT_INCR(stat, val) \
518 atomic_add_64(&arc_stats.stat.value.ui64, (val))
520 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
521 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
523 #define ARCSTAT_MAX(stat, val) { \
525 while ((val) > (m = arc_stats.stat.value.ui64) && \
526 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
530 #define ARCSTAT_MAXSTAT(stat) \
531 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
534 * We define a macro to allow ARC hits/misses to be easily broken down by
535 * two separate conditions, giving a total of four different subtypes for
536 * each of hits and misses (so eight statistics total).
538 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
541 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
543 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
547 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
549 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
554 static arc_state_t *arc_anon;
555 static arc_state_t *arc_mru;
556 static arc_state_t *arc_mru_ghost;
557 static arc_state_t *arc_mfu;
558 static arc_state_t *arc_mfu_ghost;
559 static arc_state_t *arc_l2c_only;
562 * There are several ARC variables that are critical to export as kstats --
563 * but we don't want to have to grovel around in the kstat whenever we wish to
564 * manipulate them. For these variables, we therefore define them to be in
565 * terms of the statistic variable. This assures that we are not introducing
566 * the possibility of inconsistency by having shadow copies of the variables,
567 * while still allowing the code to be readable.
569 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
570 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
571 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
572 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
573 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
574 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
575 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
576 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
578 #define L2ARC_IS_VALID_COMPRESS(_c_) \
579 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
581 static int arc_no_grow; /* Don't try to grow cache size */
582 static uint64_t arc_tempreserve;
583 static uint64_t arc_loaned_bytes;
585 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
587 typedef struct arc_callback arc_callback_t;
589 struct arc_callback {
591 arc_done_func_t *acb_done;
593 zio_t *acb_zio_dummy;
594 arc_callback_t *acb_next;
597 typedef struct arc_write_callback arc_write_callback_t;
599 struct arc_write_callback {
601 arc_done_func_t *awcb_ready;
602 arc_done_func_t *awcb_physdone;
603 arc_done_func_t *awcb_done;
608 /* protected by hash lock */
613 kmutex_t b_freeze_lock;
614 zio_cksum_t *b_freeze_cksum;
617 arc_buf_hdr_t *b_hash_next;
622 arc_callback_t *b_acb;
626 arc_buf_contents_t b_type;
630 /* protected by arc state mutex */
631 arc_state_t *b_state;
632 list_node_t b_arc_node;
634 /* updated atomically */
635 clock_t b_arc_access;
637 /* self protecting */
640 l2arc_buf_hdr_t *b_l2hdr;
641 list_node_t b_l2node;
646 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
651 val = arc_meta_limit;
652 err = sysctl_handle_64(oidp, &val, 0, req);
653 if (err != 0 || req->newptr == NULL)
656 if (val <= 0 || val > arc_c_max)
659 arc_meta_limit = val;
664 static arc_buf_t *arc_eviction_list;
665 static kmutex_t arc_eviction_mtx;
666 static arc_buf_hdr_t arc_eviction_hdr;
668 #define GHOST_STATE(state) \
669 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
670 (state) == arc_l2c_only)
672 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
673 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
674 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
675 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
676 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
677 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
678 #define HDR_FREE_IN_PROGRESS(hdr) \
679 ((hdr)->b_flags & ARC_FLAG_FREE_IN_PROGRESS)
680 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
681 #define HDR_L2_READING(hdr) \
682 ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS && \
683 (hdr)->b_l2hdr != NULL)
684 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
685 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
686 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
692 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
693 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
696 * Hash table routines
699 #define HT_LOCK_PAD CACHE_LINE_SIZE
704 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
708 #define BUF_LOCKS 256
709 typedef struct buf_hash_table {
711 arc_buf_hdr_t **ht_table;
712 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
715 static buf_hash_table_t buf_hash_table;
717 #define BUF_HASH_INDEX(spa, dva, birth) \
718 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
719 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
720 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
721 #define HDR_LOCK(hdr) \
722 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
724 uint64_t zfs_crc64_table[256];
730 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
731 #define L2ARC_HEADROOM 2 /* num of writes */
733 * If we discover during ARC scan any buffers to be compressed, we boost
734 * our headroom for the next scanning cycle by this percentage multiple.
736 #define L2ARC_HEADROOM_BOOST 200
737 #define L2ARC_FEED_SECS 1 /* caching interval secs */
738 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
740 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
741 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
743 /* L2ARC Performance Tunables */
744 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
745 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
746 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
747 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
748 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
749 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
750 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
751 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
752 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
754 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
755 &l2arc_write_max, 0, "max write size");
756 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
757 &l2arc_write_boost, 0, "extra write during warmup");
758 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
759 &l2arc_headroom, 0, "number of dev writes");
760 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
761 &l2arc_feed_secs, 0, "interval seconds");
762 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
763 &l2arc_feed_min_ms, 0, "min interval milliseconds");
765 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
766 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
767 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
768 &l2arc_feed_again, 0, "turbo warmup");
769 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
770 &l2arc_norw, 0, "no reads during writes");
772 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
773 &ARC_anon.arcs_size, 0, "size of anonymous state");
774 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
775 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
776 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
777 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
779 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
780 &ARC_mru.arcs_size, 0, "size of mru state");
781 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
782 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
783 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
784 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
786 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
787 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
788 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
789 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
790 "size of metadata in mru ghost state");
791 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
792 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
793 "size of data in mru ghost state");
795 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
796 &ARC_mfu.arcs_size, 0, "size of mfu state");
797 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
798 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
799 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
800 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
802 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
803 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
804 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
805 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
806 "size of metadata in mfu ghost state");
807 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
808 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
809 "size of data in mfu ghost state");
811 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
812 &ARC_l2c_only.arcs_size, 0, "size of mru state");
817 typedef struct l2arc_dev {
818 vdev_t *l2ad_vdev; /* vdev */
819 spa_t *l2ad_spa; /* spa */
820 uint64_t l2ad_hand; /* next write location */
821 uint64_t l2ad_start; /* first addr on device */
822 uint64_t l2ad_end; /* last addr on device */
823 uint64_t l2ad_evict; /* last addr eviction reached */
824 boolean_t l2ad_first; /* first sweep through */
825 boolean_t l2ad_writing; /* currently writing */
826 list_t *l2ad_buflist; /* buffer list */
827 list_node_t l2ad_node; /* device list node */
830 static list_t L2ARC_dev_list; /* device list */
831 static list_t *l2arc_dev_list; /* device list pointer */
832 static kmutex_t l2arc_dev_mtx; /* device list mutex */
833 static l2arc_dev_t *l2arc_dev_last; /* last device used */
834 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
835 static list_t L2ARC_free_on_write; /* free after write buf list */
836 static list_t *l2arc_free_on_write; /* free after write list ptr */
837 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
838 static uint64_t l2arc_ndev; /* number of devices */
840 typedef struct l2arc_read_callback {
841 arc_buf_t *l2rcb_buf; /* read buffer */
842 spa_t *l2rcb_spa; /* spa */
843 blkptr_t l2rcb_bp; /* original blkptr */
844 zbookmark_phys_t l2rcb_zb; /* original bookmark */
845 int l2rcb_flags; /* original flags */
846 enum zio_compress l2rcb_compress; /* applied compress */
847 } l2arc_read_callback_t;
849 typedef struct l2arc_write_callback {
850 l2arc_dev_t *l2wcb_dev; /* device info */
851 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
852 } l2arc_write_callback_t;
854 struct l2arc_buf_hdr {
855 /* protected by arc_buf_hdr mutex */
856 l2arc_dev_t *b_dev; /* L2ARC device */
857 uint64_t b_daddr; /* disk address, offset byte */
858 /* compression applied to buffer data */
859 enum zio_compress b_compress;
860 /* real alloc'd buffer size depending on b_compress applied */
862 /* temporary buffer holder for in-flight compressed data */
866 typedef struct l2arc_data_free {
867 /* protected by l2arc_free_on_write_mtx */
870 void (*l2df_func)(void *, size_t);
871 list_node_t l2df_list_node;
874 static kmutex_t l2arc_feed_thr_lock;
875 static kcondvar_t l2arc_feed_thr_cv;
876 static uint8_t l2arc_thread_exit;
878 static void arc_get_data_buf(arc_buf_t *);
879 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
880 static int arc_evict_needed(arc_buf_contents_t);
881 static void arc_evict_ghost(arc_state_t *, uint64_t, int64_t);
882 static void arc_buf_watch(arc_buf_t *);
884 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
885 static void l2arc_read_done(zio_t *);
886 static void l2arc_hdr_stat_add(void);
887 static void l2arc_hdr_stat_remove(void);
889 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *);
890 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
891 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
894 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
896 uint8_t *vdva = (uint8_t *)dva;
897 uint64_t crc = -1ULL;
900 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
902 for (i = 0; i < sizeof (dva_t); i++)
903 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
905 crc ^= (spa>>8) ^ birth;
910 #define BUF_EMPTY(buf) \
911 ((buf)->b_dva.dva_word[0] == 0 && \
912 (buf)->b_dva.dva_word[1] == 0 && \
913 (buf)->b_cksum0 == 0)
915 #define BUF_EQUAL(spa, dva, birth, buf) \
916 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
917 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
918 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
921 buf_discard_identity(arc_buf_hdr_t *hdr)
923 hdr->b_dva.dva_word[0] = 0;
924 hdr->b_dva.dva_word[1] = 0;
929 static arc_buf_hdr_t *
930 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
932 const dva_t *dva = BP_IDENTITY(bp);
933 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
934 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
935 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
938 mutex_enter(hash_lock);
939 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
940 hdr = hdr->b_hash_next) {
941 if (BUF_EQUAL(spa, dva, birth, hdr)) {
946 mutex_exit(hash_lock);
952 * Insert an entry into the hash table. If there is already an element
953 * equal to elem in the hash table, then the already existing element
954 * will be returned and the new element will not be inserted.
955 * Otherwise returns NULL.
957 static arc_buf_hdr_t *
958 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
960 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
961 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
965 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
966 ASSERT(hdr->b_birth != 0);
967 ASSERT(!HDR_IN_HASH_TABLE(hdr));
969 mutex_enter(hash_lock);
970 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
971 fhdr = fhdr->b_hash_next, i++) {
972 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
976 hdr->b_hash_next = buf_hash_table.ht_table[idx];
977 buf_hash_table.ht_table[idx] = hdr;
978 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
980 /* collect some hash table performance data */
982 ARCSTAT_BUMP(arcstat_hash_collisions);
984 ARCSTAT_BUMP(arcstat_hash_chains);
986 ARCSTAT_MAX(arcstat_hash_chain_max, i);
989 ARCSTAT_BUMP(arcstat_hash_elements);
990 ARCSTAT_MAXSTAT(arcstat_hash_elements);
996 buf_hash_remove(arc_buf_hdr_t *hdr)
998 arc_buf_hdr_t *fhdr, **hdrp;
999 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1001 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1002 ASSERT(HDR_IN_HASH_TABLE(hdr));
1004 hdrp = &buf_hash_table.ht_table[idx];
1005 while ((fhdr = *hdrp) != hdr) {
1006 ASSERT(fhdr != NULL);
1007 hdrp = &fhdr->b_hash_next;
1009 *hdrp = hdr->b_hash_next;
1010 hdr->b_hash_next = NULL;
1011 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1013 /* collect some hash table performance data */
1014 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1016 if (buf_hash_table.ht_table[idx] &&
1017 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1018 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1022 * Global data structures and functions for the buf kmem cache.
1024 static kmem_cache_t *hdr_cache;
1025 static kmem_cache_t *buf_cache;
1032 kmem_free(buf_hash_table.ht_table,
1033 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1034 for (i = 0; i < BUF_LOCKS; i++)
1035 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1036 kmem_cache_destroy(hdr_cache);
1037 kmem_cache_destroy(buf_cache);
1041 * Constructor callback - called when the cache is empty
1042 * and a new buf is requested.
1046 hdr_cons(void *vbuf, void *unused, int kmflag)
1048 arc_buf_hdr_t *hdr = vbuf;
1050 bzero(hdr, sizeof (arc_buf_hdr_t));
1051 refcount_create(&hdr->b_refcnt);
1052 cv_init(&hdr->b_cv, NULL, CV_DEFAULT, NULL);
1053 mutex_init(&hdr->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1054 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1061 buf_cons(void *vbuf, void *unused, int kmflag)
1063 arc_buf_t *buf = vbuf;
1065 bzero(buf, sizeof (arc_buf_t));
1066 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1067 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1073 * Destructor callback - called when a cached buf is
1074 * no longer required.
1078 hdr_dest(void *vbuf, void *unused)
1080 arc_buf_hdr_t *hdr = vbuf;
1082 ASSERT(BUF_EMPTY(hdr));
1083 refcount_destroy(&hdr->b_refcnt);
1084 cv_destroy(&hdr->b_cv);
1085 mutex_destroy(&hdr->b_freeze_lock);
1086 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1091 buf_dest(void *vbuf, void *unused)
1093 arc_buf_t *buf = vbuf;
1095 mutex_destroy(&buf->b_evict_lock);
1096 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1100 * Reclaim callback -- invoked when memory is low.
1104 hdr_recl(void *unused)
1106 dprintf("hdr_recl called\n");
1108 * umem calls the reclaim func when we destroy the buf cache,
1109 * which is after we do arc_fini().
1112 cv_signal(&arc_reclaim_thr_cv);
1119 uint64_t hsize = 1ULL << 12;
1123 * The hash table is big enough to fill all of physical memory
1124 * with an average block size of zfs_arc_average_blocksize (default 8K).
1125 * By default, the table will take up
1126 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1128 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1131 buf_hash_table.ht_mask = hsize - 1;
1132 buf_hash_table.ht_table =
1133 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1134 if (buf_hash_table.ht_table == NULL) {
1135 ASSERT(hsize > (1ULL << 8));
1140 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1141 0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1142 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1143 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1145 for (i = 0; i < 256; i++)
1146 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1147 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1149 for (i = 0; i < BUF_LOCKS; i++) {
1150 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1151 NULL, MUTEX_DEFAULT, NULL);
1155 #define ARC_MINTIME (hz>>4) /* 62 ms */
1158 arc_cksum_verify(arc_buf_t *buf)
1162 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1165 mutex_enter(&buf->b_hdr->b_freeze_lock);
1166 if (buf->b_hdr->b_freeze_cksum == NULL ||
1167 (buf->b_hdr->b_flags & ARC_FLAG_IO_ERROR)) {
1168 mutex_exit(&buf->b_hdr->b_freeze_lock);
1171 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1172 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1173 panic("buffer modified while frozen!");
1174 mutex_exit(&buf->b_hdr->b_freeze_lock);
1178 arc_cksum_equal(arc_buf_t *buf)
1183 mutex_enter(&buf->b_hdr->b_freeze_lock);
1184 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1185 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1186 mutex_exit(&buf->b_hdr->b_freeze_lock);
1192 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1194 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1197 mutex_enter(&buf->b_hdr->b_freeze_lock);
1198 if (buf->b_hdr->b_freeze_cksum != NULL) {
1199 mutex_exit(&buf->b_hdr->b_freeze_lock);
1202 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1203 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1204 buf->b_hdr->b_freeze_cksum);
1205 mutex_exit(&buf->b_hdr->b_freeze_lock);
1208 #endif /* illumos */
1213 typedef struct procctl {
1221 arc_buf_unwatch(arc_buf_t *buf)
1228 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1229 ctl.prwatch.pr_size = 0;
1230 ctl.prwatch.pr_wflags = 0;
1231 result = write(arc_procfd, &ctl, sizeof (ctl));
1232 ASSERT3U(result, ==, sizeof (ctl));
1239 arc_buf_watch(arc_buf_t *buf)
1246 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1247 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1248 ctl.prwatch.pr_wflags = WA_WRITE;
1249 result = write(arc_procfd, &ctl, sizeof (ctl));
1250 ASSERT3U(result, ==, sizeof (ctl));
1254 #endif /* illumos */
1257 arc_buf_thaw(arc_buf_t *buf)
1259 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1260 if (buf->b_hdr->b_state != arc_anon)
1261 panic("modifying non-anon buffer!");
1262 if (buf->b_hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1263 panic("modifying buffer while i/o in progress!");
1264 arc_cksum_verify(buf);
1267 mutex_enter(&buf->b_hdr->b_freeze_lock);
1268 if (buf->b_hdr->b_freeze_cksum != NULL) {
1269 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1270 buf->b_hdr->b_freeze_cksum = NULL;
1273 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1274 if (buf->b_hdr->b_thawed)
1275 kmem_free(buf->b_hdr->b_thawed, 1);
1276 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1279 mutex_exit(&buf->b_hdr->b_freeze_lock);
1282 arc_buf_unwatch(buf);
1283 #endif /* illumos */
1287 arc_buf_freeze(arc_buf_t *buf)
1289 kmutex_t *hash_lock;
1291 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1294 hash_lock = HDR_LOCK(buf->b_hdr);
1295 mutex_enter(hash_lock);
1297 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1298 buf->b_hdr->b_state == arc_anon);
1299 arc_cksum_compute(buf, B_FALSE);
1300 mutex_exit(hash_lock);
1305 get_buf_info(arc_buf_hdr_t *hdr, arc_state_t *state, list_t **list, kmutex_t **lock)
1307 uint64_t buf_hashid = buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1309 if (hdr->b_type == ARC_BUFC_METADATA)
1310 buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1312 buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1313 buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1316 *list = &state->arcs_lists[buf_hashid];
1317 *lock = ARCS_LOCK(state, buf_hashid);
1322 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1324 ASSERT(MUTEX_HELD(hash_lock));
1326 if ((refcount_add(&hdr->b_refcnt, tag) == 1) &&
1327 (hdr->b_state != arc_anon)) {
1328 uint64_t delta = hdr->b_size * hdr->b_datacnt;
1329 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
1333 get_buf_info(hdr, hdr->b_state, &list, &lock);
1334 ASSERT(!MUTEX_HELD(lock));
1336 ASSERT(list_link_active(&hdr->b_arc_node));
1337 list_remove(list, hdr);
1338 if (GHOST_STATE(hdr->b_state)) {
1339 ASSERT0(hdr->b_datacnt);
1340 ASSERT3P(hdr->b_buf, ==, NULL);
1341 delta = hdr->b_size;
1344 ASSERT3U(*size, >=, delta);
1345 atomic_add_64(size, -delta);
1347 /* remove the prefetch flag if we get a reference */
1348 if (hdr->b_flags & ARC_FLAG_PREFETCH)
1349 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1354 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1357 arc_state_t *state = hdr->b_state;
1359 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1360 ASSERT(!GHOST_STATE(state));
1362 if (((cnt = refcount_remove(&hdr->b_refcnt, tag)) == 0) &&
1363 (state != arc_anon)) {
1364 uint64_t *size = &state->arcs_lsize[hdr->b_type];
1368 get_buf_info(hdr, state, &list, &lock);
1369 ASSERT(!MUTEX_HELD(lock));
1371 ASSERT(!list_link_active(&hdr->b_arc_node));
1372 list_insert_head(list, hdr);
1373 ASSERT(hdr->b_datacnt > 0);
1374 atomic_add_64(size, hdr->b_size * hdr->b_datacnt);
1381 * Move the supplied buffer to the indicated state. The mutex
1382 * for the buffer must be held by the caller.
1385 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1386 kmutex_t *hash_lock)
1388 arc_state_t *old_state = hdr->b_state;
1389 int64_t refcnt = refcount_count(&hdr->b_refcnt);
1390 uint64_t from_delta, to_delta;
1394 ASSERT(MUTEX_HELD(hash_lock));
1395 ASSERT3P(new_state, !=, old_state);
1396 ASSERT(refcnt == 0 || hdr->b_datacnt > 0);
1397 ASSERT(hdr->b_datacnt == 0 || !GHOST_STATE(new_state));
1398 ASSERT(hdr->b_datacnt <= 1 || old_state != arc_anon);
1400 from_delta = to_delta = hdr->b_datacnt * hdr->b_size;
1403 * If this buffer is evictable, transfer it from the
1404 * old state list to the new state list.
1407 if (old_state != arc_anon) {
1409 uint64_t *size = &old_state->arcs_lsize[hdr->b_type];
1411 get_buf_info(hdr, old_state, &list, &lock);
1412 use_mutex = !MUTEX_HELD(lock);
1416 ASSERT(list_link_active(&hdr->b_arc_node));
1417 list_remove(list, hdr);
1420 * If prefetching out of the ghost cache,
1421 * we will have a non-zero datacnt.
1423 if (GHOST_STATE(old_state) && hdr->b_datacnt == 0) {
1424 /* ghost elements have a ghost size */
1425 ASSERT(hdr->b_buf == NULL);
1426 from_delta = hdr->b_size;
1428 ASSERT3U(*size, >=, from_delta);
1429 atomic_add_64(size, -from_delta);
1434 if (new_state != arc_anon) {
1436 uint64_t *size = &new_state->arcs_lsize[hdr->b_type];
1438 get_buf_info(hdr, new_state, &list, &lock);
1439 use_mutex = !MUTEX_HELD(lock);
1443 list_insert_head(list, hdr);
1445 /* ghost elements have a ghost size */
1446 if (GHOST_STATE(new_state)) {
1447 ASSERT(hdr->b_datacnt == 0);
1448 ASSERT(hdr->b_buf == NULL);
1449 to_delta = hdr->b_size;
1451 atomic_add_64(size, to_delta);
1458 ASSERT(!BUF_EMPTY(hdr));
1459 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1460 buf_hash_remove(hdr);
1462 /* adjust state sizes */
1464 atomic_add_64(&new_state->arcs_size, to_delta);
1466 ASSERT3U(old_state->arcs_size, >=, from_delta);
1467 atomic_add_64(&old_state->arcs_size, -from_delta);
1469 hdr->b_state = new_state;
1471 /* adjust l2arc hdr stats */
1472 if (new_state == arc_l2c_only)
1473 l2arc_hdr_stat_add();
1474 else if (old_state == arc_l2c_only)
1475 l2arc_hdr_stat_remove();
1479 arc_space_consume(uint64_t space, arc_space_type_t type)
1481 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1484 case ARC_SPACE_DATA:
1485 ARCSTAT_INCR(arcstat_data_size, space);
1487 case ARC_SPACE_OTHER:
1488 ARCSTAT_INCR(arcstat_other_size, space);
1490 case ARC_SPACE_HDRS:
1491 ARCSTAT_INCR(arcstat_hdr_size, space);
1493 case ARC_SPACE_L2HDRS:
1494 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1498 ARCSTAT_INCR(arcstat_meta_used, space);
1499 atomic_add_64(&arc_size, space);
1503 arc_space_return(uint64_t space, arc_space_type_t type)
1505 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1508 case ARC_SPACE_DATA:
1509 ARCSTAT_INCR(arcstat_data_size, -space);
1511 case ARC_SPACE_OTHER:
1512 ARCSTAT_INCR(arcstat_other_size, -space);
1514 case ARC_SPACE_HDRS:
1515 ARCSTAT_INCR(arcstat_hdr_size, -space);
1517 case ARC_SPACE_L2HDRS:
1518 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1522 ASSERT(arc_meta_used >= space);
1523 if (arc_meta_max < arc_meta_used)
1524 arc_meta_max = arc_meta_used;
1525 ARCSTAT_INCR(arcstat_meta_used, -space);
1526 ASSERT(arc_size >= space);
1527 atomic_add_64(&arc_size, -space);
1531 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1536 ASSERT3U(size, >, 0);
1537 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1538 ASSERT(BUF_EMPTY(hdr));
1541 hdr->b_spa = spa_load_guid(spa);
1542 hdr->b_state = arc_anon;
1543 hdr->b_arc_access = 0;
1544 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1547 buf->b_efunc = NULL;
1548 buf->b_private = NULL;
1551 arc_get_data_buf(buf);
1554 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1555 (void) refcount_add(&hdr->b_refcnt, tag);
1560 static char *arc_onloan_tag = "onloan";
1563 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1564 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1565 * buffers must be returned to the arc before they can be used by the DMU or
1569 arc_loan_buf(spa_t *spa, int size)
1573 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1575 atomic_add_64(&arc_loaned_bytes, size);
1580 * Return a loaned arc buffer to the arc.
1583 arc_return_buf(arc_buf_t *buf, void *tag)
1585 arc_buf_hdr_t *hdr = buf->b_hdr;
1587 ASSERT(buf->b_data != NULL);
1588 (void) refcount_add(&hdr->b_refcnt, tag);
1589 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1591 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1594 /* Detach an arc_buf from a dbuf (tag) */
1596 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1600 ASSERT(buf->b_data != NULL);
1602 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1603 (void) refcount_remove(&hdr->b_refcnt, tag);
1604 buf->b_efunc = NULL;
1605 buf->b_private = NULL;
1607 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1611 arc_buf_clone(arc_buf_t *from)
1614 arc_buf_hdr_t *hdr = from->b_hdr;
1615 uint64_t size = hdr->b_size;
1617 ASSERT(hdr->b_state != arc_anon);
1619 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1622 buf->b_efunc = NULL;
1623 buf->b_private = NULL;
1624 buf->b_next = hdr->b_buf;
1626 arc_get_data_buf(buf);
1627 bcopy(from->b_data, buf->b_data, size);
1630 * This buffer already exists in the arc so create a duplicate
1631 * copy for the caller. If the buffer is associated with user data
1632 * then track the size and number of duplicates. These stats will be
1633 * updated as duplicate buffers are created and destroyed.
1635 if (hdr->b_type == ARC_BUFC_DATA) {
1636 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1637 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1639 hdr->b_datacnt += 1;
1644 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1647 kmutex_t *hash_lock;
1650 * Check to see if this buffer is evicted. Callers
1651 * must verify b_data != NULL to know if the add_ref
1654 mutex_enter(&buf->b_evict_lock);
1655 if (buf->b_data == NULL) {
1656 mutex_exit(&buf->b_evict_lock);
1659 hash_lock = HDR_LOCK(buf->b_hdr);
1660 mutex_enter(hash_lock);
1662 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1663 mutex_exit(&buf->b_evict_lock);
1665 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1666 add_reference(hdr, hash_lock, tag);
1667 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1668 arc_access(hdr, hash_lock);
1669 mutex_exit(hash_lock);
1670 ARCSTAT_BUMP(arcstat_hits);
1671 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
1672 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1673 data, metadata, hits);
1677 arc_buf_free_on_write(void *data, size_t size,
1678 void (*free_func)(void *, size_t))
1680 l2arc_data_free_t *df;
1682 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1683 df->l2df_data = data;
1684 df->l2df_size = size;
1685 df->l2df_func = free_func;
1686 mutex_enter(&l2arc_free_on_write_mtx);
1687 list_insert_head(l2arc_free_on_write, df);
1688 mutex_exit(&l2arc_free_on_write_mtx);
1692 * Free the arc data buffer. If it is an l2arc write in progress,
1693 * the buffer is placed on l2arc_free_on_write to be freed later.
1696 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1698 arc_buf_hdr_t *hdr = buf->b_hdr;
1700 if (HDR_L2_WRITING(hdr)) {
1701 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
1702 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1704 free_func(buf->b_data, hdr->b_size);
1709 * Free up buf->b_data and if 'remove' is set, then pull the
1710 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1713 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1715 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1717 ASSERT(MUTEX_HELD(&l2arc_buflist_mtx));
1719 if (l2hdr->b_tmp_cdata == NULL)
1722 ASSERT(HDR_L2_WRITING(hdr));
1723 arc_buf_free_on_write(l2hdr->b_tmp_cdata, hdr->b_size,
1725 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1726 l2hdr->b_tmp_cdata = NULL;
1730 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1734 /* free up data associated with the buf */
1736 arc_state_t *state = buf->b_hdr->b_state;
1737 uint64_t size = buf->b_hdr->b_size;
1738 arc_buf_contents_t type = buf->b_hdr->b_type;
1740 arc_cksum_verify(buf);
1742 arc_buf_unwatch(buf);
1743 #endif /* illumos */
1746 if (type == ARC_BUFC_METADATA) {
1747 arc_buf_data_free(buf, zio_buf_free);
1748 arc_space_return(size, ARC_SPACE_DATA);
1750 ASSERT(type == ARC_BUFC_DATA);
1751 arc_buf_data_free(buf, zio_data_buf_free);
1752 ARCSTAT_INCR(arcstat_data_size, -size);
1753 atomic_add_64(&arc_size, -size);
1756 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1757 uint64_t *cnt = &state->arcs_lsize[type];
1759 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1760 ASSERT(state != arc_anon);
1762 ASSERT3U(*cnt, >=, size);
1763 atomic_add_64(cnt, -size);
1765 ASSERT3U(state->arcs_size, >=, size);
1766 atomic_add_64(&state->arcs_size, -size);
1770 * If we're destroying a duplicate buffer make sure
1771 * that the appropriate statistics are updated.
1773 if (buf->b_hdr->b_datacnt > 1 &&
1774 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1775 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1776 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1778 ASSERT(buf->b_hdr->b_datacnt > 0);
1779 buf->b_hdr->b_datacnt -= 1;
1782 /* only remove the buf if requested */
1786 /* remove the buf from the hdr list */
1787 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1789 *bufp = buf->b_next;
1792 ASSERT(buf->b_efunc == NULL);
1794 /* clean up the buf */
1796 kmem_cache_free(buf_cache, buf);
1800 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1802 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1803 ASSERT3P(hdr->b_state, ==, arc_anon);
1804 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1805 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1807 if (l2hdr != NULL) {
1808 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1810 * To prevent arc_free() and l2arc_evict() from
1811 * attempting to free the same buffer at the same time,
1812 * a FREE_IN_PROGRESS flag is given to arc_free() to
1813 * give it priority. l2arc_evict() can't destroy this
1814 * header while we are waiting on l2arc_buflist_mtx.
1816 * The hdr may be removed from l2ad_buflist before we
1817 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1819 if (!buflist_held) {
1820 mutex_enter(&l2arc_buflist_mtx);
1821 l2hdr = hdr->b_l2hdr;
1824 if (l2hdr != NULL) {
1825 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1827 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1828 arc_buf_l2_cdata_free(hdr);
1829 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1830 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1831 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1832 -l2hdr->b_asize, 0, 0);
1833 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1834 if (hdr->b_state == arc_l2c_only)
1835 l2arc_hdr_stat_remove();
1836 hdr->b_l2hdr = NULL;
1840 mutex_exit(&l2arc_buflist_mtx);
1843 if (!BUF_EMPTY(hdr)) {
1844 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1845 buf_discard_identity(hdr);
1847 while (hdr->b_buf) {
1848 arc_buf_t *buf = hdr->b_buf;
1851 mutex_enter(&arc_eviction_mtx);
1852 mutex_enter(&buf->b_evict_lock);
1853 ASSERT(buf->b_hdr != NULL);
1854 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1855 hdr->b_buf = buf->b_next;
1856 buf->b_hdr = &arc_eviction_hdr;
1857 buf->b_next = arc_eviction_list;
1858 arc_eviction_list = buf;
1859 mutex_exit(&buf->b_evict_lock);
1860 mutex_exit(&arc_eviction_mtx);
1862 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1865 if (hdr->b_freeze_cksum != NULL) {
1866 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1867 hdr->b_freeze_cksum = NULL;
1869 if (hdr->b_thawed) {
1870 kmem_free(hdr->b_thawed, 1);
1871 hdr->b_thawed = NULL;
1874 ASSERT(!list_link_active(&hdr->b_arc_node));
1875 ASSERT3P(hdr->b_hash_next, ==, NULL);
1876 ASSERT3P(hdr->b_acb, ==, NULL);
1877 kmem_cache_free(hdr_cache, hdr);
1881 arc_buf_free(arc_buf_t *buf, void *tag)
1883 arc_buf_hdr_t *hdr = buf->b_hdr;
1884 int hashed = hdr->b_state != arc_anon;
1886 ASSERT(buf->b_efunc == NULL);
1887 ASSERT(buf->b_data != NULL);
1890 kmutex_t *hash_lock = HDR_LOCK(hdr);
1892 mutex_enter(hash_lock);
1894 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1896 (void) remove_reference(hdr, hash_lock, tag);
1897 if (hdr->b_datacnt > 1) {
1898 arc_buf_destroy(buf, FALSE, TRUE);
1900 ASSERT(buf == hdr->b_buf);
1901 ASSERT(buf->b_efunc == NULL);
1902 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1904 mutex_exit(hash_lock);
1905 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1908 * We are in the middle of an async write. Don't destroy
1909 * this buffer unless the write completes before we finish
1910 * decrementing the reference count.
1912 mutex_enter(&arc_eviction_mtx);
1913 (void) remove_reference(hdr, NULL, tag);
1914 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1915 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1916 mutex_exit(&arc_eviction_mtx);
1918 arc_hdr_destroy(hdr);
1920 if (remove_reference(hdr, NULL, tag) > 0)
1921 arc_buf_destroy(buf, FALSE, TRUE);
1923 arc_hdr_destroy(hdr);
1928 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1930 arc_buf_hdr_t *hdr = buf->b_hdr;
1931 kmutex_t *hash_lock = HDR_LOCK(hdr);
1932 boolean_t no_callback = (buf->b_efunc == NULL);
1934 if (hdr->b_state == arc_anon) {
1935 ASSERT(hdr->b_datacnt == 1);
1936 arc_buf_free(buf, tag);
1937 return (no_callback);
1940 mutex_enter(hash_lock);
1942 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1943 ASSERT(hdr->b_state != arc_anon);
1944 ASSERT(buf->b_data != NULL);
1946 (void) remove_reference(hdr, hash_lock, tag);
1947 if (hdr->b_datacnt > 1) {
1949 arc_buf_destroy(buf, FALSE, TRUE);
1950 } else if (no_callback) {
1951 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1952 ASSERT(buf->b_efunc == NULL);
1953 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1955 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1956 refcount_is_zero(&hdr->b_refcnt));
1957 mutex_exit(hash_lock);
1958 return (no_callback);
1962 arc_buf_size(arc_buf_t *buf)
1964 return (buf->b_hdr->b_size);
1968 * Called from the DMU to determine if the current buffer should be
1969 * evicted. In order to ensure proper locking, the eviction must be initiated
1970 * from the DMU. Return true if the buffer is associated with user data and
1971 * duplicate buffers still exist.
1974 arc_buf_eviction_needed(arc_buf_t *buf)
1977 boolean_t evict_needed = B_FALSE;
1979 if (zfs_disable_dup_eviction)
1982 mutex_enter(&buf->b_evict_lock);
1986 * We are in arc_do_user_evicts(); let that function
1987 * perform the eviction.
1989 ASSERT(buf->b_data == NULL);
1990 mutex_exit(&buf->b_evict_lock);
1992 } else if (buf->b_data == NULL) {
1994 * We have already been added to the arc eviction list;
1995 * recommend eviction.
1997 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1998 mutex_exit(&buf->b_evict_lock);
2002 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
2003 evict_needed = B_TRUE;
2005 mutex_exit(&buf->b_evict_lock);
2006 return (evict_needed);
2010 * Evict buffers from list until we've removed the specified number of
2011 * bytes. Move the removed buffers to the appropriate evict state.
2012 * If the recycle flag is set, then attempt to "recycle" a buffer:
2013 * - look for a buffer to evict that is `bytes' long.
2014 * - return the data block from this buffer rather than freeing it.
2015 * This flag is used by callers that are trying to make space for a
2016 * new buffer in a full arc cache.
2018 * This function makes a "best effort". It skips over any buffers
2019 * it can't get a hash_lock on, and so may not catch all candidates.
2020 * It may also return without evicting as much space as requested.
2023 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
2024 arc_buf_contents_t type)
2026 arc_state_t *evicted_state;
2027 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
2028 int64_t bytes_remaining;
2029 arc_buf_hdr_t *hdr, *hdr_prev = NULL;
2030 list_t *evicted_list, *list, *evicted_list_start, *list_start;
2031 kmutex_t *lock, *evicted_lock;
2032 kmutex_t *hash_lock;
2033 boolean_t have_lock;
2034 void *stolen = NULL;
2035 arc_buf_hdr_t marker = { 0 };
2037 static int evict_metadata_offset, evict_data_offset;
2038 int i, idx, offset, list_count, lists;
2040 ASSERT(state == arc_mru || state == arc_mfu);
2042 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2044 if (type == ARC_BUFC_METADATA) {
2046 list_count = ARC_BUFC_NUMMETADATALISTS;
2047 list_start = &state->arcs_lists[0];
2048 evicted_list_start = &evicted_state->arcs_lists[0];
2049 idx = evict_metadata_offset;
2051 offset = ARC_BUFC_NUMMETADATALISTS;
2052 list_start = &state->arcs_lists[offset];
2053 evicted_list_start = &evicted_state->arcs_lists[offset];
2054 list_count = ARC_BUFC_NUMDATALISTS;
2055 idx = evict_data_offset;
2057 bytes_remaining = evicted_state->arcs_lsize[type];
2061 list = &list_start[idx];
2062 evicted_list = &evicted_list_start[idx];
2063 lock = ARCS_LOCK(state, (offset + idx));
2064 evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
2067 mutex_enter(evicted_lock);
2069 for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2070 hdr_prev = list_prev(list, hdr);
2071 bytes_remaining -= (hdr->b_size * hdr->b_datacnt);
2072 /* prefetch buffers have a minimum lifespan */
2073 if (HDR_IO_IN_PROGRESS(hdr) ||
2074 (spa && hdr->b_spa != spa) ||
2075 (hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT) &&
2076 ddi_get_lbolt() - hdr->b_arc_access <
2077 arc_min_prefetch_lifespan)) {
2081 /* "lookahead" for better eviction candidate */
2082 if (recycle && hdr->b_size != bytes &&
2083 hdr_prev && hdr_prev->b_size == bytes)
2086 /* ignore markers */
2087 if (hdr->b_spa == 0)
2091 * It may take a long time to evict all the bufs requested.
2092 * To avoid blocking all arc activity, periodically drop
2093 * the arcs_mtx and give other threads a chance to run
2094 * before reacquiring the lock.
2096 * If we are looking for a buffer to recycle, we are in
2097 * the hot code path, so don't sleep.
2099 if (!recycle && count++ > arc_evict_iterations) {
2100 list_insert_after(list, hdr, &marker);
2101 mutex_exit(evicted_lock);
2103 kpreempt(KPREEMPT_SYNC);
2105 mutex_enter(evicted_lock);
2106 hdr_prev = list_prev(list, &marker);
2107 list_remove(list, &marker);
2112 hash_lock = HDR_LOCK(hdr);
2113 have_lock = MUTEX_HELD(hash_lock);
2114 if (have_lock || mutex_tryenter(hash_lock)) {
2115 ASSERT0(refcount_count(&hdr->b_refcnt));
2116 ASSERT(hdr->b_datacnt > 0);
2117 while (hdr->b_buf) {
2118 arc_buf_t *buf = hdr->b_buf;
2119 if (!mutex_tryenter(&buf->b_evict_lock)) {
2124 bytes_evicted += hdr->b_size;
2125 if (recycle && hdr->b_type == type &&
2126 hdr->b_size == bytes &&
2127 !HDR_L2_WRITING(hdr)) {
2128 stolen = buf->b_data;
2133 mutex_enter(&arc_eviction_mtx);
2134 arc_buf_destroy(buf,
2135 buf->b_data == stolen, FALSE);
2136 hdr->b_buf = buf->b_next;
2137 buf->b_hdr = &arc_eviction_hdr;
2138 buf->b_next = arc_eviction_list;
2139 arc_eviction_list = buf;
2140 mutex_exit(&arc_eviction_mtx);
2141 mutex_exit(&buf->b_evict_lock);
2143 mutex_exit(&buf->b_evict_lock);
2144 arc_buf_destroy(buf,
2145 buf->b_data == stolen, TRUE);
2150 ARCSTAT_INCR(arcstat_evict_l2_cached,
2153 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
2154 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2158 arcstat_evict_l2_ineligible,
2163 if (hdr->b_datacnt == 0) {
2164 arc_change_state(evicted_state, hdr, hash_lock);
2165 ASSERT(HDR_IN_HASH_TABLE(hdr));
2166 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2167 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2168 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2171 mutex_exit(hash_lock);
2172 if (bytes >= 0 && bytes_evicted >= bytes)
2174 if (bytes_remaining > 0) {
2175 mutex_exit(evicted_lock);
2177 idx = ((idx + 1) & (list_count - 1));
2186 mutex_exit(evicted_lock);
2189 idx = ((idx + 1) & (list_count - 1));
2192 if (bytes_evicted < bytes) {
2193 if (lists < list_count)
2196 dprintf("only evicted %lld bytes from %x",
2197 (longlong_t)bytes_evicted, state);
2199 if (type == ARC_BUFC_METADATA)
2200 evict_metadata_offset = idx;
2202 evict_data_offset = idx;
2205 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2208 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2211 * Note: we have just evicted some data into the ghost state,
2212 * potentially putting the ghost size over the desired size. Rather
2213 * that evicting from the ghost list in this hot code path, leave
2214 * this chore to the arc_reclaim_thread().
2218 ARCSTAT_BUMP(arcstat_stolen);
2223 * Remove buffers from list until we've removed the specified number of
2224 * bytes. Destroy the buffers that are removed.
2227 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2229 arc_buf_hdr_t *hdr, *hdr_prev;
2230 arc_buf_hdr_t marker = { 0 };
2231 list_t *list, *list_start;
2232 kmutex_t *hash_lock, *lock;
2233 uint64_t bytes_deleted = 0;
2234 uint64_t bufs_skipped = 0;
2236 static int evict_offset;
2237 int list_count, idx = evict_offset;
2238 int offset, lists = 0;
2240 ASSERT(GHOST_STATE(state));
2243 * data lists come after metadata lists
2245 list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2246 list_count = ARC_BUFC_NUMDATALISTS;
2247 offset = ARC_BUFC_NUMMETADATALISTS;
2250 list = &list_start[idx];
2251 lock = ARCS_LOCK(state, idx + offset);
2254 for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2255 hdr_prev = list_prev(list, hdr);
2256 if (hdr->b_type > ARC_BUFC_NUMTYPES)
2257 panic("invalid hdr=%p", (void *)hdr);
2258 if (spa && hdr->b_spa != spa)
2261 /* ignore markers */
2262 if (hdr->b_spa == 0)
2265 hash_lock = HDR_LOCK(hdr);
2266 /* caller may be trying to modify this buffer, skip it */
2267 if (MUTEX_HELD(hash_lock))
2271 * It may take a long time to evict all the bufs requested.
2272 * To avoid blocking all arc activity, periodically drop
2273 * the arcs_mtx and give other threads a chance to run
2274 * before reacquiring the lock.
2276 if (count++ > arc_evict_iterations) {
2277 list_insert_after(list, hdr, &marker);
2279 kpreempt(KPREEMPT_SYNC);
2281 hdr_prev = list_prev(list, &marker);
2282 list_remove(list, &marker);
2286 if (mutex_tryenter(hash_lock)) {
2287 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2288 ASSERT(hdr->b_buf == NULL);
2289 ARCSTAT_BUMP(arcstat_deleted);
2290 bytes_deleted += hdr->b_size;
2292 if (hdr->b_l2hdr != NULL) {
2294 * This buffer is cached on the 2nd Level ARC;
2295 * don't destroy the header.
2297 arc_change_state(arc_l2c_only, hdr, hash_lock);
2298 mutex_exit(hash_lock);
2300 arc_change_state(arc_anon, hdr, hash_lock);
2301 mutex_exit(hash_lock);
2302 arc_hdr_destroy(hdr);
2305 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2306 if (bytes >= 0 && bytes_deleted >= bytes)
2308 } else if (bytes < 0) {
2310 * Insert a list marker and then wait for the
2311 * hash lock to become available. Once its
2312 * available, restart from where we left off.
2314 list_insert_after(list, hdr, &marker);
2316 mutex_enter(hash_lock);
2317 mutex_exit(hash_lock);
2319 hdr_prev = list_prev(list, &marker);
2320 list_remove(list, &marker);
2327 idx = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2330 if (lists < list_count)
2334 if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2335 (bytes < 0 || bytes_deleted < bytes)) {
2336 list_start = &state->arcs_lists[0];
2337 list_count = ARC_BUFC_NUMMETADATALISTS;
2343 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2347 if (bytes_deleted < bytes)
2348 dprintf("only deleted %lld bytes from %p",
2349 (longlong_t)bytes_deleted, state);
2355 int64_t adjustment, delta;
2361 adjustment = MIN((int64_t)(arc_size - arc_c),
2362 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2365 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2366 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2367 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2368 adjustment -= delta;
2371 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2372 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2373 (void) arc_evict(arc_mru, 0, delta, FALSE,
2381 adjustment = arc_size - arc_c;
2383 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2384 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2385 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2386 adjustment -= delta;
2389 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2390 int64_t delta = MIN(adjustment,
2391 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2392 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2397 * Adjust ghost lists
2400 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2402 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2403 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2404 arc_evict_ghost(arc_mru_ghost, 0, delta);
2408 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2410 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2411 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2412 arc_evict_ghost(arc_mfu_ghost, 0, delta);
2417 arc_do_user_evicts(void)
2419 static arc_buf_t *tmp_arc_eviction_list;
2422 * Move list over to avoid LOR
2425 mutex_enter(&arc_eviction_mtx);
2426 tmp_arc_eviction_list = arc_eviction_list;
2427 arc_eviction_list = NULL;
2428 mutex_exit(&arc_eviction_mtx);
2430 while (tmp_arc_eviction_list != NULL) {
2431 arc_buf_t *buf = tmp_arc_eviction_list;
2432 tmp_arc_eviction_list = buf->b_next;
2433 mutex_enter(&buf->b_evict_lock);
2435 mutex_exit(&buf->b_evict_lock);
2437 if (buf->b_efunc != NULL)
2438 VERIFY0(buf->b_efunc(buf->b_private));
2440 buf->b_efunc = NULL;
2441 buf->b_private = NULL;
2442 kmem_cache_free(buf_cache, buf);
2445 if (arc_eviction_list != NULL)
2450 * Flush all *evictable* data from the cache for the given spa.
2451 * NOTE: this will not touch "active" (i.e. referenced) data.
2454 arc_flush(spa_t *spa)
2459 guid = spa_load_guid(spa);
2461 while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2462 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2466 while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2467 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2471 while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2472 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2476 while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2477 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2482 arc_evict_ghost(arc_mru_ghost, guid, -1);
2483 arc_evict_ghost(arc_mfu_ghost, guid, -1);
2485 mutex_enter(&arc_reclaim_thr_lock);
2486 arc_do_user_evicts();
2487 mutex_exit(&arc_reclaim_thr_lock);
2488 ASSERT(spa || arc_eviction_list == NULL);
2495 if (arc_c > arc_c_min) {
2498 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
2499 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
2501 to_free = arc_c >> arc_shrink_shift;
2503 to_free = arc_c >> arc_shrink_shift;
2505 if (arc_c > arc_c_min + to_free)
2506 atomic_add_64(&arc_c, -to_free);
2510 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2511 if (arc_c > arc_size)
2512 arc_c = MAX(arc_size, arc_c_min);
2514 arc_p = (arc_c >> 1);
2516 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
2519 ASSERT(arc_c >= arc_c_min);
2520 ASSERT((int64_t)arc_p >= 0);
2523 if (arc_size > arc_c) {
2524 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
2530 static int needfree = 0;
2533 arc_reclaim_needed(void)
2539 DTRACE_PROBE(arc__reclaim_needfree);
2544 * Cooperate with pagedaemon when it's time for it to scan
2545 * and reclaim some pages.
2547 if (freemem < zfs_arc_free_target) {
2548 DTRACE_PROBE2(arc__reclaim_freemem, uint64_t,
2549 freemem, uint64_t, zfs_arc_free_target);
2555 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2560 * check that we're out of range of the pageout scanner. It starts to
2561 * schedule paging if freemem is less than lotsfree and needfree.
2562 * lotsfree is the high-water mark for pageout, and needfree is the
2563 * number of needed free pages. We add extra pages here to make sure
2564 * the scanner doesn't start up while we're freeing memory.
2566 if (freemem < lotsfree + needfree + extra)
2570 * check to make sure that swapfs has enough space so that anon
2571 * reservations can still succeed. anon_resvmem() checks that the
2572 * availrmem is greater than swapfs_minfree, and the number of reserved
2573 * swap pages. We also add a bit of extra here just to prevent
2574 * circumstances from getting really dire.
2576 if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2580 * Check that we have enough availrmem that memory locking (e.g., via
2581 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
2582 * stores the number of pages that cannot be locked; when availrmem
2583 * drops below pages_pp_maximum, page locking mechanisms such as
2584 * page_pp_lock() will fail.)
2586 if (availrmem <= pages_pp_maximum)
2590 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
2592 * If we're on an i386 platform, it's possible that we'll exhaust the
2593 * kernel heap space before we ever run out of available physical
2594 * memory. Most checks of the size of the heap_area compare against
2595 * tune.t_minarmem, which is the minimum available real memory that we
2596 * can have in the system. However, this is generally fixed at 25 pages
2597 * which is so low that it's useless. In this comparison, we seek to
2598 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2599 * heap is allocated. (Or, in the calculation, if less than 1/4th is
2602 if (vmem_size(heap_arena, VMEM_FREE) <
2603 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2)) {
2604 DTRACE_PROBE2(arc__reclaim_used, uint64_t,
2605 vmem_size(heap_arena, VMEM_FREE), uint64_t,
2606 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2);
2612 * If zio data pages are being allocated out of a separate heap segment,
2613 * then enforce that the size of available vmem for this arena remains
2614 * above about 1/16th free.
2616 * Note: The 1/16th arena free requirement was put in place
2617 * to aggressively evict memory from the arc in order to avoid
2618 * memory fragmentation issues.
2620 if (zio_arena != NULL &&
2621 vmem_size(zio_arena, VMEM_FREE) <
2622 (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2626 if (spa_get_random(100) == 0)
2628 #endif /* _KERNEL */
2629 DTRACE_PROBE(arc__reclaim_no);
2634 extern kmem_cache_t *zio_buf_cache[];
2635 extern kmem_cache_t *zio_data_buf_cache[];
2636 extern kmem_cache_t *range_seg_cache;
2638 static void __noinline
2639 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2642 kmem_cache_t *prev_cache = NULL;
2643 kmem_cache_t *prev_data_cache = NULL;
2645 DTRACE_PROBE(arc__kmem_reap_start);
2647 if (arc_meta_used >= arc_meta_limit) {
2649 * We are exceeding our meta-data cache limit.
2650 * Purge some DNLC entries to release holds on meta-data.
2652 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2656 * Reclaim unused memory from all kmem caches.
2663 * An aggressive reclamation will shrink the cache size as well as
2664 * reap free buffers from the arc kmem caches.
2666 if (strat == ARC_RECLAIM_AGGR)
2669 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2670 if (zio_buf_cache[i] != prev_cache) {
2671 prev_cache = zio_buf_cache[i];
2672 kmem_cache_reap_now(zio_buf_cache[i]);
2674 if (zio_data_buf_cache[i] != prev_data_cache) {
2675 prev_data_cache = zio_data_buf_cache[i];
2676 kmem_cache_reap_now(zio_data_buf_cache[i]);
2679 kmem_cache_reap_now(buf_cache);
2680 kmem_cache_reap_now(hdr_cache);
2681 kmem_cache_reap_now(range_seg_cache);
2685 * Ask the vmem arena to reclaim unused memory from its
2688 if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2689 vmem_qcache_reap(zio_arena);
2691 DTRACE_PROBE(arc__kmem_reap_end);
2695 arc_reclaim_thread(void *dummy __unused)
2697 clock_t growtime = 0;
2698 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2701 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2703 mutex_enter(&arc_reclaim_thr_lock);
2704 while (arc_thread_exit == 0) {
2705 if (arc_reclaim_needed()) {
2708 if (last_reclaim == ARC_RECLAIM_CONS) {
2709 DTRACE_PROBE(arc__reclaim_aggr_no_grow);
2710 last_reclaim = ARC_RECLAIM_AGGR;
2712 last_reclaim = ARC_RECLAIM_CONS;
2716 last_reclaim = ARC_RECLAIM_AGGR;
2717 DTRACE_PROBE(arc__reclaim_aggr);
2721 /* reset the growth delay for every reclaim */
2722 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2724 if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2726 * If needfree is TRUE our vm_lowmem hook
2727 * was called and in that case we must free some
2728 * memory, so switch to aggressive mode.
2731 last_reclaim = ARC_RECLAIM_AGGR;
2733 arc_kmem_reap_now(last_reclaim);
2736 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2737 arc_no_grow = FALSE;
2742 if (arc_eviction_list != NULL)
2743 arc_do_user_evicts();
2752 /* block until needed, or one second, whichever is shorter */
2753 CALLB_CPR_SAFE_BEGIN(&cpr);
2754 (void) cv_timedwait(&arc_reclaim_thr_cv,
2755 &arc_reclaim_thr_lock, hz);
2756 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2759 arc_thread_exit = 0;
2760 cv_broadcast(&arc_reclaim_thr_cv);
2761 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2766 * Adapt arc info given the number of bytes we are trying to add and
2767 * the state that we are comming from. This function is only called
2768 * when we are adding new content to the cache.
2771 arc_adapt(int bytes, arc_state_t *state)
2774 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2776 if (state == arc_l2c_only)
2781 * Adapt the target size of the MRU list:
2782 * - if we just hit in the MRU ghost list, then increase
2783 * the target size of the MRU list.
2784 * - if we just hit in the MFU ghost list, then increase
2785 * the target size of the MFU list by decreasing the
2786 * target size of the MRU list.
2788 if (state == arc_mru_ghost) {
2789 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2790 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2791 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2793 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2794 } else if (state == arc_mfu_ghost) {
2797 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2798 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2799 mult = MIN(mult, 10);
2801 delta = MIN(bytes * mult, arc_p);
2802 arc_p = MAX(arc_p_min, arc_p - delta);
2804 ASSERT((int64_t)arc_p >= 0);
2806 if (arc_reclaim_needed()) {
2807 cv_signal(&arc_reclaim_thr_cv);
2814 if (arc_c >= arc_c_max)
2818 * If we're within (2 * maxblocksize) bytes of the target
2819 * cache size, increment the target cache size
2821 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2822 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
2823 atomic_add_64(&arc_c, (int64_t)bytes);
2824 if (arc_c > arc_c_max)
2826 else if (state == arc_anon)
2827 atomic_add_64(&arc_p, (int64_t)bytes);
2831 ASSERT((int64_t)arc_p >= 0);
2835 * Check if the cache has reached its limits and eviction is required
2839 arc_evict_needed(arc_buf_contents_t type)
2841 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2844 if (arc_reclaim_needed())
2847 return (arc_size > arc_c);
2851 * The buffer, supplied as the first argument, needs a data block.
2852 * So, if we are at cache max, determine which cache should be victimized.
2853 * We have the following cases:
2855 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2856 * In this situation if we're out of space, but the resident size of the MFU is
2857 * under the limit, victimize the MFU cache to satisfy this insertion request.
2859 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2860 * Here, we've used up all of the available space for the MRU, so we need to
2861 * evict from our own cache instead. Evict from the set of resident MRU
2864 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2865 * c minus p represents the MFU space in the cache, since p is the size of the
2866 * cache that is dedicated to the MRU. In this situation there's still space on
2867 * the MFU side, so the MRU side needs to be victimized.
2869 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2870 * MFU's resident set is consuming more space than it has been allotted. In
2871 * this situation, we must victimize our own cache, the MFU, for this insertion.
2874 arc_get_data_buf(arc_buf_t *buf)
2876 arc_state_t *state = buf->b_hdr->b_state;
2877 uint64_t size = buf->b_hdr->b_size;
2878 arc_buf_contents_t type = buf->b_hdr->b_type;
2880 arc_adapt(size, state);
2883 * We have not yet reached cache maximum size,
2884 * just allocate a new buffer.
2886 if (!arc_evict_needed(type)) {
2887 if (type == ARC_BUFC_METADATA) {
2888 buf->b_data = zio_buf_alloc(size);
2889 arc_space_consume(size, ARC_SPACE_DATA);
2891 ASSERT(type == ARC_BUFC_DATA);
2892 buf->b_data = zio_data_buf_alloc(size);
2893 ARCSTAT_INCR(arcstat_data_size, size);
2894 atomic_add_64(&arc_size, size);
2900 * If we are prefetching from the mfu ghost list, this buffer
2901 * will end up on the mru list; so steal space from there.
2903 if (state == arc_mfu_ghost)
2904 state = buf->b_hdr->b_flags & ARC_FLAG_PREFETCH ?
2906 else if (state == arc_mru_ghost)
2909 if (state == arc_mru || state == arc_anon) {
2910 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2911 state = (arc_mfu->arcs_lsize[type] >= size &&
2912 arc_p > mru_used) ? arc_mfu : arc_mru;
2915 uint64_t mfu_space = arc_c - arc_p;
2916 state = (arc_mru->arcs_lsize[type] >= size &&
2917 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2919 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2920 if (type == ARC_BUFC_METADATA) {
2921 buf->b_data = zio_buf_alloc(size);
2922 arc_space_consume(size, ARC_SPACE_DATA);
2924 ASSERT(type == ARC_BUFC_DATA);
2925 buf->b_data = zio_data_buf_alloc(size);
2926 ARCSTAT_INCR(arcstat_data_size, size);
2927 atomic_add_64(&arc_size, size);
2929 ARCSTAT_BUMP(arcstat_recycle_miss);
2931 ASSERT(buf->b_data != NULL);
2934 * Update the state size. Note that ghost states have a
2935 * "ghost size" and so don't need to be updated.
2937 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2938 arc_buf_hdr_t *hdr = buf->b_hdr;
2940 atomic_add_64(&hdr->b_state->arcs_size, size);
2941 if (list_link_active(&hdr->b_arc_node)) {
2942 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2943 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2946 * If we are growing the cache, and we are adding anonymous
2947 * data, and we have outgrown arc_p, update arc_p
2949 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2950 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2951 arc_p = MIN(arc_c, arc_p + size);
2953 ARCSTAT_BUMP(arcstat_allocated);
2957 * This routine is called whenever a buffer is accessed.
2958 * NOTE: the hash lock is dropped in this function.
2961 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
2965 ASSERT(MUTEX_HELD(hash_lock));
2967 if (hdr->b_state == arc_anon) {
2969 * This buffer is not in the cache, and does not
2970 * appear in our "ghost" list. Add the new buffer
2974 ASSERT(hdr->b_arc_access == 0);
2975 hdr->b_arc_access = ddi_get_lbolt();
2976 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
2977 arc_change_state(arc_mru, hdr, hash_lock);
2979 } else if (hdr->b_state == arc_mru) {
2980 now = ddi_get_lbolt();
2983 * If this buffer is here because of a prefetch, then either:
2984 * - clear the flag if this is a "referencing" read
2985 * (any subsequent access will bump this into the MFU state).
2987 * - move the buffer to the head of the list if this is
2988 * another prefetch (to make it less likely to be evicted).
2990 if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
2991 if (refcount_count(&hdr->b_refcnt) == 0) {
2992 ASSERT(list_link_active(&hdr->b_arc_node));
2994 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
2995 ARCSTAT_BUMP(arcstat_mru_hits);
2997 hdr->b_arc_access = now;
3002 * This buffer has been "accessed" only once so far,
3003 * but it is still in the cache. Move it to the MFU
3006 if (now > hdr->b_arc_access + ARC_MINTIME) {
3008 * More than 125ms have passed since we
3009 * instantiated this buffer. Move it to the
3010 * most frequently used state.
3012 hdr->b_arc_access = now;
3013 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3014 arc_change_state(arc_mfu, hdr, hash_lock);
3016 ARCSTAT_BUMP(arcstat_mru_hits);
3017 } else if (hdr->b_state == arc_mru_ghost) {
3018 arc_state_t *new_state;
3020 * This buffer has been "accessed" recently, but
3021 * was evicted from the cache. Move it to the
3025 if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3026 new_state = arc_mru;
3027 if (refcount_count(&hdr->b_refcnt) > 0)
3028 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3029 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3031 new_state = arc_mfu;
3032 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3035 hdr->b_arc_access = ddi_get_lbolt();
3036 arc_change_state(new_state, hdr, hash_lock);
3038 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3039 } else if (hdr->b_state == arc_mfu) {
3041 * This buffer has been accessed more than once and is
3042 * still in the cache. Keep it in the MFU state.
3044 * NOTE: an add_reference() that occurred when we did
3045 * the arc_read() will have kicked this off the list.
3046 * If it was a prefetch, we will explicitly move it to
3047 * the head of the list now.
3049 if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3050 ASSERT(refcount_count(&hdr->b_refcnt) == 0);
3051 ASSERT(list_link_active(&hdr->b_arc_node));
3053 ARCSTAT_BUMP(arcstat_mfu_hits);
3054 hdr->b_arc_access = ddi_get_lbolt();
3055 } else if (hdr->b_state == arc_mfu_ghost) {
3056 arc_state_t *new_state = arc_mfu;
3058 * This buffer has been accessed more than once but has
3059 * been evicted from the cache. Move it back to the
3063 if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3065 * This is a prefetch access...
3066 * move this block back to the MRU state.
3068 ASSERT0(refcount_count(&hdr->b_refcnt));
3069 new_state = arc_mru;
3072 hdr->b_arc_access = ddi_get_lbolt();
3073 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3074 arc_change_state(new_state, hdr, hash_lock);
3076 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3077 } else if (hdr->b_state == arc_l2c_only) {
3079 * This buffer is on the 2nd Level ARC.
3082 hdr->b_arc_access = ddi_get_lbolt();
3083 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3084 arc_change_state(arc_mfu, hdr, hash_lock);
3086 ASSERT(!"invalid arc state");
3090 /* a generic arc_done_func_t which you can use */
3093 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3095 if (zio == NULL || zio->io_error == 0)
3096 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3097 VERIFY(arc_buf_remove_ref(buf, arg));
3100 /* a generic arc_done_func_t */
3102 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3104 arc_buf_t **bufp = arg;
3105 if (zio && zio->io_error) {
3106 VERIFY(arc_buf_remove_ref(buf, arg));
3110 ASSERT(buf->b_data);
3115 arc_read_done(zio_t *zio)
3119 arc_buf_t *abuf; /* buffer we're assigning to callback */
3120 kmutex_t *hash_lock = NULL;
3121 arc_callback_t *callback_list, *acb;
3122 int freeable = FALSE;
3124 buf = zio->io_private;
3128 * The hdr was inserted into hash-table and removed from lists
3129 * prior to starting I/O. We should find this header, since
3130 * it's in the hash table, and it should be legit since it's
3131 * not possible to evict it during the I/O. The only possible
3132 * reason for it not to be found is if we were freed during the
3135 if (HDR_IN_HASH_TABLE(hdr)) {
3136 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3137 ASSERT3U(hdr->b_dva.dva_word[0], ==,
3138 BP_IDENTITY(zio->io_bp)->dva_word[0]);
3139 ASSERT3U(hdr->b_dva.dva_word[1], ==,
3140 BP_IDENTITY(zio->io_bp)->dva_word[1]);
3142 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3145 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3146 hash_lock == NULL) ||
3148 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3149 (found == hdr && HDR_L2_READING(hdr)));
3152 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
3153 if (l2arc_noprefetch && (hdr->b_flags & ARC_FLAG_PREFETCH))
3154 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
3156 /* byteswap if necessary */
3157 callback_list = hdr->b_acb;
3158 ASSERT(callback_list != NULL);
3159 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3160 dmu_object_byteswap_t bswap =
3161 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3162 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3163 byteswap_uint64_array :
3164 dmu_ot_byteswap[bswap].ob_func;
3165 func(buf->b_data, hdr->b_size);
3168 arc_cksum_compute(buf, B_FALSE);
3171 #endif /* illumos */
3173 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3175 * Only call arc_access on anonymous buffers. This is because
3176 * if we've issued an I/O for an evicted buffer, we've already
3177 * called arc_access (to prevent any simultaneous readers from
3178 * getting confused).
3180 arc_access(hdr, hash_lock);
3183 /* create copies of the data buffer for the callers */
3185 for (acb = callback_list; acb; acb = acb->acb_next) {
3186 if (acb->acb_done) {
3188 ARCSTAT_BUMP(arcstat_duplicate_reads);
3189 abuf = arc_buf_clone(buf);
3191 acb->acb_buf = abuf;
3196 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3197 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3199 ASSERT(buf->b_efunc == NULL);
3200 ASSERT(hdr->b_datacnt == 1);
3201 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3204 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3206 if (zio->io_error != 0) {
3207 hdr->b_flags |= ARC_FLAG_IO_ERROR;
3208 if (hdr->b_state != arc_anon)
3209 arc_change_state(arc_anon, hdr, hash_lock);
3210 if (HDR_IN_HASH_TABLE(hdr))
3211 buf_hash_remove(hdr);
3212 freeable = refcount_is_zero(&hdr->b_refcnt);
3216 * Broadcast before we drop the hash_lock to avoid the possibility
3217 * that the hdr (and hence the cv) might be freed before we get to
3218 * the cv_broadcast().
3220 cv_broadcast(&hdr->b_cv);
3223 mutex_exit(hash_lock);
3226 * This block was freed while we waited for the read to
3227 * complete. It has been removed from the hash table and
3228 * moved to the anonymous state (so that it won't show up
3231 ASSERT3P(hdr->b_state, ==, arc_anon);
3232 freeable = refcount_is_zero(&hdr->b_refcnt);
3235 /* execute each callback and free its structure */
3236 while ((acb = callback_list) != NULL) {
3238 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3240 if (acb->acb_zio_dummy != NULL) {
3241 acb->acb_zio_dummy->io_error = zio->io_error;
3242 zio_nowait(acb->acb_zio_dummy);
3245 callback_list = acb->acb_next;
3246 kmem_free(acb, sizeof (arc_callback_t));
3250 arc_hdr_destroy(hdr);
3254 * "Read" the block block at the specified DVA (in bp) via the
3255 * cache. If the block is found in the cache, invoke the provided
3256 * callback immediately and return. Note that the `zio' parameter
3257 * in the callback will be NULL in this case, since no IO was
3258 * required. If the block is not in the cache pass the read request
3259 * on to the spa with a substitute callback function, so that the
3260 * requested block will be added to the cache.
3262 * If a read request arrives for a block that has a read in-progress,
3263 * either wait for the in-progress read to complete (and return the
3264 * results); or, if this is a read with a "done" func, add a record
3265 * to the read to invoke the "done" func when the read completes,
3266 * and return; or just return.
3268 * arc_read_done() will invoke all the requested "done" functions
3269 * for readers of this block.
3272 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3273 void *private, zio_priority_t priority, int zio_flags,
3274 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
3276 arc_buf_hdr_t *hdr = NULL;
3277 arc_buf_t *buf = NULL;
3278 kmutex_t *hash_lock = NULL;
3280 uint64_t guid = spa_load_guid(spa);
3282 ASSERT(!BP_IS_EMBEDDED(bp) ||
3283 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3286 if (!BP_IS_EMBEDDED(bp)) {
3288 * Embedded BP's have no DVA and require no I/O to "read".
3289 * Create an anonymous arc buf to back it.
3291 hdr = buf_hash_find(guid, bp, &hash_lock);
3294 if (hdr != NULL && hdr->b_datacnt > 0) {
3296 *arc_flags |= ARC_FLAG_CACHED;
3298 if (HDR_IO_IN_PROGRESS(hdr)) {
3300 if (*arc_flags & ARC_FLAG_WAIT) {
3301 cv_wait(&hdr->b_cv, hash_lock);
3302 mutex_exit(hash_lock);
3305 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3308 arc_callback_t *acb = NULL;
3310 acb = kmem_zalloc(sizeof (arc_callback_t),
3312 acb->acb_done = done;
3313 acb->acb_private = private;
3315 acb->acb_zio_dummy = zio_null(pio,
3316 spa, NULL, NULL, NULL, zio_flags);
3318 ASSERT(acb->acb_done != NULL);
3319 acb->acb_next = hdr->b_acb;
3321 add_reference(hdr, hash_lock, private);
3322 mutex_exit(hash_lock);
3325 mutex_exit(hash_lock);
3329 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3332 add_reference(hdr, hash_lock, private);
3334 * If this block is already in use, create a new
3335 * copy of the data so that we will be guaranteed
3336 * that arc_release() will always succeed.
3340 ASSERT(buf->b_data);
3341 if (HDR_BUF_AVAILABLE(hdr)) {
3342 ASSERT(buf->b_efunc == NULL);
3343 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3345 buf = arc_buf_clone(buf);
3348 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
3349 refcount_count(&hdr->b_refcnt) == 0) {
3350 hdr->b_flags |= ARC_FLAG_PREFETCH;
3352 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3353 arc_access(hdr, hash_lock);
3354 if (*arc_flags & ARC_FLAG_L2CACHE)
3355 hdr->b_flags |= ARC_FLAG_L2CACHE;
3356 if (*arc_flags & ARC_FLAG_L2COMPRESS)
3357 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3358 mutex_exit(hash_lock);
3359 ARCSTAT_BUMP(arcstat_hits);
3360 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3361 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3362 data, metadata, hits);
3365 done(NULL, buf, private);
3367 uint64_t size = BP_GET_LSIZE(bp);
3368 arc_callback_t *acb;
3371 boolean_t devw = B_FALSE;
3372 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3373 uint64_t b_asize = 0;
3376 /* this block is not in the cache */
3377 arc_buf_hdr_t *exists = NULL;
3378 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3379 buf = arc_buf_alloc(spa, size, private, type);
3381 if (!BP_IS_EMBEDDED(bp)) {
3382 hdr->b_dva = *BP_IDENTITY(bp);
3383 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3384 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3385 exists = buf_hash_insert(hdr, &hash_lock);
3387 if (exists != NULL) {
3388 /* somebody beat us to the hash insert */
3389 mutex_exit(hash_lock);
3390 buf_discard_identity(hdr);
3391 (void) arc_buf_remove_ref(buf, private);
3392 goto top; /* restart the IO request */
3395 /* if this is a prefetch, we don't have a reference */
3396 if (*arc_flags & ARC_FLAG_PREFETCH) {
3397 (void) remove_reference(hdr, hash_lock,
3399 hdr->b_flags |= ARC_FLAG_PREFETCH;
3401 if (*arc_flags & ARC_FLAG_L2CACHE)
3402 hdr->b_flags |= ARC_FLAG_L2CACHE;
3403 if (*arc_flags & ARC_FLAG_L2COMPRESS)
3404 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3405 if (BP_GET_LEVEL(bp) > 0)
3406 hdr->b_flags |= ARC_FLAG_INDIRECT;
3408 /* this block is in the ghost cache */
3409 ASSERT(GHOST_STATE(hdr->b_state));
3410 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3411 ASSERT0(refcount_count(&hdr->b_refcnt));
3412 ASSERT(hdr->b_buf == NULL);
3414 /* if this is a prefetch, we don't have a reference */
3415 if (*arc_flags & ARC_FLAG_PREFETCH)
3416 hdr->b_flags |= ARC_FLAG_PREFETCH;
3418 add_reference(hdr, hash_lock, private);
3419 if (*arc_flags & ARC_FLAG_L2CACHE)
3420 hdr->b_flags |= ARC_FLAG_L2CACHE;
3421 if (*arc_flags & ARC_FLAG_L2COMPRESS)
3422 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3423 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3426 buf->b_efunc = NULL;
3427 buf->b_private = NULL;
3430 ASSERT(hdr->b_datacnt == 0);
3432 arc_get_data_buf(buf);
3433 arc_access(hdr, hash_lock);
3436 ASSERT(!GHOST_STATE(hdr->b_state));
3438 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3439 acb->acb_done = done;
3440 acb->acb_private = private;
3442 ASSERT(hdr->b_acb == NULL);
3444 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3446 if (hdr->b_l2hdr != NULL &&
3447 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3448 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3449 addr = hdr->b_l2hdr->b_daddr;
3450 b_compress = hdr->b_l2hdr->b_compress;
3451 b_asize = hdr->b_l2hdr->b_asize;
3453 * Lock out device removal.
3455 if (vdev_is_dead(vd) ||
3456 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3460 if (hash_lock != NULL)
3461 mutex_exit(hash_lock);
3464 * At this point, we have a level 1 cache miss. Try again in
3465 * L2ARC if possible.
3467 ASSERT3U(hdr->b_size, ==, size);
3468 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3469 uint64_t, size, zbookmark_phys_t *, zb);
3470 ARCSTAT_BUMP(arcstat_misses);
3471 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3472 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3473 data, metadata, misses);
3475 curthread->td_ru.ru_inblock++;
3478 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3480 * Read from the L2ARC if the following are true:
3481 * 1. The L2ARC vdev was previously cached.
3482 * 2. This buffer still has L2ARC metadata.
3483 * 3. This buffer isn't currently writing to the L2ARC.
3484 * 4. The L2ARC entry wasn't evicted, which may
3485 * also have invalidated the vdev.
3486 * 5. This isn't prefetch and l2arc_noprefetch is set.
3488 if (hdr->b_l2hdr != NULL &&
3489 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3490 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3491 l2arc_read_callback_t *cb;
3493 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3494 ARCSTAT_BUMP(arcstat_l2_hits);
3496 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3498 cb->l2rcb_buf = buf;
3499 cb->l2rcb_spa = spa;
3502 cb->l2rcb_flags = zio_flags;
3503 cb->l2rcb_compress = b_compress;
3505 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3506 addr + size < vd->vdev_psize -
3507 VDEV_LABEL_END_SIZE);
3510 * l2arc read. The SCL_L2ARC lock will be
3511 * released by l2arc_read_done().
3512 * Issue a null zio if the underlying buffer
3513 * was squashed to zero size by compression.
3515 if (b_compress == ZIO_COMPRESS_EMPTY) {
3516 rzio = zio_null(pio, spa, vd,
3517 l2arc_read_done, cb,
3518 zio_flags | ZIO_FLAG_DONT_CACHE |
3520 ZIO_FLAG_DONT_PROPAGATE |
3521 ZIO_FLAG_DONT_RETRY);
3523 rzio = zio_read_phys(pio, vd, addr,
3524 b_asize, buf->b_data,
3526 l2arc_read_done, cb, priority,
3527 zio_flags | ZIO_FLAG_DONT_CACHE |
3529 ZIO_FLAG_DONT_PROPAGATE |
3530 ZIO_FLAG_DONT_RETRY, B_FALSE);
3532 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3534 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3536 if (*arc_flags & ARC_FLAG_NOWAIT) {
3541 ASSERT(*arc_flags & ARC_FLAG_WAIT);
3542 if (zio_wait(rzio) == 0)
3545 /* l2arc read error; goto zio_read() */
3547 DTRACE_PROBE1(l2arc__miss,
3548 arc_buf_hdr_t *, hdr);
3549 ARCSTAT_BUMP(arcstat_l2_misses);
3550 if (HDR_L2_WRITING(hdr))
3551 ARCSTAT_BUMP(arcstat_l2_rw_clash);
3552 spa_config_exit(spa, SCL_L2ARC, vd);
3556 spa_config_exit(spa, SCL_L2ARC, vd);
3557 if (l2arc_ndev != 0) {
3558 DTRACE_PROBE1(l2arc__miss,
3559 arc_buf_hdr_t *, hdr);
3560 ARCSTAT_BUMP(arcstat_l2_misses);
3564 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3565 arc_read_done, buf, priority, zio_flags, zb);
3567 if (*arc_flags & ARC_FLAG_WAIT)
3568 return (zio_wait(rzio));
3570 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3577 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3579 ASSERT(buf->b_hdr != NULL);
3580 ASSERT(buf->b_hdr->b_state != arc_anon);
3581 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3582 ASSERT(buf->b_efunc == NULL);
3583 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3585 buf->b_efunc = func;
3586 buf->b_private = private;
3590 * Notify the arc that a block was freed, and thus will never be used again.
3593 arc_freed(spa_t *spa, const blkptr_t *bp)
3596 kmutex_t *hash_lock;
3597 uint64_t guid = spa_load_guid(spa);
3599 ASSERT(!BP_IS_EMBEDDED(bp));
3601 hdr = buf_hash_find(guid, bp, &hash_lock);
3604 if (HDR_BUF_AVAILABLE(hdr)) {
3605 arc_buf_t *buf = hdr->b_buf;
3606 add_reference(hdr, hash_lock, FTAG);
3607 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3608 mutex_exit(hash_lock);
3610 arc_release(buf, FTAG);
3611 (void) arc_buf_remove_ref(buf, FTAG);
3613 mutex_exit(hash_lock);
3619 * Clear the user eviction callback set by arc_set_callback(), first calling
3620 * it if it exists. Because the presence of a callback keeps an arc_buf cached
3621 * clearing the callback may result in the arc_buf being destroyed. However,
3622 * it will not result in the *last* arc_buf being destroyed, hence the data
3623 * will remain cached in the ARC. We make a copy of the arc buffer here so
3624 * that we can process the callback without holding any locks.
3626 * It's possible that the callback is already in the process of being cleared
3627 * by another thread. In this case we can not clear the callback.
3629 * Returns B_TRUE if the callback was successfully called and cleared.
3632 arc_clear_callback(arc_buf_t *buf)
3635 kmutex_t *hash_lock;
3636 arc_evict_func_t *efunc = buf->b_efunc;
3637 void *private = buf->b_private;
3638 list_t *list, *evicted_list;
3639 kmutex_t *lock, *evicted_lock;
3641 mutex_enter(&buf->b_evict_lock);
3645 * We are in arc_do_user_evicts().
3647 ASSERT(buf->b_data == NULL);
3648 mutex_exit(&buf->b_evict_lock);
3650 } else if (buf->b_data == NULL) {
3652 * We are on the eviction list; process this buffer now
3653 * but let arc_do_user_evicts() do the reaping.
3655 buf->b_efunc = NULL;
3656 mutex_exit(&buf->b_evict_lock);
3657 VERIFY0(efunc(private));
3660 hash_lock = HDR_LOCK(hdr);
3661 mutex_enter(hash_lock);
3663 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3665 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3666 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3668 buf->b_efunc = NULL;
3669 buf->b_private = NULL;
3671 if (hdr->b_datacnt > 1) {
3672 mutex_exit(&buf->b_evict_lock);
3673 arc_buf_destroy(buf, FALSE, TRUE);
3675 ASSERT(buf == hdr->b_buf);
3676 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3677 mutex_exit(&buf->b_evict_lock);
3680 mutex_exit(hash_lock);
3681 VERIFY0(efunc(private));
3686 * Release this buffer from the cache, making it an anonymous buffer. This
3687 * must be done after a read and prior to modifying the buffer contents.
3688 * If the buffer has more than one reference, we must make
3689 * a new hdr for the buffer.
3692 arc_release(arc_buf_t *buf, void *tag)
3695 kmutex_t *hash_lock = NULL;
3696 l2arc_buf_hdr_t *l2hdr;
3700 * It would be nice to assert that if it's DMU metadata (level >
3701 * 0 || it's the dnode file), then it must be syncing context.
3702 * But we don't know that information at this level.
3705 mutex_enter(&buf->b_evict_lock);
3708 /* this buffer is not on any list */
3709 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3711 if (hdr->b_state == arc_anon) {
3712 /* this buffer is already released */
3713 ASSERT(buf->b_efunc == NULL);
3715 hash_lock = HDR_LOCK(hdr);
3716 mutex_enter(hash_lock);
3718 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3721 l2hdr = hdr->b_l2hdr;
3723 mutex_enter(&l2arc_buflist_mtx);
3724 arc_buf_l2_cdata_free(hdr);
3725 hdr->b_l2hdr = NULL;
3726 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3728 buf_size = hdr->b_size;
3731 * Do we have more than one buf?
3733 if (hdr->b_datacnt > 1) {
3734 arc_buf_hdr_t *nhdr;
3736 uint64_t blksz = hdr->b_size;
3737 uint64_t spa = hdr->b_spa;
3738 arc_buf_contents_t type = hdr->b_type;
3739 uint32_t flags = hdr->b_flags;
3741 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3743 * Pull the data off of this hdr and attach it to
3744 * a new anonymous hdr.
3746 (void) remove_reference(hdr, hash_lock, tag);
3748 while (*bufp != buf)
3749 bufp = &(*bufp)->b_next;
3750 *bufp = buf->b_next;
3753 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3754 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3755 if (refcount_is_zero(&hdr->b_refcnt)) {
3756 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3757 ASSERT3U(*size, >=, hdr->b_size);
3758 atomic_add_64(size, -hdr->b_size);
3762 * We're releasing a duplicate user data buffer, update
3763 * our statistics accordingly.
3765 if (hdr->b_type == ARC_BUFC_DATA) {
3766 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3767 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3770 hdr->b_datacnt -= 1;
3771 arc_cksum_verify(buf);
3773 arc_buf_unwatch(buf);
3774 #endif /* illumos */
3776 mutex_exit(hash_lock);
3778 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3779 nhdr->b_size = blksz;
3781 nhdr->b_type = type;
3783 nhdr->b_state = arc_anon;
3784 nhdr->b_arc_access = 0;
3785 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
3786 nhdr->b_l2hdr = NULL;
3787 nhdr->b_datacnt = 1;
3788 nhdr->b_freeze_cksum = NULL;
3789 (void) refcount_add(&nhdr->b_refcnt, tag);
3791 mutex_exit(&buf->b_evict_lock);
3792 atomic_add_64(&arc_anon->arcs_size, blksz);
3794 mutex_exit(&buf->b_evict_lock);
3795 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3796 ASSERT(!list_link_active(&hdr->b_arc_node));
3797 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3798 if (hdr->b_state != arc_anon)
3799 arc_change_state(arc_anon, hdr, hash_lock);
3800 hdr->b_arc_access = 0;
3802 mutex_exit(hash_lock);
3804 buf_discard_identity(hdr);
3807 buf->b_efunc = NULL;
3808 buf->b_private = NULL;
3811 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3812 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3813 -l2hdr->b_asize, 0, 0);
3814 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3816 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3817 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3818 mutex_exit(&l2arc_buflist_mtx);
3823 arc_released(arc_buf_t *buf)
3827 mutex_enter(&buf->b_evict_lock);
3828 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3829 mutex_exit(&buf->b_evict_lock);
3835 arc_referenced(arc_buf_t *buf)
3839 mutex_enter(&buf->b_evict_lock);
3840 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3841 mutex_exit(&buf->b_evict_lock);
3842 return (referenced);
3847 arc_write_ready(zio_t *zio)
3849 arc_write_callback_t *callback = zio->io_private;
3850 arc_buf_t *buf = callback->awcb_buf;
3851 arc_buf_hdr_t *hdr = buf->b_hdr;
3853 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3854 callback->awcb_ready(zio, buf, callback->awcb_private);
3857 * If the IO is already in progress, then this is a re-write
3858 * attempt, so we need to thaw and re-compute the cksum.
3859 * It is the responsibility of the callback to handle the
3860 * accounting for any re-write attempt.
3862 if (HDR_IO_IN_PROGRESS(hdr)) {
3863 mutex_enter(&hdr->b_freeze_lock);
3864 if (hdr->b_freeze_cksum != NULL) {
3865 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3866 hdr->b_freeze_cksum = NULL;
3868 mutex_exit(&hdr->b_freeze_lock);
3870 arc_cksum_compute(buf, B_FALSE);
3871 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3875 * The SPA calls this callback for each physical write that happens on behalf
3876 * of a logical write. See the comment in dbuf_write_physdone() for details.
3879 arc_write_physdone(zio_t *zio)
3881 arc_write_callback_t *cb = zio->io_private;
3882 if (cb->awcb_physdone != NULL)
3883 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3887 arc_write_done(zio_t *zio)
3889 arc_write_callback_t *callback = zio->io_private;
3890 arc_buf_t *buf = callback->awcb_buf;
3891 arc_buf_hdr_t *hdr = buf->b_hdr;
3893 ASSERT(hdr->b_acb == NULL);
3895 if (zio->io_error == 0) {
3896 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3897 buf_discard_identity(hdr);
3899 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3900 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3901 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3904 ASSERT(BUF_EMPTY(hdr));
3908 * If the block to be written was all-zero or compressed enough to be
3909 * embedded in the BP, no write was performed so there will be no
3910 * dva/birth/checksum. The buffer must therefore remain anonymous
3913 if (!BUF_EMPTY(hdr)) {
3914 arc_buf_hdr_t *exists;
3915 kmutex_t *hash_lock;
3917 ASSERT(zio->io_error == 0);
3919 arc_cksum_verify(buf);
3921 exists = buf_hash_insert(hdr, &hash_lock);
3924 * This can only happen if we overwrite for
3925 * sync-to-convergence, because we remove
3926 * buffers from the hash table when we arc_free().
3928 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3929 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3930 panic("bad overwrite, hdr=%p exists=%p",
3931 (void *)hdr, (void *)exists);
3932 ASSERT(refcount_is_zero(&exists->b_refcnt));
3933 arc_change_state(arc_anon, exists, hash_lock);
3934 mutex_exit(hash_lock);
3935 arc_hdr_destroy(exists);
3936 exists = buf_hash_insert(hdr, &hash_lock);
3937 ASSERT3P(exists, ==, NULL);
3938 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3940 ASSERT(zio->io_prop.zp_nopwrite);
3941 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3942 panic("bad nopwrite, hdr=%p exists=%p",
3943 (void *)hdr, (void *)exists);
3946 ASSERT(hdr->b_datacnt == 1);
3947 ASSERT(hdr->b_state == arc_anon);
3948 ASSERT(BP_GET_DEDUP(zio->io_bp));
3949 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3952 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3953 /* if it's not anon, we are doing a scrub */
3954 if (!exists && hdr->b_state == arc_anon)
3955 arc_access(hdr, hash_lock);
3956 mutex_exit(hash_lock);
3958 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3961 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3962 callback->awcb_done(zio, buf, callback->awcb_private);
3964 kmem_free(callback, sizeof (arc_write_callback_t));
3968 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3969 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3970 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3971 arc_done_func_t *done, void *private, zio_priority_t priority,
3972 int zio_flags, const zbookmark_phys_t *zb)
3974 arc_buf_hdr_t *hdr = buf->b_hdr;
3975 arc_write_callback_t *callback;
3978 ASSERT(ready != NULL);
3979 ASSERT(done != NULL);
3980 ASSERT(!HDR_IO_ERROR(hdr));
3981 ASSERT((hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS) == 0);
3982 ASSERT(hdr->b_acb == NULL);
3984 hdr->b_flags |= ARC_FLAG_L2CACHE;
3986 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3987 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3988 callback->awcb_ready = ready;
3989 callback->awcb_physdone = physdone;
3990 callback->awcb_done = done;
3991 callback->awcb_private = private;
3992 callback->awcb_buf = buf;
3994 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3995 arc_write_ready, arc_write_physdone, arc_write_done, callback,
3996 priority, zio_flags, zb);
4002 arc_memory_throttle(uint64_t reserve, uint64_t txg)
4005 uint64_t available_memory = ptob(freemem);
4006 static uint64_t page_load = 0;
4007 static uint64_t last_txg = 0;
4009 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4011 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4014 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4017 if (txg > last_txg) {
4022 * If we are in pageout, we know that memory is already tight,
4023 * the arc is already going to be evicting, so we just want to
4024 * continue to let page writes occur as quickly as possible.
4026 if (curproc == pageproc) {
4027 if (page_load > MAX(ptob(minfree), available_memory) / 4)
4028 return (SET_ERROR(ERESTART));
4029 /* Note: reserve is inflated, so we deflate */
4030 page_load += reserve / 8;
4032 } else if (page_load > 0 && arc_reclaim_needed()) {
4033 /* memory is low, delay before restarting */
4034 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4035 return (SET_ERROR(EAGAIN));
4043 arc_tempreserve_clear(uint64_t reserve)
4045 atomic_add_64(&arc_tempreserve, -reserve);
4046 ASSERT((int64_t)arc_tempreserve >= 0);
4050 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4055 if (reserve > arc_c/4 && !arc_no_grow) {
4056 arc_c = MIN(arc_c_max, reserve * 4);
4057 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4059 if (reserve > arc_c)
4060 return (SET_ERROR(ENOMEM));
4063 * Don't count loaned bufs as in flight dirty data to prevent long
4064 * network delays from blocking transactions that are ready to be
4065 * assigned to a txg.
4067 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4070 * Writes will, almost always, require additional memory allocations
4071 * in order to compress/encrypt/etc the data. We therefore need to
4072 * make sure that there is sufficient available memory for this.
4074 error = arc_memory_throttle(reserve, txg);
4079 * Throttle writes when the amount of dirty data in the cache
4080 * gets too large. We try to keep the cache less than half full
4081 * of dirty blocks so that our sync times don't grow too large.
4082 * Note: if two requests come in concurrently, we might let them
4083 * both succeed, when one of them should fail. Not a huge deal.
4086 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4087 anon_size > arc_c / 4) {
4088 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4089 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4090 arc_tempreserve>>10,
4091 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4092 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4093 reserve>>10, arc_c>>10);
4094 return (SET_ERROR(ERESTART));
4096 atomic_add_64(&arc_tempreserve, reserve);
4100 static kmutex_t arc_lowmem_lock;
4102 static eventhandler_tag arc_event_lowmem = NULL;
4105 arc_lowmem(void *arg __unused, int howto __unused)
4108 /* Serialize access via arc_lowmem_lock. */
4109 mutex_enter(&arc_lowmem_lock);
4110 mutex_enter(&arc_reclaim_thr_lock);
4112 DTRACE_PROBE(arc__needfree);
4113 cv_signal(&arc_reclaim_thr_cv);
4116 * It is unsafe to block here in arbitrary threads, because we can come
4117 * here from ARC itself and may hold ARC locks and thus risk a deadlock
4118 * with ARC reclaim thread.
4120 if (curproc == pageproc) {
4122 msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4124 mutex_exit(&arc_reclaim_thr_lock);
4125 mutex_exit(&arc_lowmem_lock);
4132 int i, prefetch_tunable_set = 0;
4134 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4135 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4136 mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
4138 /* Convert seconds to clock ticks */
4139 arc_min_prefetch_lifespan = 1 * hz;
4141 /* Start out with 1/8 of all memory */
4142 arc_c = kmem_size() / 8;
4147 * On architectures where the physical memory can be larger
4148 * than the addressable space (intel in 32-bit mode), we may
4149 * need to limit the cache to 1/8 of VM size.
4151 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4154 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4155 arc_c_min = MAX(arc_c / 4, 64<<18);
4156 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4157 if (arc_c * 8 >= 1<<30)
4158 arc_c_max = (arc_c * 8) - (1<<30);
4160 arc_c_max = arc_c_min;
4161 arc_c_max = MAX(arc_c * 5, arc_c_max);
4165 * Allow the tunables to override our calculations if they are
4166 * reasonable (ie. over 16MB)
4168 if (zfs_arc_max > 64<<18 && zfs_arc_max < kmem_size())
4169 arc_c_max = zfs_arc_max;
4170 if (zfs_arc_min > 64<<18 && zfs_arc_min <= arc_c_max)
4171 arc_c_min = zfs_arc_min;
4175 arc_p = (arc_c >> 1);
4177 /* limit meta-data to 1/4 of the arc capacity */
4178 arc_meta_limit = arc_c_max / 4;
4180 /* Allow the tunable to override if it is reasonable */
4181 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4182 arc_meta_limit = zfs_arc_meta_limit;
4184 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4185 arc_c_min = arc_meta_limit / 2;
4187 if (zfs_arc_grow_retry > 0)
4188 arc_grow_retry = zfs_arc_grow_retry;
4190 if (zfs_arc_shrink_shift > 0)
4191 arc_shrink_shift = zfs_arc_shrink_shift;
4193 if (zfs_arc_p_min_shift > 0)
4194 arc_p_min_shift = zfs_arc_p_min_shift;
4196 /* if kmem_flags are set, lets try to use less memory */
4197 if (kmem_debugging())
4199 if (arc_c < arc_c_min)
4202 zfs_arc_min = arc_c_min;
4203 zfs_arc_max = arc_c_max;
4205 arc_anon = &ARC_anon;
4207 arc_mru_ghost = &ARC_mru_ghost;
4209 arc_mfu_ghost = &ARC_mfu_ghost;
4210 arc_l2c_only = &ARC_l2c_only;
4213 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4214 mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4215 NULL, MUTEX_DEFAULT, NULL);
4216 mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4217 NULL, MUTEX_DEFAULT, NULL);
4218 mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4219 NULL, MUTEX_DEFAULT, NULL);
4220 mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4221 NULL, MUTEX_DEFAULT, NULL);
4222 mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4223 NULL, MUTEX_DEFAULT, NULL);
4224 mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4225 NULL, MUTEX_DEFAULT, NULL);
4227 list_create(&arc_mru->arcs_lists[i],
4228 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4229 list_create(&arc_mru_ghost->arcs_lists[i],
4230 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4231 list_create(&arc_mfu->arcs_lists[i],
4232 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4233 list_create(&arc_mfu_ghost->arcs_lists[i],
4234 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4235 list_create(&arc_mfu_ghost->arcs_lists[i],
4236 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4237 list_create(&arc_l2c_only->arcs_lists[i],
4238 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4243 arc_thread_exit = 0;
4244 arc_eviction_list = NULL;
4245 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4246 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4248 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4249 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4251 if (arc_ksp != NULL) {
4252 arc_ksp->ks_data = &arc_stats;
4253 kstat_install(arc_ksp);
4256 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4257 TS_RUN, minclsyspri);
4260 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4261 EVENTHANDLER_PRI_FIRST);
4268 * Calculate maximum amount of dirty data per pool.
4270 * If it has been set by /etc/system, take that.
4271 * Otherwise, use a percentage of physical memory defined by
4272 * zfs_dirty_data_max_percent (default 10%) with a cap at
4273 * zfs_dirty_data_max_max (default 4GB).
4275 if (zfs_dirty_data_max == 0) {
4276 zfs_dirty_data_max = ptob(physmem) *
4277 zfs_dirty_data_max_percent / 100;
4278 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4279 zfs_dirty_data_max_max);
4283 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4284 prefetch_tunable_set = 1;
4287 if (prefetch_tunable_set == 0) {
4288 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4290 printf(" add \"vfs.zfs.prefetch_disable=0\" "
4291 "to /boot/loader.conf.\n");
4292 zfs_prefetch_disable = 1;
4295 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4296 prefetch_tunable_set == 0) {
4297 printf("ZFS NOTICE: Prefetch is disabled by default if less "
4298 "than 4GB of RAM is present;\n"
4299 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
4300 "to /boot/loader.conf.\n");
4301 zfs_prefetch_disable = 1;
4304 /* Warn about ZFS memory and address space requirements. */
4305 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4306 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4307 "expect unstable behavior.\n");
4309 if (kmem_size() < 512 * (1 << 20)) {
4310 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4311 "expect unstable behavior.\n");
4312 printf(" Consider tuning vm.kmem_size and "
4313 "vm.kmem_size_max\n");
4314 printf(" in /boot/loader.conf.\n");
4324 mutex_enter(&arc_reclaim_thr_lock);
4325 arc_thread_exit = 1;
4326 cv_signal(&arc_reclaim_thr_cv);
4327 while (arc_thread_exit != 0)
4328 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4329 mutex_exit(&arc_reclaim_thr_lock);
4335 if (arc_ksp != NULL) {
4336 kstat_delete(arc_ksp);
4340 mutex_destroy(&arc_eviction_mtx);
4341 mutex_destroy(&arc_reclaim_thr_lock);
4342 cv_destroy(&arc_reclaim_thr_cv);
4344 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4345 list_destroy(&arc_mru->arcs_lists[i]);
4346 list_destroy(&arc_mru_ghost->arcs_lists[i]);
4347 list_destroy(&arc_mfu->arcs_lists[i]);
4348 list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4349 list_destroy(&arc_l2c_only->arcs_lists[i]);
4351 mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4352 mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4353 mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4354 mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4355 mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4356 mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4361 ASSERT(arc_loaned_bytes == 0);
4363 mutex_destroy(&arc_lowmem_lock);
4365 if (arc_event_lowmem != NULL)
4366 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4373 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4374 * It uses dedicated storage devices to hold cached data, which are populated
4375 * using large infrequent writes. The main role of this cache is to boost
4376 * the performance of random read workloads. The intended L2ARC devices
4377 * include short-stroked disks, solid state disks, and other media with
4378 * substantially faster read latency than disk.
4380 * +-----------------------+
4382 * +-----------------------+
4385 * l2arc_feed_thread() arc_read()
4389 * +---------------+ |
4391 * +---------------+ |
4396 * +-------+ +-------+
4398 * | cache | | cache |
4399 * +-------+ +-------+
4400 * +=========+ .-----.
4401 * : L2ARC : |-_____-|
4402 * : devices : | Disks |
4403 * +=========+ `-_____-'
4405 * Read requests are satisfied from the following sources, in order:
4408 * 2) vdev cache of L2ARC devices
4410 * 4) vdev cache of disks
4413 * Some L2ARC device types exhibit extremely slow write performance.
4414 * To accommodate for this there are some significant differences between
4415 * the L2ARC and traditional cache design:
4417 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4418 * the ARC behave as usual, freeing buffers and placing headers on ghost
4419 * lists. The ARC does not send buffers to the L2ARC during eviction as
4420 * this would add inflated write latencies for all ARC memory pressure.
4422 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4423 * It does this by periodically scanning buffers from the eviction-end of
4424 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4425 * not already there. It scans until a headroom of buffers is satisfied,
4426 * which itself is a buffer for ARC eviction. If a compressible buffer is
4427 * found during scanning and selected for writing to an L2ARC device, we
4428 * temporarily boost scanning headroom during the next scan cycle to make
4429 * sure we adapt to compression effects (which might significantly reduce
4430 * the data volume we write to L2ARC). The thread that does this is
4431 * l2arc_feed_thread(), illustrated below; example sizes are included to
4432 * provide a better sense of ratio than this diagram:
4435 * +---------------------+----------+
4436 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4437 * +---------------------+----------+ | o L2ARC eligible
4438 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4439 * +---------------------+----------+ |
4440 * 15.9 Gbytes ^ 32 Mbytes |
4442 * l2arc_feed_thread()
4444 * l2arc write hand <--[oooo]--'
4448 * +==============================+
4449 * L2ARC dev |####|#|###|###| |####| ... |
4450 * +==============================+
4453 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4454 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4455 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4456 * safe to say that this is an uncommon case, since buffers at the end of
4457 * the ARC lists have moved there due to inactivity.
4459 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4460 * then the L2ARC simply misses copying some buffers. This serves as a
4461 * pressure valve to prevent heavy read workloads from both stalling the ARC
4462 * with waits and clogging the L2ARC with writes. This also helps prevent
4463 * the potential for the L2ARC to churn if it attempts to cache content too
4464 * quickly, such as during backups of the entire pool.
4466 * 5. After system boot and before the ARC has filled main memory, there are
4467 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4468 * lists can remain mostly static. Instead of searching from tail of these
4469 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4470 * for eligible buffers, greatly increasing its chance of finding them.
4472 * The L2ARC device write speed is also boosted during this time so that
4473 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4474 * there are no L2ARC reads, and no fear of degrading read performance
4475 * through increased writes.
4477 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4478 * the vdev queue can aggregate them into larger and fewer writes. Each
4479 * device is written to in a rotor fashion, sweeping writes through
4480 * available space then repeating.
4482 * 7. The L2ARC does not store dirty content. It never needs to flush
4483 * write buffers back to disk based storage.
4485 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4486 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4488 * The performance of the L2ARC can be tweaked by a number of tunables, which
4489 * may be necessary for different workloads:
4491 * l2arc_write_max max write bytes per interval
4492 * l2arc_write_boost extra write bytes during device warmup
4493 * l2arc_noprefetch skip caching prefetched buffers
4494 * l2arc_headroom number of max device writes to precache
4495 * l2arc_headroom_boost when we find compressed buffers during ARC
4496 * scanning, we multiply headroom by this
4497 * percentage factor for the next scan cycle,
4498 * since more compressed buffers are likely to
4500 * l2arc_feed_secs seconds between L2ARC writing
4502 * Tunables may be removed or added as future performance improvements are
4503 * integrated, and also may become zpool properties.
4505 * There are three key functions that control how the L2ARC warms up:
4507 * l2arc_write_eligible() check if a buffer is eligible to cache
4508 * l2arc_write_size() calculate how much to write
4509 * l2arc_write_interval() calculate sleep delay between writes
4511 * These three functions determine what to write, how much, and how quickly
4516 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
4519 * A buffer is *not* eligible for the L2ARC if it:
4520 * 1. belongs to a different spa.
4521 * 2. is already cached on the L2ARC.
4522 * 3. has an I/O in progress (it may be an incomplete read).
4523 * 4. is flagged not eligible (zfs property).
4525 if (hdr->b_spa != spa_guid) {
4526 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4529 if (hdr->b_l2hdr != NULL) {
4530 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4533 if (HDR_IO_IN_PROGRESS(hdr)) {
4534 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4537 if (!HDR_L2CACHE(hdr)) {
4538 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4546 l2arc_write_size(void)
4551 * Make sure our globals have meaningful values in case the user
4554 size = l2arc_write_max;
4556 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4557 "be greater than zero, resetting it to the default (%d)",
4559 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4562 if (arc_warm == B_FALSE)
4563 size += l2arc_write_boost;
4570 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4572 clock_t interval, next, now;
4575 * If the ARC lists are busy, increase our write rate; if the
4576 * lists are stale, idle back. This is achieved by checking
4577 * how much we previously wrote - if it was more than half of
4578 * what we wanted, schedule the next write much sooner.
4580 if (l2arc_feed_again && wrote > (wanted / 2))
4581 interval = (hz * l2arc_feed_min_ms) / 1000;
4583 interval = hz * l2arc_feed_secs;
4585 now = ddi_get_lbolt();
4586 next = MAX(now, MIN(now + interval, began + interval));
4592 l2arc_hdr_stat_add(void)
4594 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4595 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4599 l2arc_hdr_stat_remove(void)
4601 ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4602 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4606 * Cycle through L2ARC devices. This is how L2ARC load balances.
4607 * If a device is returned, this also returns holding the spa config lock.
4609 static l2arc_dev_t *
4610 l2arc_dev_get_next(void)
4612 l2arc_dev_t *first, *next = NULL;
4615 * Lock out the removal of spas (spa_namespace_lock), then removal
4616 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4617 * both locks will be dropped and a spa config lock held instead.
4619 mutex_enter(&spa_namespace_lock);
4620 mutex_enter(&l2arc_dev_mtx);
4622 /* if there are no vdevs, there is nothing to do */
4623 if (l2arc_ndev == 0)
4627 next = l2arc_dev_last;
4629 /* loop around the list looking for a non-faulted vdev */
4631 next = list_head(l2arc_dev_list);
4633 next = list_next(l2arc_dev_list, next);
4635 next = list_head(l2arc_dev_list);
4638 /* if we have come back to the start, bail out */
4641 else if (next == first)
4644 } while (vdev_is_dead(next->l2ad_vdev));
4646 /* if we were unable to find any usable vdevs, return NULL */
4647 if (vdev_is_dead(next->l2ad_vdev))
4650 l2arc_dev_last = next;
4653 mutex_exit(&l2arc_dev_mtx);
4656 * Grab the config lock to prevent the 'next' device from being
4657 * removed while we are writing to it.
4660 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4661 mutex_exit(&spa_namespace_lock);
4667 * Free buffers that were tagged for destruction.
4670 l2arc_do_free_on_write()
4673 l2arc_data_free_t *df, *df_prev;
4675 mutex_enter(&l2arc_free_on_write_mtx);
4676 buflist = l2arc_free_on_write;
4678 for (df = list_tail(buflist); df; df = df_prev) {
4679 df_prev = list_prev(buflist, df);
4680 ASSERT(df->l2df_data != NULL);
4681 ASSERT(df->l2df_func != NULL);
4682 df->l2df_func(df->l2df_data, df->l2df_size);
4683 list_remove(buflist, df);
4684 kmem_free(df, sizeof (l2arc_data_free_t));
4687 mutex_exit(&l2arc_free_on_write_mtx);
4691 * A write to a cache device has completed. Update all headers to allow
4692 * reads from these buffers to begin.
4695 l2arc_write_done(zio_t *zio)
4697 l2arc_write_callback_t *cb;
4700 arc_buf_hdr_t *head, *hdr, *hdr_prev;
4701 l2arc_buf_hdr_t *abl2;
4702 kmutex_t *hash_lock;
4703 int64_t bytes_dropped = 0;
4705 cb = zio->io_private;
4707 dev = cb->l2wcb_dev;
4708 ASSERT(dev != NULL);
4709 head = cb->l2wcb_head;
4710 ASSERT(head != NULL);
4711 buflist = dev->l2ad_buflist;
4712 ASSERT(buflist != NULL);
4713 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4714 l2arc_write_callback_t *, cb);
4716 if (zio->io_error != 0)
4717 ARCSTAT_BUMP(arcstat_l2_writes_error);
4719 mutex_enter(&l2arc_buflist_mtx);
4722 * All writes completed, or an error was hit.
4724 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
4725 hdr_prev = list_prev(buflist, hdr);
4726 abl2 = hdr->b_l2hdr;
4729 * Release the temporary compressed buffer as soon as possible.
4731 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4732 l2arc_release_cdata_buf(hdr);
4734 hash_lock = HDR_LOCK(hdr);
4735 if (!mutex_tryenter(hash_lock)) {
4737 * This buffer misses out. It may be in a stage
4738 * of eviction. Its ARC_L2_WRITING flag will be
4739 * left set, denying reads to this buffer.
4741 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4745 if (zio->io_error != 0) {
4747 * Error - drop L2ARC entry.
4749 list_remove(buflist, hdr);
4750 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4751 bytes_dropped += abl2->b_asize;
4752 hdr->b_l2hdr = NULL;
4753 trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4755 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4756 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
4760 * Allow ARC to begin reads to this L2ARC entry.
4762 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
4764 mutex_exit(hash_lock);
4767 atomic_inc_64(&l2arc_writes_done);
4768 list_remove(buflist, head);
4769 kmem_cache_free(hdr_cache, head);
4770 mutex_exit(&l2arc_buflist_mtx);
4772 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4774 l2arc_do_free_on_write();
4776 kmem_free(cb, sizeof (l2arc_write_callback_t));
4780 * A read to a cache device completed. Validate buffer contents before
4781 * handing over to the regular ARC routines.
4784 l2arc_read_done(zio_t *zio)
4786 l2arc_read_callback_t *cb;
4789 kmutex_t *hash_lock;
4792 ASSERT(zio->io_vd != NULL);
4793 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4795 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4797 cb = zio->io_private;
4799 buf = cb->l2rcb_buf;
4800 ASSERT(buf != NULL);
4802 hash_lock = HDR_LOCK(buf->b_hdr);
4803 mutex_enter(hash_lock);
4805 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4808 * If the buffer was compressed, decompress it first.
4810 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4811 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4812 ASSERT(zio->io_data != NULL);
4815 * Check this survived the L2ARC journey.
4817 equal = arc_cksum_equal(buf);
4818 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4819 mutex_exit(hash_lock);
4820 zio->io_private = buf;
4821 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4822 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
4825 mutex_exit(hash_lock);
4827 * Buffer didn't survive caching. Increment stats and
4828 * reissue to the original storage device.
4830 if (zio->io_error != 0) {
4831 ARCSTAT_BUMP(arcstat_l2_io_error);
4833 zio->io_error = SET_ERROR(EIO);
4836 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4839 * If there's no waiter, issue an async i/o to the primary
4840 * storage now. If there *is* a waiter, the caller must
4841 * issue the i/o in a context where it's OK to block.
4843 if (zio->io_waiter == NULL) {
4844 zio_t *pio = zio_unique_parent(zio);
4846 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4848 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4849 buf->b_data, zio->io_size, arc_read_done, buf,
4850 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4854 kmem_free(cb, sizeof (l2arc_read_callback_t));
4858 * This is the list priority from which the L2ARC will search for pages to
4859 * cache. This is used within loops (0..3) to cycle through lists in the
4860 * desired order. This order can have a significant effect on cache
4863 * Currently the metadata lists are hit first, MFU then MRU, followed by
4864 * the data lists. This function returns a locked list, and also returns
4868 l2arc_list_locked(int list_num, kmutex_t **lock)
4870 list_t *list = NULL;
4873 ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4875 if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4877 list = &arc_mfu->arcs_lists[idx];
4878 *lock = ARCS_LOCK(arc_mfu, idx);
4879 } else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4880 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4881 list = &arc_mru->arcs_lists[idx];
4882 *lock = ARCS_LOCK(arc_mru, idx);
4883 } else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4884 ARC_BUFC_NUMDATALISTS)) {
4885 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4886 list = &arc_mfu->arcs_lists[idx];
4887 *lock = ARCS_LOCK(arc_mfu, idx);
4889 idx = list_num - ARC_BUFC_NUMLISTS;
4890 list = &arc_mru->arcs_lists[idx];
4891 *lock = ARCS_LOCK(arc_mru, idx);
4894 ASSERT(!(MUTEX_HELD(*lock)));
4900 * Evict buffers from the device write hand to the distance specified in
4901 * bytes. This distance may span populated buffers, it may span nothing.
4902 * This is clearing a region on the L2ARC device ready for writing.
4903 * If the 'all' boolean is set, every buffer is evicted.
4906 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4909 l2arc_buf_hdr_t *abl2;
4910 arc_buf_hdr_t *hdr, *hdr_prev;
4911 kmutex_t *hash_lock;
4913 int64_t bytes_evicted = 0;
4915 buflist = dev->l2ad_buflist;
4917 if (buflist == NULL)
4920 if (!all && dev->l2ad_first) {
4922 * This is the first sweep through the device. There is
4928 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4930 * When nearing the end of the device, evict to the end
4931 * before the device write hand jumps to the start.
4933 taddr = dev->l2ad_end;
4935 taddr = dev->l2ad_hand + distance;
4937 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4938 uint64_t, taddr, boolean_t, all);
4941 mutex_enter(&l2arc_buflist_mtx);
4942 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
4943 hdr_prev = list_prev(buflist, hdr);
4945 hash_lock = HDR_LOCK(hdr);
4946 if (!mutex_tryenter(hash_lock)) {
4948 * Missed the hash lock. Retry.
4950 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4951 mutex_exit(&l2arc_buflist_mtx);
4952 mutex_enter(hash_lock);
4953 mutex_exit(hash_lock);
4957 if (HDR_L2_WRITE_HEAD(hdr)) {
4959 * We hit a write head node. Leave it for
4960 * l2arc_write_done().
4962 list_remove(buflist, hdr);
4963 mutex_exit(hash_lock);
4967 if (!all && hdr->b_l2hdr != NULL &&
4968 (hdr->b_l2hdr->b_daddr > taddr ||
4969 hdr->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4971 * We've evicted to the target address,
4972 * or the end of the device.
4974 mutex_exit(hash_lock);
4978 if (HDR_FREE_IN_PROGRESS(hdr)) {
4980 * Already on the path to destruction.
4982 mutex_exit(hash_lock);
4986 if (hdr->b_state == arc_l2c_only) {
4987 ASSERT(!HDR_L2_READING(hdr));
4989 * This doesn't exist in the ARC. Destroy.
4990 * arc_hdr_destroy() will call list_remove()
4991 * and decrement arcstat_l2_size.
4993 arc_change_state(arc_anon, hdr, hash_lock);
4994 arc_hdr_destroy(hdr);
4997 * Invalidate issued or about to be issued
4998 * reads, since we may be about to write
4999 * over this location.
5001 if (HDR_L2_READING(hdr)) {
5002 ARCSTAT_BUMP(arcstat_l2_evict_reading);
5003 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
5007 * Tell ARC this no longer exists in L2ARC.
5009 if (hdr->b_l2hdr != NULL) {
5010 abl2 = hdr->b_l2hdr;
5011 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
5012 bytes_evicted += abl2->b_asize;
5013 hdr->b_l2hdr = NULL;
5015 * We are destroying l2hdr, so ensure that
5016 * its compressed buffer, if any, is not leaked.
5018 ASSERT(abl2->b_tmp_cdata == NULL);
5019 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
5020 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5022 list_remove(buflist, hdr);
5025 * This may have been leftover after a
5028 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5030 mutex_exit(hash_lock);
5032 mutex_exit(&l2arc_buflist_mtx);
5034 vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
5035 dev->l2ad_evict = taddr;
5039 * Find and write ARC buffers to the L2ARC device.
5041 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
5042 * for reading until they have completed writing.
5043 * The headroom_boost is an in-out parameter used to maintain headroom boost
5044 * state between calls to this function.
5046 * Returns the number of bytes actually written (which may be smaller than
5047 * the delta by which the device hand has changed due to alignment).
5050 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5051 boolean_t *headroom_boost)
5053 arc_buf_hdr_t *hdr, *hdr_prev, *head;
5055 uint64_t write_asize, write_psize, write_sz, headroom,
5058 kmutex_t *list_lock;
5060 l2arc_write_callback_t *cb;
5062 uint64_t guid = spa_load_guid(spa);
5063 const boolean_t do_headroom_boost = *headroom_boost;
5066 ASSERT(dev->l2ad_vdev != NULL);
5068 /* Lower the flag now, we might want to raise it again later. */
5069 *headroom_boost = B_FALSE;
5072 write_sz = write_asize = write_psize = 0;
5074 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5075 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
5077 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
5079 * We will want to try to compress buffers that are at least 2x the
5080 * device sector size.
5082 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5085 * Copy buffers for L2ARC writing.
5087 mutex_enter(&l2arc_buflist_mtx);
5088 for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
5089 uint64_t passed_sz = 0;
5091 list = l2arc_list_locked(try, &list_lock);
5092 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
5095 * L2ARC fast warmup.
5097 * Until the ARC is warm and starts to evict, read from the
5098 * head of the ARC lists rather than the tail.
5100 if (arc_warm == B_FALSE)
5101 hdr = list_head(list);
5103 hdr = list_tail(list);
5105 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
5107 headroom = target_sz * l2arc_headroom * 2 / ARC_BUFC_NUMLISTS;
5108 if (do_headroom_boost)
5109 headroom = (headroom * l2arc_headroom_boost) / 100;
5111 for (; hdr; hdr = hdr_prev) {
5112 l2arc_buf_hdr_t *l2hdr;
5113 kmutex_t *hash_lock;
5116 if (arc_warm == B_FALSE)
5117 hdr_prev = list_next(list, hdr);
5119 hdr_prev = list_prev(list, hdr);
5120 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
5122 hash_lock = HDR_LOCK(hdr);
5123 if (!mutex_tryenter(hash_lock)) {
5124 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5126 * Skip this buffer rather than waiting.
5131 passed_sz += hdr->b_size;
5132 if (passed_sz > headroom) {
5136 mutex_exit(hash_lock);
5137 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5141 if (!l2arc_write_eligible(guid, hdr)) {
5142 mutex_exit(hash_lock);
5146 if ((write_sz + hdr->b_size) > target_sz) {
5148 mutex_exit(hash_lock);
5149 ARCSTAT_BUMP(arcstat_l2_write_full);
5155 * Insert a dummy header on the buflist so
5156 * l2arc_write_done() can find where the
5157 * write buffers begin without searching.
5159 list_insert_head(dev->l2ad_buflist, head);
5162 sizeof (l2arc_write_callback_t), KM_SLEEP);
5163 cb->l2wcb_dev = dev;
5164 cb->l2wcb_head = head;
5165 pio = zio_root(spa, l2arc_write_done, cb,
5167 ARCSTAT_BUMP(arcstat_l2_write_pios);
5171 * Create and add a new L2ARC header.
5173 l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
5175 hdr->b_flags |= ARC_FLAG_L2_WRITING;
5178 * Temporarily stash the data buffer in b_tmp_cdata.
5179 * The subsequent write step will pick it up from
5180 * there. This is because can't access hdr->b_buf
5181 * without holding the hash_lock, which we in turn
5182 * can't access without holding the ARC list locks
5183 * (which we want to avoid during compression/writing).
5185 l2hdr->b_compress = ZIO_COMPRESS_OFF;
5186 l2hdr->b_asize = hdr->b_size;
5187 l2hdr->b_tmp_cdata = hdr->b_buf->b_data;
5189 buf_sz = hdr->b_size;
5190 hdr->b_l2hdr = l2hdr;
5192 list_insert_head(dev->l2ad_buflist, hdr);
5195 * Compute and store the buffer cksum before
5196 * writing. On debug the cksum is verified first.
5198 arc_cksum_verify(hdr->b_buf);
5199 arc_cksum_compute(hdr->b_buf, B_TRUE);
5201 mutex_exit(hash_lock);
5206 mutex_exit(list_lock);
5212 /* No buffers selected for writing? */
5215 mutex_exit(&l2arc_buflist_mtx);
5216 kmem_cache_free(hdr_cache, head);
5221 * Now start writing the buffers. We're starting at the write head
5222 * and work backwards, retracing the course of the buffer selector
5225 for (hdr = list_prev(dev->l2ad_buflist, head); hdr;
5226 hdr = list_prev(dev->l2ad_buflist, hdr)) {
5227 l2arc_buf_hdr_t *l2hdr;
5231 * We shouldn't need to lock the buffer here, since we flagged
5232 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
5233 * take care to only access its L2 cache parameters. In
5234 * particular, hdr->b_buf may be invalid by now due to
5237 l2hdr = hdr->b_l2hdr;
5238 l2hdr->b_daddr = dev->l2ad_hand;
5240 if ((hdr->b_flags & ARC_FLAG_L2COMPRESS) &&
5241 l2hdr->b_asize >= buf_compress_minsz) {
5242 if (l2arc_compress_buf(l2hdr)) {
5244 * If compression succeeded, enable headroom
5245 * boost on the next scan cycle.
5247 *headroom_boost = B_TRUE;
5252 * Pick up the buffer data we had previously stashed away
5253 * (and now potentially also compressed).
5255 buf_data = l2hdr->b_tmp_cdata;
5256 buf_sz = l2hdr->b_asize;
5259 * If the data has not been compressed, then clear b_tmp_cdata
5260 * to make sure that it points only to a temporary compression
5263 if (!L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress))
5264 l2hdr->b_tmp_cdata = NULL;
5266 /* Compression may have squashed the buffer to zero length. */
5270 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5271 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5272 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5273 ZIO_FLAG_CANFAIL, B_FALSE);
5275 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5277 (void) zio_nowait(wzio);
5279 write_asize += buf_sz;
5281 * Keep the clock hand suitably device-aligned.
5283 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5284 write_psize += buf_p_sz;
5285 dev->l2ad_hand += buf_p_sz;
5289 mutex_exit(&l2arc_buflist_mtx);
5291 ASSERT3U(write_asize, <=, target_sz);
5292 ARCSTAT_BUMP(arcstat_l2_writes_sent);
5293 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5294 ARCSTAT_INCR(arcstat_l2_size, write_sz);
5295 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5296 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
5299 * Bump device hand to the device start if it is approaching the end.
5300 * l2arc_evict() will already have evicted ahead for this case.
5302 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5303 dev->l2ad_hand = dev->l2ad_start;
5304 dev->l2ad_evict = dev->l2ad_start;
5305 dev->l2ad_first = B_FALSE;
5308 dev->l2ad_writing = B_TRUE;
5309 (void) zio_wait(pio);
5310 dev->l2ad_writing = B_FALSE;
5312 return (write_asize);
5316 * Compresses an L2ARC buffer.
5317 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5318 * size in l2hdr->b_asize. This routine tries to compress the data and
5319 * depending on the compression result there are three possible outcomes:
5320 * *) The buffer was incompressible. The original l2hdr contents were left
5321 * untouched and are ready for writing to an L2 device.
5322 * *) The buffer was all-zeros, so there is no need to write it to an L2
5323 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5324 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5325 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5326 * data buffer which holds the compressed data to be written, and b_asize
5327 * tells us how much data there is. b_compress is set to the appropriate
5328 * compression algorithm. Once writing is done, invoke
5329 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5331 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5332 * buffer was incompressible).
5335 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5338 size_t csize, len, rounded;
5340 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5341 ASSERT(l2hdr->b_tmp_cdata != NULL);
5343 len = l2hdr->b_asize;
5344 cdata = zio_data_buf_alloc(len);
5345 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5346 cdata, l2hdr->b_asize);
5349 /* zero block, indicate that there's nothing to write */
5350 zio_data_buf_free(cdata, len);
5351 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5353 l2hdr->b_tmp_cdata = NULL;
5354 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5358 rounded = P2ROUNDUP(csize,
5359 (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
5360 if (rounded < len) {
5362 * Compression succeeded, we'll keep the cdata around for
5363 * writing and release it afterwards.
5365 if (rounded > csize) {
5366 bzero((char *)cdata + csize, rounded - csize);
5369 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5370 l2hdr->b_asize = csize;
5371 l2hdr->b_tmp_cdata = cdata;
5372 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5376 * Compression failed, release the compressed buffer.
5377 * l2hdr will be left unmodified.
5379 zio_data_buf_free(cdata, len);
5380 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5386 * Decompresses a zio read back from an l2arc device. On success, the
5387 * underlying zio's io_data buffer is overwritten by the uncompressed
5388 * version. On decompression error (corrupt compressed stream), the
5389 * zio->io_error value is set to signal an I/O error.
5391 * Please note that the compressed data stream is not checksummed, so
5392 * if the underlying device is experiencing data corruption, we may feed
5393 * corrupt data to the decompressor, so the decompressor needs to be
5394 * able to handle this situation (LZ4 does).
5397 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5399 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5401 if (zio->io_error != 0) {
5403 * An io error has occured, just restore the original io
5404 * size in preparation for a main pool read.
5406 zio->io_orig_size = zio->io_size = hdr->b_size;
5410 if (c == ZIO_COMPRESS_EMPTY) {
5412 * An empty buffer results in a null zio, which means we
5413 * need to fill its io_data after we're done restoring the
5414 * buffer's contents.
5416 ASSERT(hdr->b_buf != NULL);
5417 bzero(hdr->b_buf->b_data, hdr->b_size);
5418 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5420 ASSERT(zio->io_data != NULL);
5422 * We copy the compressed data from the start of the arc buffer
5423 * (the zio_read will have pulled in only what we need, the
5424 * rest is garbage which we will overwrite at decompression)
5425 * and then decompress back to the ARC data buffer. This way we
5426 * can minimize copying by simply decompressing back over the
5427 * original compressed data (rather than decompressing to an
5428 * aux buffer and then copying back the uncompressed buffer,
5429 * which is likely to be much larger).
5434 csize = zio->io_size;
5435 cdata = zio_data_buf_alloc(csize);
5436 bcopy(zio->io_data, cdata, csize);
5437 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5439 zio->io_error = EIO;
5440 zio_data_buf_free(cdata, csize);
5443 /* Restore the expected uncompressed IO size. */
5444 zio->io_orig_size = zio->io_size = hdr->b_size;
5448 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5449 * This buffer serves as a temporary holder of compressed data while
5450 * the buffer entry is being written to an l2arc device. Once that is
5451 * done, we can dispose of it.
5454 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
5456 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
5458 ASSERT(L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress));
5459 if (l2hdr->b_compress != ZIO_COMPRESS_EMPTY) {
5461 * If the data was compressed, then we've allocated a
5462 * temporary buffer for it, so now we need to release it.
5464 ASSERT(l2hdr->b_tmp_cdata != NULL);
5465 zio_data_buf_free(l2hdr->b_tmp_cdata, hdr->b_size);
5466 l2hdr->b_tmp_cdata = NULL;
5468 ASSERT(l2hdr->b_tmp_cdata == NULL);
5473 * This thread feeds the L2ARC at regular intervals. This is the beating
5474 * heart of the L2ARC.
5477 l2arc_feed_thread(void *dummy __unused)
5482 uint64_t size, wrote;
5483 clock_t begin, next = ddi_get_lbolt();
5484 boolean_t headroom_boost = B_FALSE;
5486 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5488 mutex_enter(&l2arc_feed_thr_lock);
5490 while (l2arc_thread_exit == 0) {
5491 CALLB_CPR_SAFE_BEGIN(&cpr);
5492 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5493 next - ddi_get_lbolt());
5494 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5495 next = ddi_get_lbolt() + hz;
5498 * Quick check for L2ARC devices.
5500 mutex_enter(&l2arc_dev_mtx);
5501 if (l2arc_ndev == 0) {
5502 mutex_exit(&l2arc_dev_mtx);
5505 mutex_exit(&l2arc_dev_mtx);
5506 begin = ddi_get_lbolt();
5509 * This selects the next l2arc device to write to, and in
5510 * doing so the next spa to feed from: dev->l2ad_spa. This
5511 * will return NULL if there are now no l2arc devices or if
5512 * they are all faulted.
5514 * If a device is returned, its spa's config lock is also
5515 * held to prevent device removal. l2arc_dev_get_next()
5516 * will grab and release l2arc_dev_mtx.
5518 if ((dev = l2arc_dev_get_next()) == NULL)
5521 spa = dev->l2ad_spa;
5522 ASSERT(spa != NULL);
5525 * If the pool is read-only then force the feed thread to
5526 * sleep a little longer.
5528 if (!spa_writeable(spa)) {
5529 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5530 spa_config_exit(spa, SCL_L2ARC, dev);
5535 * Avoid contributing to memory pressure.
5537 if (arc_reclaim_needed()) {
5538 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5539 spa_config_exit(spa, SCL_L2ARC, dev);
5543 ARCSTAT_BUMP(arcstat_l2_feeds);
5545 size = l2arc_write_size();
5548 * Evict L2ARC buffers that will be overwritten.
5550 l2arc_evict(dev, size, B_FALSE);
5553 * Write ARC buffers.
5555 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5558 * Calculate interval between writes.
5560 next = l2arc_write_interval(begin, size, wrote);
5561 spa_config_exit(spa, SCL_L2ARC, dev);
5564 l2arc_thread_exit = 0;
5565 cv_broadcast(&l2arc_feed_thr_cv);
5566 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5571 l2arc_vdev_present(vdev_t *vd)
5575 mutex_enter(&l2arc_dev_mtx);
5576 for (dev = list_head(l2arc_dev_list); dev != NULL;
5577 dev = list_next(l2arc_dev_list, dev)) {
5578 if (dev->l2ad_vdev == vd)
5581 mutex_exit(&l2arc_dev_mtx);
5583 return (dev != NULL);
5587 * Add a vdev for use by the L2ARC. By this point the spa has already
5588 * validated the vdev and opened it.
5591 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5593 l2arc_dev_t *adddev;
5595 ASSERT(!l2arc_vdev_present(vd));
5597 vdev_ashift_optimize(vd);
5600 * Create a new l2arc device entry.
5602 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5603 adddev->l2ad_spa = spa;
5604 adddev->l2ad_vdev = vd;
5605 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5606 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5607 adddev->l2ad_hand = adddev->l2ad_start;
5608 adddev->l2ad_evict = adddev->l2ad_start;
5609 adddev->l2ad_first = B_TRUE;
5610 adddev->l2ad_writing = B_FALSE;
5613 * This is a list of all ARC buffers that are still valid on the
5616 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5617 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5618 offsetof(arc_buf_hdr_t, b_l2node));
5620 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5623 * Add device to global list
5625 mutex_enter(&l2arc_dev_mtx);
5626 list_insert_head(l2arc_dev_list, adddev);
5627 atomic_inc_64(&l2arc_ndev);
5628 mutex_exit(&l2arc_dev_mtx);
5632 * Remove a vdev from the L2ARC.
5635 l2arc_remove_vdev(vdev_t *vd)
5637 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5640 * Find the device by vdev
5642 mutex_enter(&l2arc_dev_mtx);
5643 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5644 nextdev = list_next(l2arc_dev_list, dev);
5645 if (vd == dev->l2ad_vdev) {
5650 ASSERT(remdev != NULL);
5653 * Remove device from global list
5655 list_remove(l2arc_dev_list, remdev);
5656 l2arc_dev_last = NULL; /* may have been invalidated */
5657 atomic_dec_64(&l2arc_ndev);
5658 mutex_exit(&l2arc_dev_mtx);
5661 * Clear all buflists and ARC references. L2ARC device flush.
5663 l2arc_evict(remdev, 0, B_TRUE);
5664 list_destroy(remdev->l2ad_buflist);
5665 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5666 kmem_free(remdev, sizeof (l2arc_dev_t));
5672 l2arc_thread_exit = 0;
5674 l2arc_writes_sent = 0;
5675 l2arc_writes_done = 0;
5677 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5678 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5679 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5680 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5681 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5683 l2arc_dev_list = &L2ARC_dev_list;
5684 l2arc_free_on_write = &L2ARC_free_on_write;
5685 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5686 offsetof(l2arc_dev_t, l2ad_node));
5687 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5688 offsetof(l2arc_data_free_t, l2df_list_node));
5695 * This is called from dmu_fini(), which is called from spa_fini();
5696 * Because of this, we can assume that all l2arc devices have
5697 * already been removed when the pools themselves were removed.
5700 l2arc_do_free_on_write();
5702 mutex_destroy(&l2arc_feed_thr_lock);
5703 cv_destroy(&l2arc_feed_thr_cv);
5704 mutex_destroy(&l2arc_dev_mtx);
5705 mutex_destroy(&l2arc_buflist_mtx);
5706 mutex_destroy(&l2arc_free_on_write_mtx);
5708 list_destroy(l2arc_dev_list);
5709 list_destroy(l2arc_free_on_write);
5715 if (!(spa_mode_global & FWRITE))
5718 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5719 TS_RUN, minclsyspri);
5725 if (!(spa_mode_global & FWRITE))
5728 mutex_enter(&l2arc_feed_thr_lock);
5729 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5730 l2arc_thread_exit = 1;
5731 while (l2arc_thread_exit != 0)
5732 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5733 mutex_exit(&l2arc_feed_thr_lock);