4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
24 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
30 * DVA-based Adjustable Replacement Cache
32 * While much of the theory of operation used here is
33 * based on the self-tuning, low overhead replacement cache
34 * presented by Megiddo and Modha at FAST 2003, there are some
35 * significant differences:
37 * 1. The Megiddo and Modha model assumes any page is evictable.
38 * Pages in its cache cannot be "locked" into memory. This makes
39 * the eviction algorithm simple: evict the last page in the list.
40 * This also make the performance characteristics easy to reason
41 * about. Our cache is not so simple. At any given moment, some
42 * subset of the blocks in the cache are un-evictable because we
43 * have handed out a reference to them. Blocks are only evictable
44 * when there are no external references active. This makes
45 * eviction far more problematic: we choose to evict the evictable
46 * blocks that are the "lowest" in the list.
48 * There are times when it is not possible to evict the requested
49 * space. In these circumstances we are unable to adjust the cache
50 * size. To prevent the cache growing unbounded at these times we
51 * implement a "cache throttle" that slows the flow of new data
52 * into the cache until we can make space available.
54 * 2. The Megiddo and Modha model assumes a fixed cache size.
55 * Pages are evicted when the cache is full and there is a cache
56 * miss. Our model has a variable sized cache. It grows with
57 * high use, but also tries to react to memory pressure from the
58 * operating system: decreasing its size when system memory is
61 * 3. The Megiddo and Modha model assumes a fixed page size. All
62 * elements of the cache are therefore exactly the same size. So
63 * when adjusting the cache size following a cache miss, its simply
64 * a matter of choosing a single page to evict. In our model, we
65 * have variable sized cache blocks (rangeing from 512 bytes to
66 * 128K bytes). We therefore choose a set of blocks to evict to make
67 * space for a cache miss that approximates as closely as possible
68 * the space used by the new block.
70 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71 * by N. Megiddo & D. Modha, FAST 2003
77 * A new reference to a cache buffer can be obtained in two
78 * ways: 1) via a hash table lookup using the DVA as a key,
79 * or 2) via one of the ARC lists. The arc_read() interface
80 * uses method 1, while the internal arc algorithms for
81 * adjusting the cache use method 2. We therefore provide two
82 * types of locks: 1) the hash table lock array, and 2) the
85 * Buffers do not have their own mutexs, rather they rely on the
86 * hash table mutexs for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexs).
89 * buf_hash_find() returns the appropriate mutex (held) when it
90 * locates the requested buffer in the hash table. It returns
91 * NULL for the mutex if the buffer was not in the table.
93 * buf_hash_remove() expects the appropriate hash mutex to be
94 * already held before it is invoked.
96 * Each arc state also has a mutex which is used to protect the
97 * buffer list associated with the state. When attempting to
98 * obtain a hash table lock while holding an arc list lock you
99 * must use: mutex_tryenter() to avoid deadlock. Also note that
100 * the active state mutex must be held before the ghost state mutex.
102 * Arc buffers may have an associated eviction callback function.
103 * This function will be invoked prior to removing the buffer (e.g.
104 * in arc_do_user_evicts()). Note however that the data associated
105 * with the buffer may be evicted prior to the callback. The callback
106 * must be made with *no locks held* (to prevent deadlock). Additionally,
107 * the users of callbacks must ensure that their private data is
108 * protected from simultaneous callbacks from arc_clear_callback()
109 * and arc_do_user_evicts().
111 * Note that the majority of the performance stats are manipulated
112 * with atomic operations.
114 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
116 * - L2ARC buflist creation
117 * - L2ARC buflist eviction
118 * - L2ARC write completion, which walks L2ARC buflists
119 * - ARC header destruction, as it removes from L2ARC buflists
120 * - ARC header release, as it removes from L2ARC buflists
125 #include <sys/zio_compress.h>
126 #include <sys/zfs_context.h>
128 #include <sys/refcount.h>
129 #include <sys/vdev.h>
130 #include <sys/vdev_impl.h>
131 #include <sys/dsl_pool.h>
133 #include <sys/dnlc.h>
135 #include <sys/callb.h>
136 #include <sys/kstat.h>
137 #include <sys/trim_map.h>
138 #include <zfs_fletcher.h>
141 #include <vm/vm_pageout.h>
142 #include <machine/vmparam.h>
146 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
147 boolean_t arc_watch = B_FALSE;
152 static kmutex_t arc_reclaim_thr_lock;
153 static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
154 static uint8_t arc_thread_exit;
156 #define ARC_REDUCE_DNLC_PERCENT 3
157 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
159 typedef enum arc_reclaim_strategy {
160 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
161 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
162 } arc_reclaim_strategy_t;
165 * The number of iterations through arc_evict_*() before we
166 * drop & reacquire the lock.
168 int arc_evict_iterations = 100;
170 /* number of seconds before growing cache again */
171 static int arc_grow_retry = 60;
173 /* shift of arc_c for calculating both min and max arc_p */
174 static int arc_p_min_shift = 4;
176 /* log2(fraction of arc to reclaim) */
177 static int arc_shrink_shift = 5;
180 * minimum lifespan of a prefetch block in clock ticks
181 * (initialized in arc_init())
183 static int arc_min_prefetch_lifespan;
186 * If this percent of memory is free, don't throttle.
188 int arc_lotsfree_percent = 10;
191 extern int zfs_prefetch_disable;
194 * The arc has filled available memory and has now warmed up.
196 static boolean_t arc_warm;
198 uint64_t zfs_arc_max;
199 uint64_t zfs_arc_min;
200 uint64_t zfs_arc_meta_limit = 0;
201 uint64_t zfs_arc_meta_min = 0;
202 int zfs_arc_grow_retry = 0;
203 int zfs_arc_shrink_shift = 0;
204 int zfs_arc_p_min_shift = 0;
205 int zfs_disable_dup_eviction = 0;
206 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
207 u_int zfs_arc_free_target = 0;
209 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
210 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
214 arc_free_target_init(void *unused __unused)
217 zfs_arc_free_target = vm_pageout_wakeup_thresh;
219 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
220 arc_free_target_init, NULL);
222 TUNABLE_QUAD("vfs.zfs.arc_max", &zfs_arc_max);
223 TUNABLE_QUAD("vfs.zfs.arc_min", &zfs_arc_min);
224 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
225 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
226 TUNABLE_QUAD("vfs.zfs.arc_average_blocksize", &zfs_arc_average_blocksize);
227 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
228 SYSCTL_DECL(_vfs_zfs);
229 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
231 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
233 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
234 &zfs_arc_average_blocksize, 0,
235 "ARC average blocksize");
236 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
237 &arc_shrink_shift, 0,
238 "log2(fraction of arc to reclaim)");
241 * We don't have a tunable for arc_free_target due to the dependency on
242 * pagedaemon initialisation.
244 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
245 CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
246 sysctl_vfs_zfs_arc_free_target, "IU",
247 "Desired number of free pages below which ARC triggers reclaim");
250 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
255 val = zfs_arc_free_target;
256 err = sysctl_handle_int(oidp, &val, 0, req);
257 if (err != 0 || req->newptr == NULL)
262 if (val > cnt.v_page_count)
265 zfs_arc_free_target = val;
271 * Must be declared here, before the definition of corresponding kstat
272 * macro which uses the same names will confuse the compiler.
274 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
275 CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
276 sysctl_vfs_zfs_arc_meta_limit, "QU",
277 "ARC metadata limit");
281 * Note that buffers can be in one of 6 states:
282 * ARC_anon - anonymous (discussed below)
283 * ARC_mru - recently used, currently cached
284 * ARC_mru_ghost - recentely used, no longer in cache
285 * ARC_mfu - frequently used, currently cached
286 * ARC_mfu_ghost - frequently used, no longer in cache
287 * ARC_l2c_only - exists in L2ARC but not other states
288 * When there are no active references to the buffer, they are
289 * are linked onto a list in one of these arc states. These are
290 * the only buffers that can be evicted or deleted. Within each
291 * state there are multiple lists, one for meta-data and one for
292 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
293 * etc.) is tracked separately so that it can be managed more
294 * explicitly: favored over data, limited explicitly.
296 * Anonymous buffers are buffers that are not associated with
297 * a DVA. These are buffers that hold dirty block copies
298 * before they are written to stable storage. By definition,
299 * they are "ref'd" and are considered part of arc_mru
300 * that cannot be freed. Generally, they will aquire a DVA
301 * as they are written and migrate onto the arc_mru list.
303 * The ARC_l2c_only state is for buffers that are in the second
304 * level ARC but no longer in any of the ARC_m* lists. The second
305 * level ARC itself may also contain buffers that are in any of
306 * the ARC_m* states - meaning that a buffer can exist in two
307 * places. The reason for the ARC_l2c_only state is to keep the
308 * buffer header in the hash table, so that reads that hit the
309 * second level ARC benefit from these fast lookups.
312 #define ARCS_LOCK_PAD CACHE_LINE_SIZE
316 unsigned char pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
321 * must be power of two for mask use to work
324 #define ARC_BUFC_NUMDATALISTS 16
325 #define ARC_BUFC_NUMMETADATALISTS 16
326 #define ARC_BUFC_NUMLISTS (ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
328 typedef struct arc_state {
329 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
330 uint64_t arcs_size; /* total amount of data in this state */
331 list_t arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
332 struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
335 #define ARCS_LOCK(s, i) (&((s)->arcs_locks[(i)].arcs_lock))
338 static arc_state_t ARC_anon;
339 static arc_state_t ARC_mru;
340 static arc_state_t ARC_mru_ghost;
341 static arc_state_t ARC_mfu;
342 static arc_state_t ARC_mfu_ghost;
343 static arc_state_t ARC_l2c_only;
345 typedef struct arc_stats {
346 kstat_named_t arcstat_hits;
347 kstat_named_t arcstat_misses;
348 kstat_named_t arcstat_demand_data_hits;
349 kstat_named_t arcstat_demand_data_misses;
350 kstat_named_t arcstat_demand_metadata_hits;
351 kstat_named_t arcstat_demand_metadata_misses;
352 kstat_named_t arcstat_prefetch_data_hits;
353 kstat_named_t arcstat_prefetch_data_misses;
354 kstat_named_t arcstat_prefetch_metadata_hits;
355 kstat_named_t arcstat_prefetch_metadata_misses;
356 kstat_named_t arcstat_mru_hits;
357 kstat_named_t arcstat_mru_ghost_hits;
358 kstat_named_t arcstat_mfu_hits;
359 kstat_named_t arcstat_mfu_ghost_hits;
360 kstat_named_t arcstat_allocated;
361 kstat_named_t arcstat_deleted;
362 kstat_named_t arcstat_stolen;
363 kstat_named_t arcstat_recycle_miss;
365 * Number of buffers that could not be evicted because the hash lock
366 * was held by another thread. The lock may not necessarily be held
367 * by something using the same buffer, since hash locks are shared
368 * by multiple buffers.
370 kstat_named_t arcstat_mutex_miss;
372 * Number of buffers skipped because they have I/O in progress, are
373 * indrect prefetch buffers that have not lived long enough, or are
374 * not from the spa we're trying to evict from.
376 kstat_named_t arcstat_evict_skip;
377 kstat_named_t arcstat_evict_l2_cached;
378 kstat_named_t arcstat_evict_l2_eligible;
379 kstat_named_t arcstat_evict_l2_ineligible;
380 kstat_named_t arcstat_hash_elements;
381 kstat_named_t arcstat_hash_elements_max;
382 kstat_named_t arcstat_hash_collisions;
383 kstat_named_t arcstat_hash_chains;
384 kstat_named_t arcstat_hash_chain_max;
385 kstat_named_t arcstat_p;
386 kstat_named_t arcstat_c;
387 kstat_named_t arcstat_c_min;
388 kstat_named_t arcstat_c_max;
389 kstat_named_t arcstat_size;
390 kstat_named_t arcstat_hdr_size;
391 kstat_named_t arcstat_data_size;
392 kstat_named_t arcstat_other_size;
393 kstat_named_t arcstat_l2_hits;
394 kstat_named_t arcstat_l2_misses;
395 kstat_named_t arcstat_l2_feeds;
396 kstat_named_t arcstat_l2_rw_clash;
397 kstat_named_t arcstat_l2_read_bytes;
398 kstat_named_t arcstat_l2_write_bytes;
399 kstat_named_t arcstat_l2_writes_sent;
400 kstat_named_t arcstat_l2_writes_done;
401 kstat_named_t arcstat_l2_writes_error;
402 kstat_named_t arcstat_l2_writes_hdr_miss;
403 kstat_named_t arcstat_l2_evict_lock_retry;
404 kstat_named_t arcstat_l2_evict_reading;
405 kstat_named_t arcstat_l2_free_on_write;
406 kstat_named_t arcstat_l2_cdata_free_on_write;
407 kstat_named_t arcstat_l2_abort_lowmem;
408 kstat_named_t arcstat_l2_cksum_bad;
409 kstat_named_t arcstat_l2_io_error;
410 kstat_named_t arcstat_l2_size;
411 kstat_named_t arcstat_l2_asize;
412 kstat_named_t arcstat_l2_hdr_size;
413 kstat_named_t arcstat_l2_compress_successes;
414 kstat_named_t arcstat_l2_compress_zeros;
415 kstat_named_t arcstat_l2_compress_failures;
416 kstat_named_t arcstat_l2_write_trylock_fail;
417 kstat_named_t arcstat_l2_write_passed_headroom;
418 kstat_named_t arcstat_l2_write_spa_mismatch;
419 kstat_named_t arcstat_l2_write_in_l2;
420 kstat_named_t arcstat_l2_write_hdr_io_in_progress;
421 kstat_named_t arcstat_l2_write_not_cacheable;
422 kstat_named_t arcstat_l2_write_full;
423 kstat_named_t arcstat_l2_write_buffer_iter;
424 kstat_named_t arcstat_l2_write_pios;
425 kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
426 kstat_named_t arcstat_l2_write_buffer_list_iter;
427 kstat_named_t arcstat_l2_write_buffer_list_null_iter;
428 kstat_named_t arcstat_memory_throttle_count;
429 kstat_named_t arcstat_duplicate_buffers;
430 kstat_named_t arcstat_duplicate_buffers_size;
431 kstat_named_t arcstat_duplicate_reads;
432 kstat_named_t arcstat_meta_used;
433 kstat_named_t arcstat_meta_limit;
434 kstat_named_t arcstat_meta_max;
435 kstat_named_t arcstat_meta_min;
438 static arc_stats_t arc_stats = {
439 { "hits", KSTAT_DATA_UINT64 },
440 { "misses", KSTAT_DATA_UINT64 },
441 { "demand_data_hits", KSTAT_DATA_UINT64 },
442 { "demand_data_misses", KSTAT_DATA_UINT64 },
443 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
444 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
445 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
446 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
447 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
448 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
449 { "mru_hits", KSTAT_DATA_UINT64 },
450 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
451 { "mfu_hits", KSTAT_DATA_UINT64 },
452 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
453 { "allocated", KSTAT_DATA_UINT64 },
454 { "deleted", KSTAT_DATA_UINT64 },
455 { "stolen", KSTAT_DATA_UINT64 },
456 { "recycle_miss", KSTAT_DATA_UINT64 },
457 { "mutex_miss", KSTAT_DATA_UINT64 },
458 { "evict_skip", KSTAT_DATA_UINT64 },
459 { "evict_l2_cached", KSTAT_DATA_UINT64 },
460 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
461 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
462 { "hash_elements", KSTAT_DATA_UINT64 },
463 { "hash_elements_max", KSTAT_DATA_UINT64 },
464 { "hash_collisions", KSTAT_DATA_UINT64 },
465 { "hash_chains", KSTAT_DATA_UINT64 },
466 { "hash_chain_max", KSTAT_DATA_UINT64 },
467 { "p", KSTAT_DATA_UINT64 },
468 { "c", KSTAT_DATA_UINT64 },
469 { "c_min", KSTAT_DATA_UINT64 },
470 { "c_max", KSTAT_DATA_UINT64 },
471 { "size", KSTAT_DATA_UINT64 },
472 { "hdr_size", KSTAT_DATA_UINT64 },
473 { "data_size", KSTAT_DATA_UINT64 },
474 { "other_size", KSTAT_DATA_UINT64 },
475 { "l2_hits", KSTAT_DATA_UINT64 },
476 { "l2_misses", KSTAT_DATA_UINT64 },
477 { "l2_feeds", KSTAT_DATA_UINT64 },
478 { "l2_rw_clash", KSTAT_DATA_UINT64 },
479 { "l2_read_bytes", KSTAT_DATA_UINT64 },
480 { "l2_write_bytes", KSTAT_DATA_UINT64 },
481 { "l2_writes_sent", KSTAT_DATA_UINT64 },
482 { "l2_writes_done", KSTAT_DATA_UINT64 },
483 { "l2_writes_error", KSTAT_DATA_UINT64 },
484 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
485 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
486 { "l2_evict_reading", KSTAT_DATA_UINT64 },
487 { "l2_free_on_write", KSTAT_DATA_UINT64 },
488 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
489 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
490 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
491 { "l2_io_error", KSTAT_DATA_UINT64 },
492 { "l2_size", KSTAT_DATA_UINT64 },
493 { "l2_asize", KSTAT_DATA_UINT64 },
494 { "l2_hdr_size", KSTAT_DATA_UINT64 },
495 { "l2_compress_successes", KSTAT_DATA_UINT64 },
496 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
497 { "l2_compress_failures", KSTAT_DATA_UINT64 },
498 { "l2_write_trylock_fail", KSTAT_DATA_UINT64 },
499 { "l2_write_passed_headroom", KSTAT_DATA_UINT64 },
500 { "l2_write_spa_mismatch", KSTAT_DATA_UINT64 },
501 { "l2_write_in_l2", KSTAT_DATA_UINT64 },
502 { "l2_write_io_in_progress", KSTAT_DATA_UINT64 },
503 { "l2_write_not_cacheable", KSTAT_DATA_UINT64 },
504 { "l2_write_full", KSTAT_DATA_UINT64 },
505 { "l2_write_buffer_iter", KSTAT_DATA_UINT64 },
506 { "l2_write_pios", KSTAT_DATA_UINT64 },
507 { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
508 { "l2_write_buffer_list_iter", KSTAT_DATA_UINT64 },
509 { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
510 { "memory_throttle_count", KSTAT_DATA_UINT64 },
511 { "duplicate_buffers", KSTAT_DATA_UINT64 },
512 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
513 { "duplicate_reads", KSTAT_DATA_UINT64 },
514 { "arc_meta_used", KSTAT_DATA_UINT64 },
515 { "arc_meta_limit", KSTAT_DATA_UINT64 },
516 { "arc_meta_max", KSTAT_DATA_UINT64 },
517 { "arc_meta_min", KSTAT_DATA_UINT64 }
520 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
522 #define ARCSTAT_INCR(stat, val) \
523 atomic_add_64(&arc_stats.stat.value.ui64, (val))
525 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
526 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
528 #define ARCSTAT_MAX(stat, val) { \
530 while ((val) > (m = arc_stats.stat.value.ui64) && \
531 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
535 #define ARCSTAT_MAXSTAT(stat) \
536 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
539 * We define a macro to allow ARC hits/misses to be easily broken down by
540 * two separate conditions, giving a total of four different subtypes for
541 * each of hits and misses (so eight statistics total).
543 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
546 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
548 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
552 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
554 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
559 static arc_state_t *arc_anon;
560 static arc_state_t *arc_mru;
561 static arc_state_t *arc_mru_ghost;
562 static arc_state_t *arc_mfu;
563 static arc_state_t *arc_mfu_ghost;
564 static arc_state_t *arc_l2c_only;
567 * There are several ARC variables that are critical to export as kstats --
568 * but we don't want to have to grovel around in the kstat whenever we wish to
569 * manipulate them. For these variables, we therefore define them to be in
570 * terms of the statistic variable. This assures that we are not introducing
571 * the possibility of inconsistency by having shadow copies of the variables,
572 * while still allowing the code to be readable.
574 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
575 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
576 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
577 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
578 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
579 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
580 #define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
581 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
582 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
584 #define L2ARC_IS_VALID_COMPRESS(_c_) \
585 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
587 static int arc_no_grow; /* Don't try to grow cache size */
588 static uint64_t arc_tempreserve;
589 static uint64_t arc_loaned_bytes;
591 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
593 typedef struct arc_callback arc_callback_t;
595 struct arc_callback {
597 arc_done_func_t *acb_done;
599 zio_t *acb_zio_dummy;
600 arc_callback_t *acb_next;
603 typedef struct arc_write_callback arc_write_callback_t;
605 struct arc_write_callback {
607 arc_done_func_t *awcb_ready;
608 arc_done_func_t *awcb_physdone;
609 arc_done_func_t *awcb_done;
614 /* protected by hash lock */
619 kmutex_t b_freeze_lock;
620 zio_cksum_t *b_freeze_cksum;
623 arc_buf_hdr_t *b_hash_next;
628 arc_callback_t *b_acb;
632 arc_buf_contents_t b_type;
636 /* protected by arc state mutex */
637 arc_state_t *b_state;
638 list_node_t b_arc_node;
640 /* updated atomically */
641 clock_t b_arc_access;
643 /* self protecting */
646 l2arc_buf_hdr_t *b_l2hdr;
647 list_node_t b_l2node;
652 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
657 val = arc_meta_limit;
658 err = sysctl_handle_64(oidp, &val, 0, req);
659 if (err != 0 || req->newptr == NULL)
662 if (val <= 0 || val > arc_c_max)
665 arc_meta_limit = val;
670 static arc_buf_t *arc_eviction_list;
671 static kmutex_t arc_eviction_mtx;
672 static arc_buf_hdr_t arc_eviction_hdr;
674 #define GHOST_STATE(state) \
675 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
676 (state) == arc_l2c_only)
678 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
679 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
680 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
681 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
682 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
683 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
684 #define HDR_FREE_IN_PROGRESS(hdr) \
685 ((hdr)->b_flags & ARC_FLAG_FREE_IN_PROGRESS)
686 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
687 #define HDR_L2_READING(hdr) \
688 ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS && \
689 (hdr)->b_l2hdr != NULL)
690 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
691 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
692 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
698 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
699 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
702 * Hash table routines
705 #define HT_LOCK_PAD CACHE_LINE_SIZE
710 unsigned char pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
714 #define BUF_LOCKS 256
715 typedef struct buf_hash_table {
717 arc_buf_hdr_t **ht_table;
718 struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
721 static buf_hash_table_t buf_hash_table;
723 #define BUF_HASH_INDEX(spa, dva, birth) \
724 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
725 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
726 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
727 #define HDR_LOCK(hdr) \
728 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
730 uint64_t zfs_crc64_table[256];
736 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
737 #define L2ARC_HEADROOM 2 /* num of writes */
739 * If we discover during ARC scan any buffers to be compressed, we boost
740 * our headroom for the next scanning cycle by this percentage multiple.
742 #define L2ARC_HEADROOM_BOOST 200
743 #define L2ARC_FEED_SECS 1 /* caching interval secs */
744 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
746 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
747 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
749 /* L2ARC Performance Tunables */
750 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE; /* default max write size */
751 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra write during warmup */
752 uint64_t l2arc_headroom = L2ARC_HEADROOM; /* number of dev writes */
753 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
754 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
755 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
756 boolean_t l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
757 boolean_t l2arc_feed_again = B_TRUE; /* turbo warmup */
758 boolean_t l2arc_norw = B_TRUE; /* no reads during writes */
760 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
761 &l2arc_write_max, 0, "max write size");
762 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
763 &l2arc_write_boost, 0, "extra write during warmup");
764 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
765 &l2arc_headroom, 0, "number of dev writes");
766 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
767 &l2arc_feed_secs, 0, "interval seconds");
768 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
769 &l2arc_feed_min_ms, 0, "min interval milliseconds");
771 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
772 &l2arc_noprefetch, 0, "don't cache prefetch bufs");
773 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
774 &l2arc_feed_again, 0, "turbo warmup");
775 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
776 &l2arc_norw, 0, "no reads during writes");
778 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
779 &ARC_anon.arcs_size, 0, "size of anonymous state");
780 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
781 &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
782 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
783 &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
785 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
786 &ARC_mru.arcs_size, 0, "size of mru state");
787 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
788 &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
789 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
790 &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
792 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
793 &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
794 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
795 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
796 "size of metadata in mru ghost state");
797 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
798 &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
799 "size of data in mru ghost state");
801 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
802 &ARC_mfu.arcs_size, 0, "size of mfu state");
803 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
804 &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
805 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
806 &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
808 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
809 &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
810 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
811 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
812 "size of metadata in mfu ghost state");
813 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
814 &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
815 "size of data in mfu ghost state");
817 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
818 &ARC_l2c_only.arcs_size, 0, "size of mru state");
823 typedef struct l2arc_dev {
824 vdev_t *l2ad_vdev; /* vdev */
825 spa_t *l2ad_spa; /* spa */
826 uint64_t l2ad_hand; /* next write location */
827 uint64_t l2ad_start; /* first addr on device */
828 uint64_t l2ad_end; /* last addr on device */
829 uint64_t l2ad_evict; /* last addr eviction reached */
830 boolean_t l2ad_first; /* first sweep through */
831 boolean_t l2ad_writing; /* currently writing */
832 list_t *l2ad_buflist; /* buffer list */
833 list_node_t l2ad_node; /* device list node */
836 static list_t L2ARC_dev_list; /* device list */
837 static list_t *l2arc_dev_list; /* device list pointer */
838 static kmutex_t l2arc_dev_mtx; /* device list mutex */
839 static l2arc_dev_t *l2arc_dev_last; /* last device used */
840 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
841 static list_t L2ARC_free_on_write; /* free after write buf list */
842 static list_t *l2arc_free_on_write; /* free after write list ptr */
843 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
844 static uint64_t l2arc_ndev; /* number of devices */
846 typedef struct l2arc_read_callback {
847 arc_buf_t *l2rcb_buf; /* read buffer */
848 spa_t *l2rcb_spa; /* spa */
849 blkptr_t l2rcb_bp; /* original blkptr */
850 zbookmark_phys_t l2rcb_zb; /* original bookmark */
851 int l2rcb_flags; /* original flags */
852 enum zio_compress l2rcb_compress; /* applied compress */
853 } l2arc_read_callback_t;
855 typedef struct l2arc_write_callback {
856 l2arc_dev_t *l2wcb_dev; /* device info */
857 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
858 } l2arc_write_callback_t;
860 struct l2arc_buf_hdr {
861 /* protected by arc_buf_hdr mutex */
862 l2arc_dev_t *b_dev; /* L2ARC device */
863 uint64_t b_daddr; /* disk address, offset byte */
864 /* compression applied to buffer data */
865 enum zio_compress b_compress;
866 /* real alloc'd buffer size depending on b_compress applied */
868 /* temporary buffer holder for in-flight compressed data */
872 typedef struct l2arc_data_free {
873 /* protected by l2arc_free_on_write_mtx */
876 void (*l2df_func)(void *, size_t);
877 list_node_t l2df_list_node;
880 static kmutex_t l2arc_feed_thr_lock;
881 static kcondvar_t l2arc_feed_thr_cv;
882 static uint8_t l2arc_thread_exit;
884 static void arc_get_data_buf(arc_buf_t *);
885 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
886 static int arc_evict_needed(arc_buf_contents_t);
887 static void arc_evict_ghost(arc_state_t *, uint64_t, int64_t);
888 static void arc_buf_watch(arc_buf_t *);
890 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
891 static void l2arc_read_done(zio_t *);
892 static void l2arc_hdr_stat_add(void);
893 static void l2arc_hdr_stat_remove(void);
895 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *);
896 static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
897 static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
900 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
902 uint8_t *vdva = (uint8_t *)dva;
903 uint64_t crc = -1ULL;
906 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
908 for (i = 0; i < sizeof (dva_t); i++)
909 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
911 crc ^= (spa>>8) ^ birth;
916 #define BUF_EMPTY(buf) \
917 ((buf)->b_dva.dva_word[0] == 0 && \
918 (buf)->b_dva.dva_word[1] == 0 && \
919 (buf)->b_cksum0 == 0)
921 #define BUF_EQUAL(spa, dva, birth, buf) \
922 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
923 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
924 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
927 buf_discard_identity(arc_buf_hdr_t *hdr)
929 hdr->b_dva.dva_word[0] = 0;
930 hdr->b_dva.dva_word[1] = 0;
935 static arc_buf_hdr_t *
936 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
938 const dva_t *dva = BP_IDENTITY(bp);
939 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
940 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
941 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
944 mutex_enter(hash_lock);
945 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
946 hdr = hdr->b_hash_next) {
947 if (BUF_EQUAL(spa, dva, birth, hdr)) {
952 mutex_exit(hash_lock);
958 * Insert an entry into the hash table. If there is already an element
959 * equal to elem in the hash table, then the already existing element
960 * will be returned and the new element will not be inserted.
961 * Otherwise returns NULL.
963 static arc_buf_hdr_t *
964 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
966 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
967 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
971 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
972 ASSERT(hdr->b_birth != 0);
973 ASSERT(!HDR_IN_HASH_TABLE(hdr));
975 mutex_enter(hash_lock);
976 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
977 fhdr = fhdr->b_hash_next, i++) {
978 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
982 hdr->b_hash_next = buf_hash_table.ht_table[idx];
983 buf_hash_table.ht_table[idx] = hdr;
984 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
986 /* collect some hash table performance data */
988 ARCSTAT_BUMP(arcstat_hash_collisions);
990 ARCSTAT_BUMP(arcstat_hash_chains);
992 ARCSTAT_MAX(arcstat_hash_chain_max, i);
995 ARCSTAT_BUMP(arcstat_hash_elements);
996 ARCSTAT_MAXSTAT(arcstat_hash_elements);
1002 buf_hash_remove(arc_buf_hdr_t *hdr)
1004 arc_buf_hdr_t *fhdr, **hdrp;
1005 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1007 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1008 ASSERT(HDR_IN_HASH_TABLE(hdr));
1010 hdrp = &buf_hash_table.ht_table[idx];
1011 while ((fhdr = *hdrp) != hdr) {
1012 ASSERT(fhdr != NULL);
1013 hdrp = &fhdr->b_hash_next;
1015 *hdrp = hdr->b_hash_next;
1016 hdr->b_hash_next = NULL;
1017 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1019 /* collect some hash table performance data */
1020 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1022 if (buf_hash_table.ht_table[idx] &&
1023 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1024 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1028 * Global data structures and functions for the buf kmem cache.
1030 static kmem_cache_t *hdr_cache;
1031 static kmem_cache_t *buf_cache;
1038 kmem_free(buf_hash_table.ht_table,
1039 (buf_hash_table.ht_mask + 1) * sizeof (void *));
1040 for (i = 0; i < BUF_LOCKS; i++)
1041 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1042 kmem_cache_destroy(hdr_cache);
1043 kmem_cache_destroy(buf_cache);
1047 * Constructor callback - called when the cache is empty
1048 * and a new buf is requested.
1052 hdr_cons(void *vbuf, void *unused, int kmflag)
1054 arc_buf_hdr_t *hdr = vbuf;
1056 bzero(hdr, sizeof (arc_buf_hdr_t));
1057 refcount_create(&hdr->b_refcnt);
1058 cv_init(&hdr->b_cv, NULL, CV_DEFAULT, NULL);
1059 mutex_init(&hdr->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1060 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1067 buf_cons(void *vbuf, void *unused, int kmflag)
1069 arc_buf_t *buf = vbuf;
1071 bzero(buf, sizeof (arc_buf_t));
1072 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1073 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1079 * Destructor callback - called when a cached buf is
1080 * no longer required.
1084 hdr_dest(void *vbuf, void *unused)
1086 arc_buf_hdr_t *hdr = vbuf;
1088 ASSERT(BUF_EMPTY(hdr));
1089 refcount_destroy(&hdr->b_refcnt);
1090 cv_destroy(&hdr->b_cv);
1091 mutex_destroy(&hdr->b_freeze_lock);
1092 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
1097 buf_dest(void *vbuf, void *unused)
1099 arc_buf_t *buf = vbuf;
1101 mutex_destroy(&buf->b_evict_lock);
1102 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1106 * Reclaim callback -- invoked when memory is low.
1110 hdr_recl(void *unused)
1112 dprintf("hdr_recl called\n");
1114 * umem calls the reclaim func when we destroy the buf cache,
1115 * which is after we do arc_fini().
1118 cv_signal(&arc_reclaim_thr_cv);
1125 uint64_t hsize = 1ULL << 12;
1129 * The hash table is big enough to fill all of physical memory
1130 * with an average block size of zfs_arc_average_blocksize (default 8K).
1131 * By default, the table will take up
1132 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1134 while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1137 buf_hash_table.ht_mask = hsize - 1;
1138 buf_hash_table.ht_table =
1139 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1140 if (buf_hash_table.ht_table == NULL) {
1141 ASSERT(hsize > (1ULL << 8));
1146 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1147 0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
1148 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1149 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1151 for (i = 0; i < 256; i++)
1152 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1153 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1155 for (i = 0; i < BUF_LOCKS; i++) {
1156 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1157 NULL, MUTEX_DEFAULT, NULL);
1161 #define ARC_MINTIME (hz>>4) /* 62 ms */
1164 arc_cksum_verify(arc_buf_t *buf)
1168 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1171 mutex_enter(&buf->b_hdr->b_freeze_lock);
1172 if (buf->b_hdr->b_freeze_cksum == NULL ||
1173 (buf->b_hdr->b_flags & ARC_FLAG_IO_ERROR)) {
1174 mutex_exit(&buf->b_hdr->b_freeze_lock);
1177 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1178 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1179 panic("buffer modified while frozen!");
1180 mutex_exit(&buf->b_hdr->b_freeze_lock);
1184 arc_cksum_equal(arc_buf_t *buf)
1189 mutex_enter(&buf->b_hdr->b_freeze_lock);
1190 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1191 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1192 mutex_exit(&buf->b_hdr->b_freeze_lock);
1198 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1200 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1203 mutex_enter(&buf->b_hdr->b_freeze_lock);
1204 if (buf->b_hdr->b_freeze_cksum != NULL) {
1205 mutex_exit(&buf->b_hdr->b_freeze_lock);
1208 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1209 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1210 buf->b_hdr->b_freeze_cksum);
1211 mutex_exit(&buf->b_hdr->b_freeze_lock);
1214 #endif /* illumos */
1219 typedef struct procctl {
1227 arc_buf_unwatch(arc_buf_t *buf)
1234 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1235 ctl.prwatch.pr_size = 0;
1236 ctl.prwatch.pr_wflags = 0;
1237 result = write(arc_procfd, &ctl, sizeof (ctl));
1238 ASSERT3U(result, ==, sizeof (ctl));
1245 arc_buf_watch(arc_buf_t *buf)
1252 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1253 ctl.prwatch.pr_size = buf->b_hdr->b_size;
1254 ctl.prwatch.pr_wflags = WA_WRITE;
1255 result = write(arc_procfd, &ctl, sizeof (ctl));
1256 ASSERT3U(result, ==, sizeof (ctl));
1260 #endif /* illumos */
1263 arc_buf_thaw(arc_buf_t *buf)
1265 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1266 if (buf->b_hdr->b_state != arc_anon)
1267 panic("modifying non-anon buffer!");
1268 if (buf->b_hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1269 panic("modifying buffer while i/o in progress!");
1270 arc_cksum_verify(buf);
1273 mutex_enter(&buf->b_hdr->b_freeze_lock);
1274 if (buf->b_hdr->b_freeze_cksum != NULL) {
1275 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1276 buf->b_hdr->b_freeze_cksum = NULL;
1279 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1280 if (buf->b_hdr->b_thawed)
1281 kmem_free(buf->b_hdr->b_thawed, 1);
1282 buf->b_hdr->b_thawed = kmem_alloc(1, KM_SLEEP);
1285 mutex_exit(&buf->b_hdr->b_freeze_lock);
1288 arc_buf_unwatch(buf);
1289 #endif /* illumos */
1293 arc_buf_freeze(arc_buf_t *buf)
1295 kmutex_t *hash_lock;
1297 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1300 hash_lock = HDR_LOCK(buf->b_hdr);
1301 mutex_enter(hash_lock);
1303 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1304 buf->b_hdr->b_state == arc_anon);
1305 arc_cksum_compute(buf, B_FALSE);
1306 mutex_exit(hash_lock);
1311 get_buf_info(arc_buf_hdr_t *hdr, arc_state_t *state, list_t **list, kmutex_t **lock)
1313 uint64_t buf_hashid = buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1315 if (hdr->b_type == ARC_BUFC_METADATA)
1316 buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1318 buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1319 buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1322 *list = &state->arcs_lists[buf_hashid];
1323 *lock = ARCS_LOCK(state, buf_hashid);
1328 add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1330 ASSERT(MUTEX_HELD(hash_lock));
1332 if ((refcount_add(&hdr->b_refcnt, tag) == 1) &&
1333 (hdr->b_state != arc_anon)) {
1334 uint64_t delta = hdr->b_size * hdr->b_datacnt;
1335 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
1339 get_buf_info(hdr, hdr->b_state, &list, &lock);
1340 ASSERT(!MUTEX_HELD(lock));
1342 ASSERT(list_link_active(&hdr->b_arc_node));
1343 list_remove(list, hdr);
1344 if (GHOST_STATE(hdr->b_state)) {
1345 ASSERT0(hdr->b_datacnt);
1346 ASSERT3P(hdr->b_buf, ==, NULL);
1347 delta = hdr->b_size;
1350 ASSERT3U(*size, >=, delta);
1351 atomic_add_64(size, -delta);
1353 /* remove the prefetch flag if we get a reference */
1354 if (hdr->b_flags & ARC_FLAG_PREFETCH)
1355 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1360 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1363 arc_state_t *state = hdr->b_state;
1365 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1366 ASSERT(!GHOST_STATE(state));
1368 if (((cnt = refcount_remove(&hdr->b_refcnt, tag)) == 0) &&
1369 (state != arc_anon)) {
1370 uint64_t *size = &state->arcs_lsize[hdr->b_type];
1374 get_buf_info(hdr, state, &list, &lock);
1375 ASSERT(!MUTEX_HELD(lock));
1377 ASSERT(!list_link_active(&hdr->b_arc_node));
1378 list_insert_head(list, hdr);
1379 ASSERT(hdr->b_datacnt > 0);
1380 atomic_add_64(size, hdr->b_size * hdr->b_datacnt);
1387 * Move the supplied buffer to the indicated state. The mutex
1388 * for the buffer must be held by the caller.
1391 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1392 kmutex_t *hash_lock)
1394 arc_state_t *old_state = hdr->b_state;
1395 int64_t refcnt = refcount_count(&hdr->b_refcnt);
1396 uint64_t from_delta, to_delta;
1400 ASSERT(MUTEX_HELD(hash_lock));
1401 ASSERT3P(new_state, !=, old_state);
1402 ASSERT(refcnt == 0 || hdr->b_datacnt > 0);
1403 ASSERT(hdr->b_datacnt == 0 || !GHOST_STATE(new_state));
1404 ASSERT(hdr->b_datacnt <= 1 || old_state != arc_anon);
1406 from_delta = to_delta = hdr->b_datacnt * hdr->b_size;
1409 * If this buffer is evictable, transfer it from the
1410 * old state list to the new state list.
1413 if (old_state != arc_anon) {
1415 uint64_t *size = &old_state->arcs_lsize[hdr->b_type];
1417 get_buf_info(hdr, old_state, &list, &lock);
1418 use_mutex = !MUTEX_HELD(lock);
1422 ASSERT(list_link_active(&hdr->b_arc_node));
1423 list_remove(list, hdr);
1426 * If prefetching out of the ghost cache,
1427 * we will have a non-zero datacnt.
1429 if (GHOST_STATE(old_state) && hdr->b_datacnt == 0) {
1430 /* ghost elements have a ghost size */
1431 ASSERT(hdr->b_buf == NULL);
1432 from_delta = hdr->b_size;
1434 ASSERT3U(*size, >=, from_delta);
1435 atomic_add_64(size, -from_delta);
1440 if (new_state != arc_anon) {
1442 uint64_t *size = &new_state->arcs_lsize[hdr->b_type];
1444 get_buf_info(hdr, new_state, &list, &lock);
1445 use_mutex = !MUTEX_HELD(lock);
1449 list_insert_head(list, hdr);
1451 /* ghost elements have a ghost size */
1452 if (GHOST_STATE(new_state)) {
1453 ASSERT(hdr->b_datacnt == 0);
1454 ASSERT(hdr->b_buf == NULL);
1455 to_delta = hdr->b_size;
1457 atomic_add_64(size, to_delta);
1464 ASSERT(!BUF_EMPTY(hdr));
1465 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1466 buf_hash_remove(hdr);
1468 /* adjust state sizes */
1470 atomic_add_64(&new_state->arcs_size, to_delta);
1472 ASSERT3U(old_state->arcs_size, >=, from_delta);
1473 atomic_add_64(&old_state->arcs_size, -from_delta);
1475 hdr->b_state = new_state;
1477 /* adjust l2arc hdr stats */
1478 if (new_state == arc_l2c_only)
1479 l2arc_hdr_stat_add();
1480 else if (old_state == arc_l2c_only)
1481 l2arc_hdr_stat_remove();
1485 arc_space_consume(uint64_t space, arc_space_type_t type)
1487 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1490 case ARC_SPACE_DATA:
1491 ARCSTAT_INCR(arcstat_data_size, space);
1493 case ARC_SPACE_OTHER:
1494 ARCSTAT_INCR(arcstat_other_size, space);
1496 case ARC_SPACE_HDRS:
1497 ARCSTAT_INCR(arcstat_hdr_size, space);
1499 case ARC_SPACE_L2HDRS:
1500 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1504 ARCSTAT_INCR(arcstat_meta_used, space);
1505 atomic_add_64(&arc_size, space);
1509 arc_space_return(uint64_t space, arc_space_type_t type)
1511 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1514 case ARC_SPACE_DATA:
1515 ARCSTAT_INCR(arcstat_data_size, -space);
1517 case ARC_SPACE_OTHER:
1518 ARCSTAT_INCR(arcstat_other_size, -space);
1520 case ARC_SPACE_HDRS:
1521 ARCSTAT_INCR(arcstat_hdr_size, -space);
1523 case ARC_SPACE_L2HDRS:
1524 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1528 ASSERT(arc_meta_used >= space);
1529 if (arc_meta_max < arc_meta_used)
1530 arc_meta_max = arc_meta_used;
1531 ARCSTAT_INCR(arcstat_meta_used, -space);
1532 ASSERT(arc_size >= space);
1533 atomic_add_64(&arc_size, -space);
1537 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1542 ASSERT3U(size, >, 0);
1543 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1544 ASSERT(BUF_EMPTY(hdr));
1547 hdr->b_spa = spa_load_guid(spa);
1548 hdr->b_state = arc_anon;
1549 hdr->b_arc_access = 0;
1550 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1553 buf->b_efunc = NULL;
1554 buf->b_private = NULL;
1557 arc_get_data_buf(buf);
1560 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1561 (void) refcount_add(&hdr->b_refcnt, tag);
1566 static char *arc_onloan_tag = "onloan";
1569 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1570 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1571 * buffers must be returned to the arc before they can be used by the DMU or
1575 arc_loan_buf(spa_t *spa, int size)
1579 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1581 atomic_add_64(&arc_loaned_bytes, size);
1586 * Return a loaned arc buffer to the arc.
1589 arc_return_buf(arc_buf_t *buf, void *tag)
1591 arc_buf_hdr_t *hdr = buf->b_hdr;
1593 ASSERT(buf->b_data != NULL);
1594 (void) refcount_add(&hdr->b_refcnt, tag);
1595 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1597 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1600 /* Detach an arc_buf from a dbuf (tag) */
1602 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1606 ASSERT(buf->b_data != NULL);
1608 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1609 (void) refcount_remove(&hdr->b_refcnt, tag);
1610 buf->b_efunc = NULL;
1611 buf->b_private = NULL;
1613 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1617 arc_buf_clone(arc_buf_t *from)
1620 arc_buf_hdr_t *hdr = from->b_hdr;
1621 uint64_t size = hdr->b_size;
1623 ASSERT(hdr->b_state != arc_anon);
1625 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1628 buf->b_efunc = NULL;
1629 buf->b_private = NULL;
1630 buf->b_next = hdr->b_buf;
1632 arc_get_data_buf(buf);
1633 bcopy(from->b_data, buf->b_data, size);
1636 * This buffer already exists in the arc so create a duplicate
1637 * copy for the caller. If the buffer is associated with user data
1638 * then track the size and number of duplicates. These stats will be
1639 * updated as duplicate buffers are created and destroyed.
1641 if (hdr->b_type == ARC_BUFC_DATA) {
1642 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1643 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1645 hdr->b_datacnt += 1;
1650 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1653 kmutex_t *hash_lock;
1656 * Check to see if this buffer is evicted. Callers
1657 * must verify b_data != NULL to know if the add_ref
1660 mutex_enter(&buf->b_evict_lock);
1661 if (buf->b_data == NULL) {
1662 mutex_exit(&buf->b_evict_lock);
1665 hash_lock = HDR_LOCK(buf->b_hdr);
1666 mutex_enter(hash_lock);
1668 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1669 mutex_exit(&buf->b_evict_lock);
1671 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1672 add_reference(hdr, hash_lock, tag);
1673 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1674 arc_access(hdr, hash_lock);
1675 mutex_exit(hash_lock);
1676 ARCSTAT_BUMP(arcstat_hits);
1677 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
1678 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1679 data, metadata, hits);
1683 arc_buf_free_on_write(void *data, size_t size,
1684 void (*free_func)(void *, size_t))
1686 l2arc_data_free_t *df;
1688 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1689 df->l2df_data = data;
1690 df->l2df_size = size;
1691 df->l2df_func = free_func;
1692 mutex_enter(&l2arc_free_on_write_mtx);
1693 list_insert_head(l2arc_free_on_write, df);
1694 mutex_exit(&l2arc_free_on_write_mtx);
1698 * Free the arc data buffer. If it is an l2arc write in progress,
1699 * the buffer is placed on l2arc_free_on_write to be freed later.
1702 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1704 arc_buf_hdr_t *hdr = buf->b_hdr;
1706 if (HDR_L2_WRITING(hdr)) {
1707 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
1708 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1710 free_func(buf->b_data, hdr->b_size);
1715 * Free up buf->b_data and if 'remove' is set, then pull the
1716 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1719 arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1721 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1723 ASSERT(MUTEX_HELD(&l2arc_buflist_mtx));
1725 if (l2hdr->b_tmp_cdata == NULL)
1728 ASSERT(HDR_L2_WRITING(hdr));
1729 arc_buf_free_on_write(l2hdr->b_tmp_cdata, hdr->b_size,
1731 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1732 l2hdr->b_tmp_cdata = NULL;
1736 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
1740 /* free up data associated with the buf */
1742 arc_state_t *state = buf->b_hdr->b_state;
1743 uint64_t size = buf->b_hdr->b_size;
1744 arc_buf_contents_t type = buf->b_hdr->b_type;
1746 arc_cksum_verify(buf);
1748 arc_buf_unwatch(buf);
1749 #endif /* illumos */
1752 if (type == ARC_BUFC_METADATA) {
1753 arc_buf_data_free(buf, zio_buf_free);
1754 arc_space_return(size, ARC_SPACE_DATA);
1756 ASSERT(type == ARC_BUFC_DATA);
1757 arc_buf_data_free(buf, zio_data_buf_free);
1758 ARCSTAT_INCR(arcstat_data_size, -size);
1759 atomic_add_64(&arc_size, -size);
1762 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1763 uint64_t *cnt = &state->arcs_lsize[type];
1765 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1766 ASSERT(state != arc_anon);
1768 ASSERT3U(*cnt, >=, size);
1769 atomic_add_64(cnt, -size);
1771 ASSERT3U(state->arcs_size, >=, size);
1772 atomic_add_64(&state->arcs_size, -size);
1776 * If we're destroying a duplicate buffer make sure
1777 * that the appropriate statistics are updated.
1779 if (buf->b_hdr->b_datacnt > 1 &&
1780 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1781 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1782 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1784 ASSERT(buf->b_hdr->b_datacnt > 0);
1785 buf->b_hdr->b_datacnt -= 1;
1788 /* only remove the buf if requested */
1792 /* remove the buf from the hdr list */
1793 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1795 *bufp = buf->b_next;
1798 ASSERT(buf->b_efunc == NULL);
1800 /* clean up the buf */
1802 kmem_cache_free(buf_cache, buf);
1806 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1808 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1809 ASSERT3P(hdr->b_state, ==, arc_anon);
1810 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1811 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1813 if (l2hdr != NULL) {
1814 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1816 * To prevent arc_free() and l2arc_evict() from
1817 * attempting to free the same buffer at the same time,
1818 * a FREE_IN_PROGRESS flag is given to arc_free() to
1819 * give it priority. l2arc_evict() can't destroy this
1820 * header while we are waiting on l2arc_buflist_mtx.
1822 * The hdr may be removed from l2ad_buflist before we
1823 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1825 if (!buflist_held) {
1826 mutex_enter(&l2arc_buflist_mtx);
1827 l2hdr = hdr->b_l2hdr;
1830 if (l2hdr != NULL) {
1831 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
1833 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1834 arc_buf_l2_cdata_free(hdr);
1835 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1836 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1837 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
1838 -l2hdr->b_asize, 0, 0);
1839 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1840 if (hdr->b_state == arc_l2c_only)
1841 l2arc_hdr_stat_remove();
1842 hdr->b_l2hdr = NULL;
1846 mutex_exit(&l2arc_buflist_mtx);
1849 if (!BUF_EMPTY(hdr)) {
1850 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1851 buf_discard_identity(hdr);
1853 while (hdr->b_buf) {
1854 arc_buf_t *buf = hdr->b_buf;
1857 mutex_enter(&arc_eviction_mtx);
1858 mutex_enter(&buf->b_evict_lock);
1859 ASSERT(buf->b_hdr != NULL);
1860 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1861 hdr->b_buf = buf->b_next;
1862 buf->b_hdr = &arc_eviction_hdr;
1863 buf->b_next = arc_eviction_list;
1864 arc_eviction_list = buf;
1865 mutex_exit(&buf->b_evict_lock);
1866 mutex_exit(&arc_eviction_mtx);
1868 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1871 if (hdr->b_freeze_cksum != NULL) {
1872 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1873 hdr->b_freeze_cksum = NULL;
1875 if (hdr->b_thawed) {
1876 kmem_free(hdr->b_thawed, 1);
1877 hdr->b_thawed = NULL;
1880 ASSERT(!list_link_active(&hdr->b_arc_node));
1881 ASSERT3P(hdr->b_hash_next, ==, NULL);
1882 ASSERT3P(hdr->b_acb, ==, NULL);
1883 kmem_cache_free(hdr_cache, hdr);
1887 arc_buf_free(arc_buf_t *buf, void *tag)
1889 arc_buf_hdr_t *hdr = buf->b_hdr;
1890 int hashed = hdr->b_state != arc_anon;
1892 ASSERT(buf->b_efunc == NULL);
1893 ASSERT(buf->b_data != NULL);
1896 kmutex_t *hash_lock = HDR_LOCK(hdr);
1898 mutex_enter(hash_lock);
1900 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1902 (void) remove_reference(hdr, hash_lock, tag);
1903 if (hdr->b_datacnt > 1) {
1904 arc_buf_destroy(buf, FALSE, TRUE);
1906 ASSERT(buf == hdr->b_buf);
1907 ASSERT(buf->b_efunc == NULL);
1908 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1910 mutex_exit(hash_lock);
1911 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1914 * We are in the middle of an async write. Don't destroy
1915 * this buffer unless the write completes before we finish
1916 * decrementing the reference count.
1918 mutex_enter(&arc_eviction_mtx);
1919 (void) remove_reference(hdr, NULL, tag);
1920 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1921 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1922 mutex_exit(&arc_eviction_mtx);
1924 arc_hdr_destroy(hdr);
1926 if (remove_reference(hdr, NULL, tag) > 0)
1927 arc_buf_destroy(buf, FALSE, TRUE);
1929 arc_hdr_destroy(hdr);
1934 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1936 arc_buf_hdr_t *hdr = buf->b_hdr;
1937 kmutex_t *hash_lock = HDR_LOCK(hdr);
1938 boolean_t no_callback = (buf->b_efunc == NULL);
1940 if (hdr->b_state == arc_anon) {
1941 ASSERT(hdr->b_datacnt == 1);
1942 arc_buf_free(buf, tag);
1943 return (no_callback);
1946 mutex_enter(hash_lock);
1948 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1949 ASSERT(hdr->b_state != arc_anon);
1950 ASSERT(buf->b_data != NULL);
1952 (void) remove_reference(hdr, hash_lock, tag);
1953 if (hdr->b_datacnt > 1) {
1955 arc_buf_destroy(buf, FALSE, TRUE);
1956 } else if (no_callback) {
1957 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1958 ASSERT(buf->b_efunc == NULL);
1959 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
1961 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1962 refcount_is_zero(&hdr->b_refcnt));
1963 mutex_exit(hash_lock);
1964 return (no_callback);
1968 arc_buf_size(arc_buf_t *buf)
1970 return (buf->b_hdr->b_size);
1974 * Called from the DMU to determine if the current buffer should be
1975 * evicted. In order to ensure proper locking, the eviction must be initiated
1976 * from the DMU. Return true if the buffer is associated with user data and
1977 * duplicate buffers still exist.
1980 arc_buf_eviction_needed(arc_buf_t *buf)
1983 boolean_t evict_needed = B_FALSE;
1985 if (zfs_disable_dup_eviction)
1988 mutex_enter(&buf->b_evict_lock);
1992 * We are in arc_do_user_evicts(); let that function
1993 * perform the eviction.
1995 ASSERT(buf->b_data == NULL);
1996 mutex_exit(&buf->b_evict_lock);
1998 } else if (buf->b_data == NULL) {
2000 * We have already been added to the arc eviction list;
2001 * recommend eviction.
2003 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2004 mutex_exit(&buf->b_evict_lock);
2008 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
2009 evict_needed = B_TRUE;
2011 mutex_exit(&buf->b_evict_lock);
2012 return (evict_needed);
2016 * Evict buffers from list until we've removed the specified number of
2017 * bytes. Move the removed buffers to the appropriate evict state.
2018 * If the recycle flag is set, then attempt to "recycle" a buffer:
2019 * - look for a buffer to evict that is `bytes' long.
2020 * - return the data block from this buffer rather than freeing it.
2021 * This flag is used by callers that are trying to make space for a
2022 * new buffer in a full arc cache.
2024 * This function makes a "best effort". It skips over any buffers
2025 * it can't get a hash_lock on, and so may not catch all candidates.
2026 * It may also return without evicting as much space as requested.
2029 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
2030 arc_buf_contents_t type)
2032 arc_state_t *evicted_state;
2033 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
2034 int64_t bytes_remaining;
2035 arc_buf_hdr_t *hdr, *hdr_prev = NULL;
2036 list_t *evicted_list, *list, *evicted_list_start, *list_start;
2037 kmutex_t *lock, *evicted_lock;
2038 kmutex_t *hash_lock;
2039 boolean_t have_lock;
2040 void *stolen = NULL;
2041 arc_buf_hdr_t marker = { 0 };
2043 static int evict_metadata_offset, evict_data_offset;
2044 int i, idx, offset, list_count, lists;
2046 ASSERT(state == arc_mru || state == arc_mfu);
2048 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2051 * Decide which "type" (data vs metadata) to recycle from.
2053 * If we are over the metadata limit, recycle from metadata.
2054 * If we are under the metadata minimum, recycle from data.
2055 * Otherwise, recycle from whichever type has the oldest (least
2056 * recently accessed) header. This is not yet implemented.
2059 arc_buf_contents_t realtype;
2060 if (state->arcs_lsize[ARC_BUFC_DATA] == 0) {
2061 realtype = ARC_BUFC_METADATA;
2062 } else if (state->arcs_lsize[ARC_BUFC_METADATA] == 0) {
2063 realtype = ARC_BUFC_DATA;
2064 } else if (arc_meta_used >= arc_meta_limit) {
2065 realtype = ARC_BUFC_METADATA;
2066 } else if (arc_meta_used <= arc_meta_min) {
2067 realtype = ARC_BUFC_DATA;
2070 if (data_hdr->b_arc_access <
2071 metadata_hdr->b_arc_access) {
2072 realtype = ARC_BUFC_DATA;
2074 realtype = ARC_BUFC_METADATA;
2081 if (realtype != type) {
2083 * If we want to evict from a different list,
2084 * we can not recycle, because DATA vs METADATA
2085 * buffers are segregated into different kmem
2086 * caches (and vmem arenas).
2093 if (type == ARC_BUFC_METADATA) {
2095 list_count = ARC_BUFC_NUMMETADATALISTS;
2096 list_start = &state->arcs_lists[0];
2097 evicted_list_start = &evicted_state->arcs_lists[0];
2098 idx = evict_metadata_offset;
2100 offset = ARC_BUFC_NUMMETADATALISTS;
2101 list_start = &state->arcs_lists[offset];
2102 evicted_list_start = &evicted_state->arcs_lists[offset];
2103 list_count = ARC_BUFC_NUMDATALISTS;
2104 idx = evict_data_offset;
2106 bytes_remaining = evicted_state->arcs_lsize[type];
2110 list = &list_start[idx];
2111 evicted_list = &evicted_list_start[idx];
2112 lock = ARCS_LOCK(state, (offset + idx));
2113 evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
2116 mutex_enter(evicted_lock);
2118 for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2119 hdr_prev = list_prev(list, hdr);
2120 bytes_remaining -= (hdr->b_size * hdr->b_datacnt);
2121 /* prefetch buffers have a minimum lifespan */
2122 if (HDR_IO_IN_PROGRESS(hdr) ||
2123 (spa && hdr->b_spa != spa) ||
2124 (hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT) &&
2125 ddi_get_lbolt() - hdr->b_arc_access <
2126 arc_min_prefetch_lifespan)) {
2130 /* "lookahead" for better eviction candidate */
2131 if (recycle && hdr->b_size != bytes &&
2132 hdr_prev && hdr_prev->b_size == bytes)
2135 /* ignore markers */
2136 if (hdr->b_spa == 0)
2140 * It may take a long time to evict all the bufs requested.
2141 * To avoid blocking all arc activity, periodically drop
2142 * the arcs_mtx and give other threads a chance to run
2143 * before reacquiring the lock.
2145 * If we are looking for a buffer to recycle, we are in
2146 * the hot code path, so don't sleep.
2148 if (!recycle && count++ > arc_evict_iterations) {
2149 list_insert_after(list, hdr, &marker);
2150 mutex_exit(evicted_lock);
2152 kpreempt(KPREEMPT_SYNC);
2154 mutex_enter(evicted_lock);
2155 hdr_prev = list_prev(list, &marker);
2156 list_remove(list, &marker);
2161 hash_lock = HDR_LOCK(hdr);
2162 have_lock = MUTEX_HELD(hash_lock);
2163 if (have_lock || mutex_tryenter(hash_lock)) {
2164 ASSERT0(refcount_count(&hdr->b_refcnt));
2165 ASSERT(hdr->b_datacnt > 0);
2166 while (hdr->b_buf) {
2167 arc_buf_t *buf = hdr->b_buf;
2168 if (!mutex_tryenter(&buf->b_evict_lock)) {
2173 bytes_evicted += hdr->b_size;
2174 if (recycle && hdr->b_type == type &&
2175 hdr->b_size == bytes &&
2176 !HDR_L2_WRITING(hdr)) {
2177 stolen = buf->b_data;
2182 mutex_enter(&arc_eviction_mtx);
2183 arc_buf_destroy(buf,
2184 buf->b_data == stolen, FALSE);
2185 hdr->b_buf = buf->b_next;
2186 buf->b_hdr = &arc_eviction_hdr;
2187 buf->b_next = arc_eviction_list;
2188 arc_eviction_list = buf;
2189 mutex_exit(&arc_eviction_mtx);
2190 mutex_exit(&buf->b_evict_lock);
2192 mutex_exit(&buf->b_evict_lock);
2193 arc_buf_destroy(buf,
2194 buf->b_data == stolen, TRUE);
2199 ARCSTAT_INCR(arcstat_evict_l2_cached,
2202 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
2203 ARCSTAT_INCR(arcstat_evict_l2_eligible,
2207 arcstat_evict_l2_ineligible,
2212 if (hdr->b_datacnt == 0) {
2213 arc_change_state(evicted_state, hdr, hash_lock);
2214 ASSERT(HDR_IN_HASH_TABLE(hdr));
2215 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2216 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2217 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2220 mutex_exit(hash_lock);
2221 if (bytes >= 0 && bytes_evicted >= bytes)
2223 if (bytes_remaining > 0) {
2224 mutex_exit(evicted_lock);
2226 idx = ((idx + 1) & (list_count - 1));
2235 mutex_exit(evicted_lock);
2238 idx = ((idx + 1) & (list_count - 1));
2241 if (bytes_evicted < bytes) {
2242 if (lists < list_count)
2245 dprintf("only evicted %lld bytes from %x",
2246 (longlong_t)bytes_evicted, state);
2248 if (type == ARC_BUFC_METADATA)
2249 evict_metadata_offset = idx;
2251 evict_data_offset = idx;
2254 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2257 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2260 * Note: we have just evicted some data into the ghost state,
2261 * potentially putting the ghost size over the desired size. Rather
2262 * that evicting from the ghost list in this hot code path, leave
2263 * this chore to the arc_reclaim_thread().
2267 ARCSTAT_BUMP(arcstat_stolen);
2272 * Remove buffers from list until we've removed the specified number of
2273 * bytes. Destroy the buffers that are removed.
2276 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2278 arc_buf_hdr_t *hdr, *hdr_prev;
2279 arc_buf_hdr_t marker = { 0 };
2280 list_t *list, *list_start;
2281 kmutex_t *hash_lock, *lock;
2282 uint64_t bytes_deleted = 0;
2283 uint64_t bufs_skipped = 0;
2285 static int evict_offset;
2286 int list_count, idx = evict_offset;
2287 int offset, lists = 0;
2289 ASSERT(GHOST_STATE(state));
2292 * data lists come after metadata lists
2294 list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2295 list_count = ARC_BUFC_NUMDATALISTS;
2296 offset = ARC_BUFC_NUMMETADATALISTS;
2299 list = &list_start[idx];
2300 lock = ARCS_LOCK(state, idx + offset);
2303 for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2304 hdr_prev = list_prev(list, hdr);
2305 if (hdr->b_type > ARC_BUFC_NUMTYPES)
2306 panic("invalid hdr=%p", (void *)hdr);
2307 if (spa && hdr->b_spa != spa)
2310 /* ignore markers */
2311 if (hdr->b_spa == 0)
2314 hash_lock = HDR_LOCK(hdr);
2315 /* caller may be trying to modify this buffer, skip it */
2316 if (MUTEX_HELD(hash_lock))
2320 * It may take a long time to evict all the bufs requested.
2321 * To avoid blocking all arc activity, periodically drop
2322 * the arcs_mtx and give other threads a chance to run
2323 * before reacquiring the lock.
2325 if (count++ > arc_evict_iterations) {
2326 list_insert_after(list, hdr, &marker);
2328 kpreempt(KPREEMPT_SYNC);
2330 hdr_prev = list_prev(list, &marker);
2331 list_remove(list, &marker);
2335 if (mutex_tryenter(hash_lock)) {
2336 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2337 ASSERT(hdr->b_buf == NULL);
2338 ARCSTAT_BUMP(arcstat_deleted);
2339 bytes_deleted += hdr->b_size;
2341 if (hdr->b_l2hdr != NULL) {
2343 * This buffer is cached on the 2nd Level ARC;
2344 * don't destroy the header.
2346 arc_change_state(arc_l2c_only, hdr, hash_lock);
2347 mutex_exit(hash_lock);
2349 arc_change_state(arc_anon, hdr, hash_lock);
2350 mutex_exit(hash_lock);
2351 arc_hdr_destroy(hdr);
2354 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2355 if (bytes >= 0 && bytes_deleted >= bytes)
2357 } else if (bytes < 0) {
2359 * Insert a list marker and then wait for the
2360 * hash lock to become available. Once its
2361 * available, restart from where we left off.
2363 list_insert_after(list, hdr, &marker);
2365 mutex_enter(hash_lock);
2366 mutex_exit(hash_lock);
2368 hdr_prev = list_prev(list, &marker);
2369 list_remove(list, &marker);
2376 idx = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2379 if (lists < list_count)
2383 if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2384 (bytes < 0 || bytes_deleted < bytes)) {
2385 list_start = &state->arcs_lists[0];
2386 list_count = ARC_BUFC_NUMMETADATALISTS;
2392 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2396 if (bytes_deleted < bytes)
2397 dprintf("only deleted %lld bytes from %p",
2398 (longlong_t)bytes_deleted, state);
2404 int64_t adjustment, delta;
2410 adjustment = MIN((int64_t)(arc_size - arc_c),
2411 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2414 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2415 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2416 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2417 adjustment -= delta;
2420 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2421 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2422 (void) arc_evict(arc_mru, 0, delta, FALSE,
2430 adjustment = arc_size - arc_c;
2432 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2433 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2434 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2435 adjustment -= delta;
2438 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2439 int64_t delta = MIN(adjustment,
2440 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2441 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2446 * Adjust ghost lists
2449 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2451 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2452 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2453 arc_evict_ghost(arc_mru_ghost, 0, delta);
2457 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2459 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2460 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2461 arc_evict_ghost(arc_mfu_ghost, 0, delta);
2466 arc_do_user_evicts(void)
2468 static arc_buf_t *tmp_arc_eviction_list;
2471 * Move list over to avoid LOR
2474 mutex_enter(&arc_eviction_mtx);
2475 tmp_arc_eviction_list = arc_eviction_list;
2476 arc_eviction_list = NULL;
2477 mutex_exit(&arc_eviction_mtx);
2479 while (tmp_arc_eviction_list != NULL) {
2480 arc_buf_t *buf = tmp_arc_eviction_list;
2481 tmp_arc_eviction_list = buf->b_next;
2482 mutex_enter(&buf->b_evict_lock);
2484 mutex_exit(&buf->b_evict_lock);
2486 if (buf->b_efunc != NULL)
2487 VERIFY0(buf->b_efunc(buf->b_private));
2489 buf->b_efunc = NULL;
2490 buf->b_private = NULL;
2491 kmem_cache_free(buf_cache, buf);
2494 if (arc_eviction_list != NULL)
2499 * Flush all *evictable* data from the cache for the given spa.
2500 * NOTE: this will not touch "active" (i.e. referenced) data.
2503 arc_flush(spa_t *spa)
2508 guid = spa_load_guid(spa);
2510 while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
2511 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2515 while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
2516 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2520 while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
2521 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2525 while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
2526 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2531 arc_evict_ghost(arc_mru_ghost, guid, -1);
2532 arc_evict_ghost(arc_mfu_ghost, guid, -1);
2534 mutex_enter(&arc_reclaim_thr_lock);
2535 arc_do_user_evicts();
2536 mutex_exit(&arc_reclaim_thr_lock);
2537 ASSERT(spa || arc_eviction_list == NULL);
2544 if (arc_c > arc_c_min) {
2547 to_free = arc_c >> arc_shrink_shift;
2548 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
2549 arc_c_min, uint64_t, arc_p, uint64_t, to_free);
2550 if (arc_c > arc_c_min + to_free)
2551 atomic_add_64(&arc_c, -to_free);
2555 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
2556 if (arc_c > arc_size)
2557 arc_c = MAX(arc_size, arc_c_min);
2559 arc_p = (arc_c >> 1);
2561 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
2564 ASSERT(arc_c >= arc_c_min);
2565 ASSERT((int64_t)arc_p >= 0);
2568 if (arc_size > arc_c) {
2569 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
2575 static int needfree = 0;
2578 arc_reclaim_needed(void)
2584 DTRACE_PROBE(arc__reclaim_needfree);
2589 * Cooperate with pagedaemon when it's time for it to scan
2590 * and reclaim some pages.
2592 if (freemem < zfs_arc_free_target) {
2593 DTRACE_PROBE2(arc__reclaim_freemem, uint64_t,
2594 freemem, uint64_t, zfs_arc_free_target);
2600 * take 'desfree' extra pages, so we reclaim sooner, rather than later
2605 * check that we're out of range of the pageout scanner. It starts to
2606 * schedule paging if freemem is less than lotsfree and needfree.
2607 * lotsfree is the high-water mark for pageout, and needfree is the
2608 * number of needed free pages. We add extra pages here to make sure
2609 * the scanner doesn't start up while we're freeing memory.
2611 if (freemem < lotsfree + needfree + extra)
2615 * check to make sure that swapfs has enough space so that anon
2616 * reservations can still succeed. anon_resvmem() checks that the
2617 * availrmem is greater than swapfs_minfree, and the number of reserved
2618 * swap pages. We also add a bit of extra here just to prevent
2619 * circumstances from getting really dire.
2621 if (availrmem < swapfs_minfree + swapfs_reserve + extra)
2625 * Check that we have enough availrmem that memory locking (e.g., via
2626 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
2627 * stores the number of pages that cannot be locked; when availrmem
2628 * drops below pages_pp_maximum, page locking mechanisms such as
2629 * page_pp_lock() will fail.)
2631 if (availrmem <= pages_pp_maximum)
2635 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
2637 * If we're on an i386 platform, it's possible that we'll exhaust the
2638 * kernel heap space before we ever run out of available physical
2639 * memory. Most checks of the size of the heap_area compare against
2640 * tune.t_minarmem, which is the minimum available real memory that we
2641 * can have in the system. However, this is generally fixed at 25 pages
2642 * which is so low that it's useless. In this comparison, we seek to
2643 * calculate the total heap-size, and reclaim if more than 3/4ths of the
2644 * heap is allocated. (Or, in the calculation, if less than 1/4th is
2647 if (vmem_size(heap_arena, VMEM_FREE) <
2648 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2)) {
2649 DTRACE_PROBE2(arc__reclaim_used, uint64_t,
2650 vmem_size(heap_arena, VMEM_FREE), uint64_t,
2651 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2);
2654 #define zio_arena NULL
2656 #define zio_arena heap_arena
2660 * If zio data pages are being allocated out of a separate heap segment,
2661 * then enforce that the size of available vmem for this arena remains
2662 * above about 1/16th free.
2664 * Note: The 1/16th arena free requirement was put in place
2665 * to aggressively evict memory from the arc in order to avoid
2666 * memory fragmentation issues.
2668 if (zio_arena != NULL &&
2669 vmem_size(zio_arena, VMEM_FREE) <
2670 (vmem_size(zio_arena, VMEM_ALLOC) >> 4))
2674 * Above limits know nothing about real level of KVA fragmentation.
2675 * Start aggressive reclamation if too little sequential KVA left.
2677 if (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) {
2678 DTRACE_PROBE2(arc__reclaim_maxfree, uint64_t,
2679 vmem_size(heap_arena, VMEM_MAXFREE),
2680 uint64_t, zfs_max_recordsize);
2685 if (spa_get_random(100) == 0)
2687 #endif /* _KERNEL */
2688 DTRACE_PROBE(arc__reclaim_no);
2693 extern kmem_cache_t *zio_buf_cache[];
2694 extern kmem_cache_t *zio_data_buf_cache[];
2695 extern kmem_cache_t *range_seg_cache;
2697 static __noinline void
2698 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
2701 kmem_cache_t *prev_cache = NULL;
2702 kmem_cache_t *prev_data_cache = NULL;
2704 DTRACE_PROBE(arc__kmem_reap_start);
2706 if (arc_meta_used >= arc_meta_limit) {
2708 * We are exceeding our meta-data cache limit.
2709 * Purge some DNLC entries to release holds on meta-data.
2711 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
2715 * Reclaim unused memory from all kmem caches.
2722 * An aggressive reclamation will shrink the cache size as well as
2723 * reap free buffers from the arc kmem caches.
2725 if (strat == ARC_RECLAIM_AGGR)
2728 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2729 if (zio_buf_cache[i] != prev_cache) {
2730 prev_cache = zio_buf_cache[i];
2731 kmem_cache_reap_now(zio_buf_cache[i]);
2733 if (zio_data_buf_cache[i] != prev_data_cache) {
2734 prev_data_cache = zio_data_buf_cache[i];
2735 kmem_cache_reap_now(zio_data_buf_cache[i]);
2738 kmem_cache_reap_now(buf_cache);
2739 kmem_cache_reap_now(hdr_cache);
2740 kmem_cache_reap_now(range_seg_cache);
2744 * Ask the vmem arena to reclaim unused memory from its
2747 if (zio_arena != NULL && strat == ARC_RECLAIM_AGGR)
2748 vmem_qcache_reap(zio_arena);
2750 DTRACE_PROBE(arc__kmem_reap_end);
2754 arc_reclaim_thread(void *dummy __unused)
2756 clock_t growtime = 0;
2757 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2760 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2762 mutex_enter(&arc_reclaim_thr_lock);
2763 while (arc_thread_exit == 0) {
2764 if (arc_reclaim_needed()) {
2767 if (last_reclaim == ARC_RECLAIM_CONS) {
2768 DTRACE_PROBE(arc__reclaim_aggr_no_grow);
2769 last_reclaim = ARC_RECLAIM_AGGR;
2771 last_reclaim = ARC_RECLAIM_CONS;
2775 last_reclaim = ARC_RECLAIM_AGGR;
2776 DTRACE_PROBE(arc__reclaim_aggr);
2780 /* reset the growth delay for every reclaim */
2781 growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
2783 if (needfree && last_reclaim == ARC_RECLAIM_CONS) {
2785 * If needfree is TRUE our vm_lowmem hook
2786 * was called and in that case we must free some
2787 * memory, so switch to aggressive mode.
2790 last_reclaim = ARC_RECLAIM_AGGR;
2792 arc_kmem_reap_now(last_reclaim);
2795 } else if (arc_no_grow && ddi_get_lbolt() >= growtime) {
2796 arc_no_grow = FALSE;
2801 if (arc_eviction_list != NULL)
2802 arc_do_user_evicts();
2811 /* block until needed, or one second, whichever is shorter */
2812 CALLB_CPR_SAFE_BEGIN(&cpr);
2813 (void) cv_timedwait(&arc_reclaim_thr_cv,
2814 &arc_reclaim_thr_lock, hz);
2815 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2818 arc_thread_exit = 0;
2819 cv_broadcast(&arc_reclaim_thr_cv);
2820 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2825 * Adapt arc info given the number of bytes we are trying to add and
2826 * the state that we are comming from. This function is only called
2827 * when we are adding new content to the cache.
2830 arc_adapt(int bytes, arc_state_t *state)
2833 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2835 if (state == arc_l2c_only)
2840 * Adapt the target size of the MRU list:
2841 * - if we just hit in the MRU ghost list, then increase
2842 * the target size of the MRU list.
2843 * - if we just hit in the MFU ghost list, then increase
2844 * the target size of the MFU list by decreasing the
2845 * target size of the MRU list.
2847 if (state == arc_mru_ghost) {
2848 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2849 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2850 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2852 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2853 } else if (state == arc_mfu_ghost) {
2856 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2857 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2858 mult = MIN(mult, 10);
2860 delta = MIN(bytes * mult, arc_p);
2861 arc_p = MAX(arc_p_min, arc_p - delta);
2863 ASSERT((int64_t)arc_p >= 0);
2865 if (arc_reclaim_needed()) {
2866 cv_signal(&arc_reclaim_thr_cv);
2873 if (arc_c >= arc_c_max)
2877 * If we're within (2 * maxblocksize) bytes of the target
2878 * cache size, increment the target cache size
2880 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2881 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
2882 atomic_add_64(&arc_c, (int64_t)bytes);
2883 if (arc_c > arc_c_max)
2885 else if (state == arc_anon)
2886 atomic_add_64(&arc_p, (int64_t)bytes);
2890 ASSERT((int64_t)arc_p >= 0);
2894 * Check if the cache has reached its limits and eviction is required
2898 arc_evict_needed(arc_buf_contents_t type)
2900 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2903 if (arc_reclaim_needed())
2906 return (arc_size > arc_c);
2910 * The buffer, supplied as the first argument, needs a data block.
2911 * So, if we are at cache max, determine which cache should be victimized.
2912 * We have the following cases:
2914 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2915 * In this situation if we're out of space, but the resident size of the MFU is
2916 * under the limit, victimize the MFU cache to satisfy this insertion request.
2918 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2919 * Here, we've used up all of the available space for the MRU, so we need to
2920 * evict from our own cache instead. Evict from the set of resident MRU
2923 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2924 * c minus p represents the MFU space in the cache, since p is the size of the
2925 * cache that is dedicated to the MRU. In this situation there's still space on
2926 * the MFU side, so the MRU side needs to be victimized.
2928 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2929 * MFU's resident set is consuming more space than it has been allotted. In
2930 * this situation, we must victimize our own cache, the MFU, for this insertion.
2933 arc_get_data_buf(arc_buf_t *buf)
2935 arc_state_t *state = buf->b_hdr->b_state;
2936 uint64_t size = buf->b_hdr->b_size;
2937 arc_buf_contents_t type = buf->b_hdr->b_type;
2939 arc_adapt(size, state);
2942 * We have not yet reached cache maximum size,
2943 * just allocate a new buffer.
2945 if (!arc_evict_needed(type)) {
2946 if (type == ARC_BUFC_METADATA) {
2947 buf->b_data = zio_buf_alloc(size);
2948 arc_space_consume(size, ARC_SPACE_DATA);
2950 ASSERT(type == ARC_BUFC_DATA);
2951 buf->b_data = zio_data_buf_alloc(size);
2952 ARCSTAT_INCR(arcstat_data_size, size);
2953 atomic_add_64(&arc_size, size);
2959 * If we are prefetching from the mfu ghost list, this buffer
2960 * will end up on the mru list; so steal space from there.
2962 if (state == arc_mfu_ghost)
2963 state = buf->b_hdr->b_flags & ARC_FLAG_PREFETCH ?
2965 else if (state == arc_mru_ghost)
2968 if (state == arc_mru || state == arc_anon) {
2969 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2970 state = (arc_mfu->arcs_lsize[type] >= size &&
2971 arc_p > mru_used) ? arc_mfu : arc_mru;
2974 uint64_t mfu_space = arc_c - arc_p;
2975 state = (arc_mru->arcs_lsize[type] >= size &&
2976 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2978 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2979 if (type == ARC_BUFC_METADATA) {
2980 buf->b_data = zio_buf_alloc(size);
2981 arc_space_consume(size, ARC_SPACE_DATA);
2983 ASSERT(type == ARC_BUFC_DATA);
2984 buf->b_data = zio_data_buf_alloc(size);
2985 ARCSTAT_INCR(arcstat_data_size, size);
2986 atomic_add_64(&arc_size, size);
2988 ARCSTAT_BUMP(arcstat_recycle_miss);
2990 ASSERT(buf->b_data != NULL);
2993 * Update the state size. Note that ghost states have a
2994 * "ghost size" and so don't need to be updated.
2996 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2997 arc_buf_hdr_t *hdr = buf->b_hdr;
2999 atomic_add_64(&hdr->b_state->arcs_size, size);
3000 if (list_link_active(&hdr->b_arc_node)) {
3001 ASSERT(refcount_is_zero(&hdr->b_refcnt));
3002 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
3005 * If we are growing the cache, and we are adding anonymous
3006 * data, and we have outgrown arc_p, update arc_p
3008 if (arc_size < arc_c && hdr->b_state == arc_anon &&
3009 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
3010 arc_p = MIN(arc_c, arc_p + size);
3012 ARCSTAT_BUMP(arcstat_allocated);
3016 * This routine is called whenever a buffer is accessed.
3017 * NOTE: the hash lock is dropped in this function.
3020 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3024 ASSERT(MUTEX_HELD(hash_lock));
3026 if (hdr->b_state == arc_anon) {
3028 * This buffer is not in the cache, and does not
3029 * appear in our "ghost" list. Add the new buffer
3033 ASSERT(hdr->b_arc_access == 0);
3034 hdr->b_arc_access = ddi_get_lbolt();
3035 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3036 arc_change_state(arc_mru, hdr, hash_lock);
3038 } else if (hdr->b_state == arc_mru) {
3039 now = ddi_get_lbolt();
3042 * If this buffer is here because of a prefetch, then either:
3043 * - clear the flag if this is a "referencing" read
3044 * (any subsequent access will bump this into the MFU state).
3046 * - move the buffer to the head of the list if this is
3047 * another prefetch (to make it less likely to be evicted).
3049 if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3050 if (refcount_count(&hdr->b_refcnt) == 0) {
3051 ASSERT(list_link_active(&hdr->b_arc_node));
3053 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3054 ARCSTAT_BUMP(arcstat_mru_hits);
3056 hdr->b_arc_access = now;
3061 * This buffer has been "accessed" only once so far,
3062 * but it is still in the cache. Move it to the MFU
3065 if (now > hdr->b_arc_access + ARC_MINTIME) {
3067 * More than 125ms have passed since we
3068 * instantiated this buffer. Move it to the
3069 * most frequently used state.
3071 hdr->b_arc_access = now;
3072 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3073 arc_change_state(arc_mfu, hdr, hash_lock);
3075 ARCSTAT_BUMP(arcstat_mru_hits);
3076 } else if (hdr->b_state == arc_mru_ghost) {
3077 arc_state_t *new_state;
3079 * This buffer has been "accessed" recently, but
3080 * was evicted from the cache. Move it to the
3084 if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3085 new_state = arc_mru;
3086 if (refcount_count(&hdr->b_refcnt) > 0)
3087 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3088 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3090 new_state = arc_mfu;
3091 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3094 hdr->b_arc_access = ddi_get_lbolt();
3095 arc_change_state(new_state, hdr, hash_lock);
3097 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3098 } else if (hdr->b_state == arc_mfu) {
3100 * This buffer has been accessed more than once and is
3101 * still in the cache. Keep it in the MFU state.
3103 * NOTE: an add_reference() that occurred when we did
3104 * the arc_read() will have kicked this off the list.
3105 * If it was a prefetch, we will explicitly move it to
3106 * the head of the list now.
3108 if ((hdr->b_flags & ARC_FLAG_PREFETCH) != 0) {
3109 ASSERT(refcount_count(&hdr->b_refcnt) == 0);
3110 ASSERT(list_link_active(&hdr->b_arc_node));
3112 ARCSTAT_BUMP(arcstat_mfu_hits);
3113 hdr->b_arc_access = ddi_get_lbolt();
3114 } else if (hdr->b_state == arc_mfu_ghost) {
3115 arc_state_t *new_state = arc_mfu;
3117 * This buffer has been accessed more than once but has
3118 * been evicted from the cache. Move it back to the
3122 if (hdr->b_flags & ARC_FLAG_PREFETCH) {
3124 * This is a prefetch access...
3125 * move this block back to the MRU state.
3127 ASSERT0(refcount_count(&hdr->b_refcnt));
3128 new_state = arc_mru;
3131 hdr->b_arc_access = ddi_get_lbolt();
3132 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3133 arc_change_state(new_state, hdr, hash_lock);
3135 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3136 } else if (hdr->b_state == arc_l2c_only) {
3138 * This buffer is on the 2nd Level ARC.
3141 hdr->b_arc_access = ddi_get_lbolt();
3142 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3143 arc_change_state(arc_mfu, hdr, hash_lock);
3145 ASSERT(!"invalid arc state");
3149 /* a generic arc_done_func_t which you can use */
3152 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3154 if (zio == NULL || zio->io_error == 0)
3155 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3156 VERIFY(arc_buf_remove_ref(buf, arg));
3159 /* a generic arc_done_func_t */
3161 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3163 arc_buf_t **bufp = arg;
3164 if (zio && zio->io_error) {
3165 VERIFY(arc_buf_remove_ref(buf, arg));
3169 ASSERT(buf->b_data);
3174 arc_read_done(zio_t *zio)
3178 arc_buf_t *abuf; /* buffer we're assigning to callback */
3179 kmutex_t *hash_lock = NULL;
3180 arc_callback_t *callback_list, *acb;
3181 int freeable = FALSE;
3183 buf = zio->io_private;
3187 * The hdr was inserted into hash-table and removed from lists
3188 * prior to starting I/O. We should find this header, since
3189 * it's in the hash table, and it should be legit since it's
3190 * not possible to evict it during the I/O. The only possible
3191 * reason for it not to be found is if we were freed during the
3194 if (HDR_IN_HASH_TABLE(hdr)) {
3195 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3196 ASSERT3U(hdr->b_dva.dva_word[0], ==,
3197 BP_IDENTITY(zio->io_bp)->dva_word[0]);
3198 ASSERT3U(hdr->b_dva.dva_word[1], ==,
3199 BP_IDENTITY(zio->io_bp)->dva_word[1]);
3201 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3204 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3205 hash_lock == NULL) ||
3207 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3208 (found == hdr && HDR_L2_READING(hdr)));
3211 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
3212 if (l2arc_noprefetch && (hdr->b_flags & ARC_FLAG_PREFETCH))
3213 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
3215 /* byteswap if necessary */
3216 callback_list = hdr->b_acb;
3217 ASSERT(callback_list != NULL);
3218 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3219 dmu_object_byteswap_t bswap =
3220 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3221 arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3222 byteswap_uint64_array :
3223 dmu_ot_byteswap[bswap].ob_func;
3224 func(buf->b_data, hdr->b_size);
3227 arc_cksum_compute(buf, B_FALSE);
3230 #endif /* illumos */
3232 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3234 * Only call arc_access on anonymous buffers. This is because
3235 * if we've issued an I/O for an evicted buffer, we've already
3236 * called arc_access (to prevent any simultaneous readers from
3237 * getting confused).
3239 arc_access(hdr, hash_lock);
3242 /* create copies of the data buffer for the callers */
3244 for (acb = callback_list; acb; acb = acb->acb_next) {
3245 if (acb->acb_done) {
3247 ARCSTAT_BUMP(arcstat_duplicate_reads);
3248 abuf = arc_buf_clone(buf);
3250 acb->acb_buf = abuf;
3255 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3256 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3258 ASSERT(buf->b_efunc == NULL);
3259 ASSERT(hdr->b_datacnt == 1);
3260 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3263 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3265 if (zio->io_error != 0) {
3266 hdr->b_flags |= ARC_FLAG_IO_ERROR;
3267 if (hdr->b_state != arc_anon)
3268 arc_change_state(arc_anon, hdr, hash_lock);
3269 if (HDR_IN_HASH_TABLE(hdr))
3270 buf_hash_remove(hdr);
3271 freeable = refcount_is_zero(&hdr->b_refcnt);
3275 * Broadcast before we drop the hash_lock to avoid the possibility
3276 * that the hdr (and hence the cv) might be freed before we get to
3277 * the cv_broadcast().
3279 cv_broadcast(&hdr->b_cv);
3282 mutex_exit(hash_lock);
3285 * This block was freed while we waited for the read to
3286 * complete. It has been removed from the hash table and
3287 * moved to the anonymous state (so that it won't show up
3290 ASSERT3P(hdr->b_state, ==, arc_anon);
3291 freeable = refcount_is_zero(&hdr->b_refcnt);
3294 /* execute each callback and free its structure */
3295 while ((acb = callback_list) != NULL) {
3297 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3299 if (acb->acb_zio_dummy != NULL) {
3300 acb->acb_zio_dummy->io_error = zio->io_error;
3301 zio_nowait(acb->acb_zio_dummy);
3304 callback_list = acb->acb_next;
3305 kmem_free(acb, sizeof (arc_callback_t));
3309 arc_hdr_destroy(hdr);
3313 * "Read" the block block at the specified DVA (in bp) via the
3314 * cache. If the block is found in the cache, invoke the provided
3315 * callback immediately and return. Note that the `zio' parameter
3316 * in the callback will be NULL in this case, since no IO was
3317 * required. If the block is not in the cache pass the read request
3318 * on to the spa with a substitute callback function, so that the
3319 * requested block will be added to the cache.
3321 * If a read request arrives for a block that has a read in-progress,
3322 * either wait for the in-progress read to complete (and return the
3323 * results); or, if this is a read with a "done" func, add a record
3324 * to the read to invoke the "done" func when the read completes,
3325 * and return; or just return.
3327 * arc_read_done() will invoke all the requested "done" functions
3328 * for readers of this block.
3331 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3332 void *private, zio_priority_t priority, int zio_flags,
3333 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
3335 arc_buf_hdr_t *hdr = NULL;
3336 arc_buf_t *buf = NULL;
3337 kmutex_t *hash_lock = NULL;
3339 uint64_t guid = spa_load_guid(spa);
3341 ASSERT(!BP_IS_EMBEDDED(bp) ||
3342 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3345 if (!BP_IS_EMBEDDED(bp)) {
3347 * Embedded BP's have no DVA and require no I/O to "read".
3348 * Create an anonymous arc buf to back it.
3350 hdr = buf_hash_find(guid, bp, &hash_lock);
3353 if (hdr != NULL && hdr->b_datacnt > 0) {
3355 *arc_flags |= ARC_FLAG_CACHED;
3357 if (HDR_IO_IN_PROGRESS(hdr)) {
3359 if (*arc_flags & ARC_FLAG_WAIT) {
3360 cv_wait(&hdr->b_cv, hash_lock);
3361 mutex_exit(hash_lock);
3364 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3367 arc_callback_t *acb = NULL;
3369 acb = kmem_zalloc(sizeof (arc_callback_t),
3371 acb->acb_done = done;
3372 acb->acb_private = private;
3374 acb->acb_zio_dummy = zio_null(pio,
3375 spa, NULL, NULL, NULL, zio_flags);
3377 ASSERT(acb->acb_done != NULL);
3378 acb->acb_next = hdr->b_acb;
3380 add_reference(hdr, hash_lock, private);
3381 mutex_exit(hash_lock);
3384 mutex_exit(hash_lock);
3388 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3391 add_reference(hdr, hash_lock, private);
3393 * If this block is already in use, create a new
3394 * copy of the data so that we will be guaranteed
3395 * that arc_release() will always succeed.
3399 ASSERT(buf->b_data);
3400 if (HDR_BUF_AVAILABLE(hdr)) {
3401 ASSERT(buf->b_efunc == NULL);
3402 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3404 buf = arc_buf_clone(buf);
3407 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
3408 refcount_count(&hdr->b_refcnt) == 0) {
3409 hdr->b_flags |= ARC_FLAG_PREFETCH;
3411 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3412 arc_access(hdr, hash_lock);
3413 if (*arc_flags & ARC_FLAG_L2CACHE)
3414 hdr->b_flags |= ARC_FLAG_L2CACHE;
3415 if (*arc_flags & ARC_FLAG_L2COMPRESS)
3416 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3417 mutex_exit(hash_lock);
3418 ARCSTAT_BUMP(arcstat_hits);
3419 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3420 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3421 data, metadata, hits);
3424 done(NULL, buf, private);
3426 uint64_t size = BP_GET_LSIZE(bp);
3427 arc_callback_t *acb;
3430 boolean_t devw = B_FALSE;
3431 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
3432 uint64_t b_asize = 0;
3435 /* this block is not in the cache */
3436 arc_buf_hdr_t *exists = NULL;
3437 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3438 buf = arc_buf_alloc(spa, size, private, type);
3440 if (!BP_IS_EMBEDDED(bp)) {
3441 hdr->b_dva = *BP_IDENTITY(bp);
3442 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3443 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3444 exists = buf_hash_insert(hdr, &hash_lock);
3446 if (exists != NULL) {
3447 /* somebody beat us to the hash insert */
3448 mutex_exit(hash_lock);
3449 buf_discard_identity(hdr);
3450 (void) arc_buf_remove_ref(buf, private);
3451 goto top; /* restart the IO request */
3454 /* if this is a prefetch, we don't have a reference */
3455 if (*arc_flags & ARC_FLAG_PREFETCH) {
3456 (void) remove_reference(hdr, hash_lock,
3458 hdr->b_flags |= ARC_FLAG_PREFETCH;
3460 if (*arc_flags & ARC_FLAG_L2CACHE)
3461 hdr->b_flags |= ARC_FLAG_L2CACHE;
3462 if (*arc_flags & ARC_FLAG_L2COMPRESS)
3463 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3464 if (BP_GET_LEVEL(bp) > 0)
3465 hdr->b_flags |= ARC_FLAG_INDIRECT;
3467 /* this block is in the ghost cache */
3468 ASSERT(GHOST_STATE(hdr->b_state));
3469 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3470 ASSERT0(refcount_count(&hdr->b_refcnt));
3471 ASSERT(hdr->b_buf == NULL);
3473 /* if this is a prefetch, we don't have a reference */
3474 if (*arc_flags & ARC_FLAG_PREFETCH)
3475 hdr->b_flags |= ARC_FLAG_PREFETCH;
3477 add_reference(hdr, hash_lock, private);
3478 if (*arc_flags & ARC_FLAG_L2CACHE)
3479 hdr->b_flags |= ARC_FLAG_L2CACHE;
3480 if (*arc_flags & ARC_FLAG_L2COMPRESS)
3481 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
3482 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3485 buf->b_efunc = NULL;
3486 buf->b_private = NULL;
3489 ASSERT(hdr->b_datacnt == 0);
3491 arc_get_data_buf(buf);
3492 arc_access(hdr, hash_lock);
3495 ASSERT(!GHOST_STATE(hdr->b_state));
3497 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
3498 acb->acb_done = done;
3499 acb->acb_private = private;
3501 ASSERT(hdr->b_acb == NULL);
3503 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3505 if (hdr->b_l2hdr != NULL &&
3506 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3507 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3508 addr = hdr->b_l2hdr->b_daddr;
3509 b_compress = hdr->b_l2hdr->b_compress;
3510 b_asize = hdr->b_l2hdr->b_asize;
3512 * Lock out device removal.
3514 if (vdev_is_dead(vd) ||
3515 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3519 if (hash_lock != NULL)
3520 mutex_exit(hash_lock);
3523 * At this point, we have a level 1 cache miss. Try again in
3524 * L2ARC if possible.
3526 ASSERT3U(hdr->b_size, ==, size);
3527 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3528 uint64_t, size, zbookmark_phys_t *, zb);
3529 ARCSTAT_BUMP(arcstat_misses);
3530 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_FLAG_PREFETCH),
3531 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3532 data, metadata, misses);
3534 curthread->td_ru.ru_inblock++;
3537 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3539 * Read from the L2ARC if the following are true:
3540 * 1. The L2ARC vdev was previously cached.
3541 * 2. This buffer still has L2ARC metadata.
3542 * 3. This buffer isn't currently writing to the L2ARC.
3543 * 4. The L2ARC entry wasn't evicted, which may
3544 * also have invalidated the vdev.
3545 * 5. This isn't prefetch and l2arc_noprefetch is set.
3547 if (hdr->b_l2hdr != NULL &&
3548 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3549 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3550 l2arc_read_callback_t *cb;
3552 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3553 ARCSTAT_BUMP(arcstat_l2_hits);
3555 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3557 cb->l2rcb_buf = buf;
3558 cb->l2rcb_spa = spa;
3561 cb->l2rcb_flags = zio_flags;
3562 cb->l2rcb_compress = b_compress;
3564 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3565 addr + size < vd->vdev_psize -
3566 VDEV_LABEL_END_SIZE);
3569 * l2arc read. The SCL_L2ARC lock will be
3570 * released by l2arc_read_done().
3571 * Issue a null zio if the underlying buffer
3572 * was squashed to zero size by compression.
3574 if (b_compress == ZIO_COMPRESS_EMPTY) {
3575 rzio = zio_null(pio, spa, vd,
3576 l2arc_read_done, cb,
3577 zio_flags | ZIO_FLAG_DONT_CACHE |
3579 ZIO_FLAG_DONT_PROPAGATE |
3580 ZIO_FLAG_DONT_RETRY);
3582 rzio = zio_read_phys(pio, vd, addr,
3583 b_asize, buf->b_data,
3585 l2arc_read_done, cb, priority,
3586 zio_flags | ZIO_FLAG_DONT_CACHE |
3588 ZIO_FLAG_DONT_PROPAGATE |
3589 ZIO_FLAG_DONT_RETRY, B_FALSE);
3591 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3593 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
3595 if (*arc_flags & ARC_FLAG_NOWAIT) {
3600 ASSERT(*arc_flags & ARC_FLAG_WAIT);
3601 if (zio_wait(rzio) == 0)
3604 /* l2arc read error; goto zio_read() */
3606 DTRACE_PROBE1(l2arc__miss,
3607 arc_buf_hdr_t *, hdr);
3608 ARCSTAT_BUMP(arcstat_l2_misses);
3609 if (HDR_L2_WRITING(hdr))
3610 ARCSTAT_BUMP(arcstat_l2_rw_clash);
3611 spa_config_exit(spa, SCL_L2ARC, vd);
3615 spa_config_exit(spa, SCL_L2ARC, vd);
3616 if (l2arc_ndev != 0) {
3617 DTRACE_PROBE1(l2arc__miss,
3618 arc_buf_hdr_t *, hdr);
3619 ARCSTAT_BUMP(arcstat_l2_misses);
3623 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3624 arc_read_done, buf, priority, zio_flags, zb);
3626 if (*arc_flags & ARC_FLAG_WAIT)
3627 return (zio_wait(rzio));
3629 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3636 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3638 ASSERT(buf->b_hdr != NULL);
3639 ASSERT(buf->b_hdr->b_state != arc_anon);
3640 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3641 ASSERT(buf->b_efunc == NULL);
3642 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3644 buf->b_efunc = func;
3645 buf->b_private = private;
3649 * Notify the arc that a block was freed, and thus will never be used again.
3652 arc_freed(spa_t *spa, const blkptr_t *bp)
3655 kmutex_t *hash_lock;
3656 uint64_t guid = spa_load_guid(spa);
3658 ASSERT(!BP_IS_EMBEDDED(bp));
3660 hdr = buf_hash_find(guid, bp, &hash_lock);
3663 if (HDR_BUF_AVAILABLE(hdr)) {
3664 arc_buf_t *buf = hdr->b_buf;
3665 add_reference(hdr, hash_lock, FTAG);
3666 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3667 mutex_exit(hash_lock);
3669 arc_release(buf, FTAG);
3670 (void) arc_buf_remove_ref(buf, FTAG);
3672 mutex_exit(hash_lock);
3678 * Clear the user eviction callback set by arc_set_callback(), first calling
3679 * it if it exists. Because the presence of a callback keeps an arc_buf cached
3680 * clearing the callback may result in the arc_buf being destroyed. However,
3681 * it will not result in the *last* arc_buf being destroyed, hence the data
3682 * will remain cached in the ARC. We make a copy of the arc buffer here so
3683 * that we can process the callback without holding any locks.
3685 * It's possible that the callback is already in the process of being cleared
3686 * by another thread. In this case we can not clear the callback.
3688 * Returns B_TRUE if the callback was successfully called and cleared.
3691 arc_clear_callback(arc_buf_t *buf)
3694 kmutex_t *hash_lock;
3695 arc_evict_func_t *efunc = buf->b_efunc;
3696 void *private = buf->b_private;
3697 list_t *list, *evicted_list;
3698 kmutex_t *lock, *evicted_lock;
3700 mutex_enter(&buf->b_evict_lock);
3704 * We are in arc_do_user_evicts().
3706 ASSERT(buf->b_data == NULL);
3707 mutex_exit(&buf->b_evict_lock);
3709 } else if (buf->b_data == NULL) {
3711 * We are on the eviction list; process this buffer now
3712 * but let arc_do_user_evicts() do the reaping.
3714 buf->b_efunc = NULL;
3715 mutex_exit(&buf->b_evict_lock);
3716 VERIFY0(efunc(private));
3719 hash_lock = HDR_LOCK(hdr);
3720 mutex_enter(hash_lock);
3722 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3724 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3725 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3727 buf->b_efunc = NULL;
3728 buf->b_private = NULL;
3730 if (hdr->b_datacnt > 1) {
3731 mutex_exit(&buf->b_evict_lock);
3732 arc_buf_destroy(buf, FALSE, TRUE);
3734 ASSERT(buf == hdr->b_buf);
3735 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3736 mutex_exit(&buf->b_evict_lock);
3739 mutex_exit(hash_lock);
3740 VERIFY0(efunc(private));
3745 * Release this buffer from the cache, making it an anonymous buffer. This
3746 * must be done after a read and prior to modifying the buffer contents.
3747 * If the buffer has more than one reference, we must make
3748 * a new hdr for the buffer.
3751 arc_release(arc_buf_t *buf, void *tag)
3754 kmutex_t *hash_lock = NULL;
3755 l2arc_buf_hdr_t *l2hdr;
3759 * It would be nice to assert that if it's DMU metadata (level >
3760 * 0 || it's the dnode file), then it must be syncing context.
3761 * But we don't know that information at this level.
3764 mutex_enter(&buf->b_evict_lock);
3767 /* this buffer is not on any list */
3768 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3770 if (hdr->b_state == arc_anon) {
3771 /* this buffer is already released */
3772 ASSERT(buf->b_efunc == NULL);
3774 hash_lock = HDR_LOCK(hdr);
3775 mutex_enter(hash_lock);
3777 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3780 l2hdr = hdr->b_l2hdr;
3782 mutex_enter(&l2arc_buflist_mtx);
3783 arc_buf_l2_cdata_free(hdr);
3784 hdr->b_l2hdr = NULL;
3785 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3787 buf_size = hdr->b_size;
3790 * Do we have more than one buf?
3792 if (hdr->b_datacnt > 1) {
3793 arc_buf_hdr_t *nhdr;
3795 uint64_t blksz = hdr->b_size;
3796 uint64_t spa = hdr->b_spa;
3797 arc_buf_contents_t type = hdr->b_type;
3798 uint32_t flags = hdr->b_flags;
3800 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3802 * Pull the data off of this hdr and attach it to
3803 * a new anonymous hdr.
3805 (void) remove_reference(hdr, hash_lock, tag);
3807 while (*bufp != buf)
3808 bufp = &(*bufp)->b_next;
3809 *bufp = buf->b_next;
3812 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3813 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3814 if (refcount_is_zero(&hdr->b_refcnt)) {
3815 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3816 ASSERT3U(*size, >=, hdr->b_size);
3817 atomic_add_64(size, -hdr->b_size);
3821 * We're releasing a duplicate user data buffer, update
3822 * our statistics accordingly.
3824 if (hdr->b_type == ARC_BUFC_DATA) {
3825 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3826 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3829 hdr->b_datacnt -= 1;
3830 arc_cksum_verify(buf);
3832 arc_buf_unwatch(buf);
3833 #endif /* illumos */
3835 mutex_exit(hash_lock);
3837 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3838 nhdr->b_size = blksz;
3840 nhdr->b_type = type;
3842 nhdr->b_state = arc_anon;
3843 nhdr->b_arc_access = 0;
3844 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
3845 nhdr->b_l2hdr = NULL;
3846 nhdr->b_datacnt = 1;
3847 nhdr->b_freeze_cksum = NULL;
3848 (void) refcount_add(&nhdr->b_refcnt, tag);
3850 mutex_exit(&buf->b_evict_lock);
3851 atomic_add_64(&arc_anon->arcs_size, blksz);
3853 mutex_exit(&buf->b_evict_lock);
3854 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3855 ASSERT(!list_link_active(&hdr->b_arc_node));
3856 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3857 if (hdr->b_state != arc_anon)
3858 arc_change_state(arc_anon, hdr, hash_lock);
3859 hdr->b_arc_access = 0;
3861 mutex_exit(hash_lock);
3863 buf_discard_identity(hdr);
3866 buf->b_efunc = NULL;
3867 buf->b_private = NULL;
3870 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3871 vdev_space_update(l2hdr->b_dev->l2ad_vdev,
3872 -l2hdr->b_asize, 0, 0);
3873 trim_map_free(l2hdr->b_dev->l2ad_vdev, l2hdr->b_daddr,
3875 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3876 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3877 mutex_exit(&l2arc_buflist_mtx);
3882 arc_released(arc_buf_t *buf)
3886 mutex_enter(&buf->b_evict_lock);
3887 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3888 mutex_exit(&buf->b_evict_lock);
3894 arc_referenced(arc_buf_t *buf)
3898 mutex_enter(&buf->b_evict_lock);
3899 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3900 mutex_exit(&buf->b_evict_lock);
3901 return (referenced);
3906 arc_write_ready(zio_t *zio)
3908 arc_write_callback_t *callback = zio->io_private;
3909 arc_buf_t *buf = callback->awcb_buf;
3910 arc_buf_hdr_t *hdr = buf->b_hdr;
3912 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3913 callback->awcb_ready(zio, buf, callback->awcb_private);
3916 * If the IO is already in progress, then this is a re-write
3917 * attempt, so we need to thaw and re-compute the cksum.
3918 * It is the responsibility of the callback to handle the
3919 * accounting for any re-write attempt.
3921 if (HDR_IO_IN_PROGRESS(hdr)) {
3922 mutex_enter(&hdr->b_freeze_lock);
3923 if (hdr->b_freeze_cksum != NULL) {
3924 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3925 hdr->b_freeze_cksum = NULL;
3927 mutex_exit(&hdr->b_freeze_lock);
3929 arc_cksum_compute(buf, B_FALSE);
3930 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
3934 * The SPA calls this callback for each physical write that happens on behalf
3935 * of a logical write. See the comment in dbuf_write_physdone() for details.
3938 arc_write_physdone(zio_t *zio)
3940 arc_write_callback_t *cb = zio->io_private;
3941 if (cb->awcb_physdone != NULL)
3942 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3946 arc_write_done(zio_t *zio)
3948 arc_write_callback_t *callback = zio->io_private;
3949 arc_buf_t *buf = callback->awcb_buf;
3950 arc_buf_hdr_t *hdr = buf->b_hdr;
3952 ASSERT(hdr->b_acb == NULL);
3954 if (zio->io_error == 0) {
3955 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
3956 buf_discard_identity(hdr);
3958 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3959 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3960 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3963 ASSERT(BUF_EMPTY(hdr));
3967 * If the block to be written was all-zero or compressed enough to be
3968 * embedded in the BP, no write was performed so there will be no
3969 * dva/birth/checksum. The buffer must therefore remain anonymous
3972 if (!BUF_EMPTY(hdr)) {
3973 arc_buf_hdr_t *exists;
3974 kmutex_t *hash_lock;
3976 ASSERT(zio->io_error == 0);
3978 arc_cksum_verify(buf);
3980 exists = buf_hash_insert(hdr, &hash_lock);
3983 * This can only happen if we overwrite for
3984 * sync-to-convergence, because we remove
3985 * buffers from the hash table when we arc_free().
3987 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3988 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3989 panic("bad overwrite, hdr=%p exists=%p",
3990 (void *)hdr, (void *)exists);
3991 ASSERT(refcount_is_zero(&exists->b_refcnt));
3992 arc_change_state(arc_anon, exists, hash_lock);
3993 mutex_exit(hash_lock);
3994 arc_hdr_destroy(exists);
3995 exists = buf_hash_insert(hdr, &hash_lock);
3996 ASSERT3P(exists, ==, NULL);
3997 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3999 ASSERT(zio->io_prop.zp_nopwrite);
4000 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4001 panic("bad nopwrite, hdr=%p exists=%p",
4002 (void *)hdr, (void *)exists);
4005 ASSERT(hdr->b_datacnt == 1);
4006 ASSERT(hdr->b_state == arc_anon);
4007 ASSERT(BP_GET_DEDUP(zio->io_bp));
4008 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
4011 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4012 /* if it's not anon, we are doing a scrub */
4013 if (!exists && hdr->b_state == arc_anon)
4014 arc_access(hdr, hash_lock);
4015 mutex_exit(hash_lock);
4017 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4020 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
4021 callback->awcb_done(zio, buf, callback->awcb_private);
4023 kmem_free(callback, sizeof (arc_write_callback_t));
4027 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4028 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4029 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4030 arc_done_func_t *done, void *private, zio_priority_t priority,
4031 int zio_flags, const zbookmark_phys_t *zb)
4033 arc_buf_hdr_t *hdr = buf->b_hdr;
4034 arc_write_callback_t *callback;
4037 ASSERT(ready != NULL);
4038 ASSERT(done != NULL);
4039 ASSERT(!HDR_IO_ERROR(hdr));
4040 ASSERT((hdr->b_flags & ARC_FLAG_IO_IN_PROGRESS) == 0);
4041 ASSERT(hdr->b_acb == NULL);
4043 hdr->b_flags |= ARC_FLAG_L2CACHE;
4045 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4046 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4047 callback->awcb_ready = ready;
4048 callback->awcb_physdone = physdone;
4049 callback->awcb_done = done;
4050 callback->awcb_private = private;
4051 callback->awcb_buf = buf;
4053 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4054 arc_write_ready, arc_write_physdone, arc_write_done, callback,
4055 priority, zio_flags, zb);
4061 arc_memory_throttle(uint64_t reserve, uint64_t txg)
4064 uint64_t available_memory = ptob(freemem);
4065 static uint64_t page_load = 0;
4066 static uint64_t last_txg = 0;
4068 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4070 MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4073 if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4076 if (txg > last_txg) {
4081 * If we are in pageout, we know that memory is already tight,
4082 * the arc is already going to be evicting, so we just want to
4083 * continue to let page writes occur as quickly as possible.
4085 if (curproc == pageproc) {
4086 if (page_load > MAX(ptob(minfree), available_memory) / 4)
4087 return (SET_ERROR(ERESTART));
4088 /* Note: reserve is inflated, so we deflate */
4089 page_load += reserve / 8;
4091 } else if (page_load > 0 && arc_reclaim_needed()) {
4092 /* memory is low, delay before restarting */
4093 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4094 return (SET_ERROR(EAGAIN));
4102 arc_tempreserve_clear(uint64_t reserve)
4104 atomic_add_64(&arc_tempreserve, -reserve);
4105 ASSERT((int64_t)arc_tempreserve >= 0);
4109 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4114 if (reserve > arc_c/4 && !arc_no_grow) {
4115 arc_c = MIN(arc_c_max, reserve * 4);
4116 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4118 if (reserve > arc_c)
4119 return (SET_ERROR(ENOMEM));
4122 * Don't count loaned bufs as in flight dirty data to prevent long
4123 * network delays from blocking transactions that are ready to be
4124 * assigned to a txg.
4126 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4129 * Writes will, almost always, require additional memory allocations
4130 * in order to compress/encrypt/etc the data. We therefore need to
4131 * make sure that there is sufficient available memory for this.
4133 error = arc_memory_throttle(reserve, txg);
4138 * Throttle writes when the amount of dirty data in the cache
4139 * gets too large. We try to keep the cache less than half full
4140 * of dirty blocks so that our sync times don't grow too large.
4141 * Note: if two requests come in concurrently, we might let them
4142 * both succeed, when one of them should fail. Not a huge deal.
4145 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4146 anon_size > arc_c / 4) {
4147 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4148 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4149 arc_tempreserve>>10,
4150 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4151 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4152 reserve>>10, arc_c>>10);
4153 return (SET_ERROR(ERESTART));
4155 atomic_add_64(&arc_tempreserve, reserve);
4159 static kmutex_t arc_lowmem_lock;
4161 static eventhandler_tag arc_event_lowmem = NULL;
4164 arc_lowmem(void *arg __unused, int howto __unused)
4167 /* Serialize access via arc_lowmem_lock. */
4168 mutex_enter(&arc_lowmem_lock);
4169 mutex_enter(&arc_reclaim_thr_lock);
4171 DTRACE_PROBE(arc__needfree);
4172 cv_signal(&arc_reclaim_thr_cv);
4175 * It is unsafe to block here in arbitrary threads, because we can come
4176 * here from ARC itself and may hold ARC locks and thus risk a deadlock
4177 * with ARC reclaim thread.
4179 if (curproc == pageproc) {
4181 msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4183 mutex_exit(&arc_reclaim_thr_lock);
4184 mutex_exit(&arc_lowmem_lock);
4191 int i, prefetch_tunable_set = 0;
4193 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4194 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4195 mutex_init(&arc_lowmem_lock, NULL, MUTEX_DEFAULT, NULL);
4197 /* Convert seconds to clock ticks */
4198 arc_min_prefetch_lifespan = 1 * hz;
4200 /* Start out with 1/8 of all memory */
4201 arc_c = kmem_size() / 8;
4206 * On architectures where the physical memory can be larger
4207 * than the addressable space (intel in 32-bit mode), we may
4208 * need to limit the cache to 1/8 of VM size.
4210 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4213 /* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4214 arc_c_min = MAX(arc_c / 4, 16 << 20);
4215 /* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4216 if (arc_c * 8 >= 1 << 30)
4217 arc_c_max = (arc_c * 8) - (1 << 30);
4219 arc_c_max = arc_c_min;
4220 arc_c_max = MAX(arc_c * 5, arc_c_max);
4224 * Allow the tunables to override our calculations if they are
4225 * reasonable (ie. over 16MB)
4227 if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
4228 arc_c_max = zfs_arc_max;
4229 if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
4230 arc_c_min = zfs_arc_min;
4234 arc_p = (arc_c >> 1);
4236 /* limit meta-data to 1/4 of the arc capacity */
4237 arc_meta_limit = arc_c_max / 4;
4239 /* Allow the tunable to override if it is reasonable */
4240 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4241 arc_meta_limit = zfs_arc_meta_limit;
4243 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4244 arc_c_min = arc_meta_limit / 2;
4246 if (zfs_arc_meta_min > 0) {
4247 arc_meta_min = zfs_arc_meta_min;
4249 arc_meta_min = arc_c_min / 2;
4252 if (zfs_arc_grow_retry > 0)
4253 arc_grow_retry = zfs_arc_grow_retry;
4255 if (zfs_arc_shrink_shift > 0)
4256 arc_shrink_shift = zfs_arc_shrink_shift;
4258 if (zfs_arc_p_min_shift > 0)
4259 arc_p_min_shift = zfs_arc_p_min_shift;
4261 /* if kmem_flags are set, lets try to use less memory */
4262 if (kmem_debugging())
4264 if (arc_c < arc_c_min)
4267 zfs_arc_min = arc_c_min;
4268 zfs_arc_max = arc_c_max;
4270 arc_anon = &ARC_anon;
4272 arc_mru_ghost = &ARC_mru_ghost;
4274 arc_mfu_ghost = &ARC_mfu_ghost;
4275 arc_l2c_only = &ARC_l2c_only;
4278 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4279 mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4280 NULL, MUTEX_DEFAULT, NULL);
4281 mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4282 NULL, MUTEX_DEFAULT, NULL);
4283 mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4284 NULL, MUTEX_DEFAULT, NULL);
4285 mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4286 NULL, MUTEX_DEFAULT, NULL);
4287 mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4288 NULL, MUTEX_DEFAULT, NULL);
4289 mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4290 NULL, MUTEX_DEFAULT, NULL);
4292 list_create(&arc_mru->arcs_lists[i],
4293 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4294 list_create(&arc_mru_ghost->arcs_lists[i],
4295 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4296 list_create(&arc_mfu->arcs_lists[i],
4297 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4298 list_create(&arc_mfu_ghost->arcs_lists[i],
4299 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4300 list_create(&arc_mfu_ghost->arcs_lists[i],
4301 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4302 list_create(&arc_l2c_only->arcs_lists[i],
4303 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4308 arc_thread_exit = 0;
4309 arc_eviction_list = NULL;
4310 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4311 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4313 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4314 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4316 if (arc_ksp != NULL) {
4317 arc_ksp->ks_data = &arc_stats;
4318 kstat_install(arc_ksp);
4321 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
4322 TS_RUN, minclsyspri);
4325 arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
4326 EVENTHANDLER_PRI_FIRST);
4333 * Calculate maximum amount of dirty data per pool.
4335 * If it has been set by /etc/system, take that.
4336 * Otherwise, use a percentage of physical memory defined by
4337 * zfs_dirty_data_max_percent (default 10%) with a cap at
4338 * zfs_dirty_data_max_max (default 4GB).
4340 if (zfs_dirty_data_max == 0) {
4341 zfs_dirty_data_max = ptob(physmem) *
4342 zfs_dirty_data_max_percent / 100;
4343 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4344 zfs_dirty_data_max_max);
4348 if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
4349 prefetch_tunable_set = 1;
4352 if (prefetch_tunable_set == 0) {
4353 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
4355 printf(" add \"vfs.zfs.prefetch_disable=0\" "
4356 "to /boot/loader.conf.\n");
4357 zfs_prefetch_disable = 1;
4360 if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
4361 prefetch_tunable_set == 0) {
4362 printf("ZFS NOTICE: Prefetch is disabled by default if less "
4363 "than 4GB of RAM is present;\n"
4364 " to enable, add \"vfs.zfs.prefetch_disable=0\" "
4365 "to /boot/loader.conf.\n");
4366 zfs_prefetch_disable = 1;
4369 /* Warn about ZFS memory and address space requirements. */
4370 if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
4371 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
4372 "expect unstable behavior.\n");
4374 if (kmem_size() < 512 * (1 << 20)) {
4375 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
4376 "expect unstable behavior.\n");
4377 printf(" Consider tuning vm.kmem_size and "
4378 "vm.kmem_size_max\n");
4379 printf(" in /boot/loader.conf.\n");
4389 mutex_enter(&arc_reclaim_thr_lock);
4390 arc_thread_exit = 1;
4391 cv_signal(&arc_reclaim_thr_cv);
4392 while (arc_thread_exit != 0)
4393 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4394 mutex_exit(&arc_reclaim_thr_lock);
4400 if (arc_ksp != NULL) {
4401 kstat_delete(arc_ksp);
4405 mutex_destroy(&arc_eviction_mtx);
4406 mutex_destroy(&arc_reclaim_thr_lock);
4407 cv_destroy(&arc_reclaim_thr_cv);
4409 for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4410 list_destroy(&arc_mru->arcs_lists[i]);
4411 list_destroy(&arc_mru_ghost->arcs_lists[i]);
4412 list_destroy(&arc_mfu->arcs_lists[i]);
4413 list_destroy(&arc_mfu_ghost->arcs_lists[i]);
4414 list_destroy(&arc_l2c_only->arcs_lists[i]);
4416 mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
4417 mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
4418 mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
4419 mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
4420 mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
4421 mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
4426 ASSERT(arc_loaned_bytes == 0);
4428 mutex_destroy(&arc_lowmem_lock);
4430 if (arc_event_lowmem != NULL)
4431 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
4438 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4439 * It uses dedicated storage devices to hold cached data, which are populated
4440 * using large infrequent writes. The main role of this cache is to boost
4441 * the performance of random read workloads. The intended L2ARC devices
4442 * include short-stroked disks, solid state disks, and other media with
4443 * substantially faster read latency than disk.
4445 * +-----------------------+
4447 * +-----------------------+
4450 * l2arc_feed_thread() arc_read()
4454 * +---------------+ |
4456 * +---------------+ |
4461 * +-------+ +-------+
4463 * | cache | | cache |
4464 * +-------+ +-------+
4465 * +=========+ .-----.
4466 * : L2ARC : |-_____-|
4467 * : devices : | Disks |
4468 * +=========+ `-_____-'
4470 * Read requests are satisfied from the following sources, in order:
4473 * 2) vdev cache of L2ARC devices
4475 * 4) vdev cache of disks
4478 * Some L2ARC device types exhibit extremely slow write performance.
4479 * To accommodate for this there are some significant differences between
4480 * the L2ARC and traditional cache design:
4482 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4483 * the ARC behave as usual, freeing buffers and placing headers on ghost
4484 * lists. The ARC does not send buffers to the L2ARC during eviction as
4485 * this would add inflated write latencies for all ARC memory pressure.
4487 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4488 * It does this by periodically scanning buffers from the eviction-end of
4489 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4490 * not already there. It scans until a headroom of buffers is satisfied,
4491 * which itself is a buffer for ARC eviction. If a compressible buffer is
4492 * found during scanning and selected for writing to an L2ARC device, we
4493 * temporarily boost scanning headroom during the next scan cycle to make
4494 * sure we adapt to compression effects (which might significantly reduce
4495 * the data volume we write to L2ARC). The thread that does this is
4496 * l2arc_feed_thread(), illustrated below; example sizes are included to
4497 * provide a better sense of ratio than this diagram:
4500 * +---------------------+----------+
4501 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4502 * +---------------------+----------+ | o L2ARC eligible
4503 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4504 * +---------------------+----------+ |
4505 * 15.9 Gbytes ^ 32 Mbytes |
4507 * l2arc_feed_thread()
4509 * l2arc write hand <--[oooo]--'
4513 * +==============================+
4514 * L2ARC dev |####|#|###|###| |####| ... |
4515 * +==============================+
4518 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4519 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4520 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4521 * safe to say that this is an uncommon case, since buffers at the end of
4522 * the ARC lists have moved there due to inactivity.
4524 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4525 * then the L2ARC simply misses copying some buffers. This serves as a
4526 * pressure valve to prevent heavy read workloads from both stalling the ARC
4527 * with waits and clogging the L2ARC with writes. This also helps prevent
4528 * the potential for the L2ARC to churn if it attempts to cache content too
4529 * quickly, such as during backups of the entire pool.
4531 * 5. After system boot and before the ARC has filled main memory, there are
4532 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4533 * lists can remain mostly static. Instead of searching from tail of these
4534 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4535 * for eligible buffers, greatly increasing its chance of finding them.
4537 * The L2ARC device write speed is also boosted during this time so that
4538 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4539 * there are no L2ARC reads, and no fear of degrading read performance
4540 * through increased writes.
4542 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4543 * the vdev queue can aggregate them into larger and fewer writes. Each
4544 * device is written to in a rotor fashion, sweeping writes through
4545 * available space then repeating.
4547 * 7. The L2ARC does not store dirty content. It never needs to flush
4548 * write buffers back to disk based storage.
4550 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4551 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4553 * The performance of the L2ARC can be tweaked by a number of tunables, which
4554 * may be necessary for different workloads:
4556 * l2arc_write_max max write bytes per interval
4557 * l2arc_write_boost extra write bytes during device warmup
4558 * l2arc_noprefetch skip caching prefetched buffers
4559 * l2arc_headroom number of max device writes to precache
4560 * l2arc_headroom_boost when we find compressed buffers during ARC
4561 * scanning, we multiply headroom by this
4562 * percentage factor for the next scan cycle,
4563 * since more compressed buffers are likely to
4565 * l2arc_feed_secs seconds between L2ARC writing
4567 * Tunables may be removed or added as future performance improvements are
4568 * integrated, and also may become zpool properties.
4570 * There are three key functions that control how the L2ARC warms up:
4572 * l2arc_write_eligible() check if a buffer is eligible to cache
4573 * l2arc_write_size() calculate how much to write
4574 * l2arc_write_interval() calculate sleep delay between writes
4576 * These three functions determine what to write, how much, and how quickly
4581 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
4584 * A buffer is *not* eligible for the L2ARC if it:
4585 * 1. belongs to a different spa.
4586 * 2. is already cached on the L2ARC.
4587 * 3. has an I/O in progress (it may be an incomplete read).
4588 * 4. is flagged not eligible (zfs property).
4590 if (hdr->b_spa != spa_guid) {
4591 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
4594 if (hdr->b_l2hdr != NULL) {
4595 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
4598 if (HDR_IO_IN_PROGRESS(hdr)) {
4599 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
4602 if (!HDR_L2CACHE(hdr)) {
4603 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
4611 l2arc_write_size(void)
4616 * Make sure our globals have meaningful values in case the user
4619 size = l2arc_write_max;
4621 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4622 "be greater than zero, resetting it to the default (%d)",
4624 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4627 if (arc_warm == B_FALSE)
4628 size += l2arc_write_boost;
4635 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4637 clock_t interval, next, now;
4640 * If the ARC lists are busy, increase our write rate; if the
4641 * lists are stale, idle back. This is achieved by checking
4642 * how much we previously wrote - if it was more than half of
4643 * what we wanted, schedule the next write much sooner.
4645 if (l2arc_feed_again && wrote > (wanted / 2))
4646 interval = (hz * l2arc_feed_min_ms) / 1000;
4648 interval = hz * l2arc_feed_secs;
4650 now = ddi_get_lbolt();
4651 next = MAX(now, MIN(now + interval, began + interval));
4657 l2arc_hdr_stat_add(void)
4659 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4660 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4664 l2arc_hdr_stat_remove(void)
4666 ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4667 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4671 * Cycle through L2ARC devices. This is how L2ARC load balances.
4672 * If a device is returned, this also returns holding the spa config lock.
4674 static l2arc_dev_t *
4675 l2arc_dev_get_next(void)
4677 l2arc_dev_t *first, *next = NULL;
4680 * Lock out the removal of spas (spa_namespace_lock), then removal
4681 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4682 * both locks will be dropped and a spa config lock held instead.
4684 mutex_enter(&spa_namespace_lock);
4685 mutex_enter(&l2arc_dev_mtx);
4687 /* if there are no vdevs, there is nothing to do */
4688 if (l2arc_ndev == 0)
4692 next = l2arc_dev_last;
4694 /* loop around the list looking for a non-faulted vdev */
4696 next = list_head(l2arc_dev_list);
4698 next = list_next(l2arc_dev_list, next);
4700 next = list_head(l2arc_dev_list);
4703 /* if we have come back to the start, bail out */
4706 else if (next == first)
4709 } while (vdev_is_dead(next->l2ad_vdev));
4711 /* if we were unable to find any usable vdevs, return NULL */
4712 if (vdev_is_dead(next->l2ad_vdev))
4715 l2arc_dev_last = next;
4718 mutex_exit(&l2arc_dev_mtx);
4721 * Grab the config lock to prevent the 'next' device from being
4722 * removed while we are writing to it.
4725 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4726 mutex_exit(&spa_namespace_lock);
4732 * Free buffers that were tagged for destruction.
4735 l2arc_do_free_on_write()
4738 l2arc_data_free_t *df, *df_prev;
4740 mutex_enter(&l2arc_free_on_write_mtx);
4741 buflist = l2arc_free_on_write;
4743 for (df = list_tail(buflist); df; df = df_prev) {
4744 df_prev = list_prev(buflist, df);
4745 ASSERT(df->l2df_data != NULL);
4746 ASSERT(df->l2df_func != NULL);
4747 df->l2df_func(df->l2df_data, df->l2df_size);
4748 list_remove(buflist, df);
4749 kmem_free(df, sizeof (l2arc_data_free_t));
4752 mutex_exit(&l2arc_free_on_write_mtx);
4756 * A write to a cache device has completed. Update all headers to allow
4757 * reads from these buffers to begin.
4760 l2arc_write_done(zio_t *zio)
4762 l2arc_write_callback_t *cb;
4765 arc_buf_hdr_t *head, *hdr, *hdr_prev;
4766 l2arc_buf_hdr_t *abl2;
4767 kmutex_t *hash_lock;
4768 int64_t bytes_dropped = 0;
4770 cb = zio->io_private;
4772 dev = cb->l2wcb_dev;
4773 ASSERT(dev != NULL);
4774 head = cb->l2wcb_head;
4775 ASSERT(head != NULL);
4776 buflist = dev->l2ad_buflist;
4777 ASSERT(buflist != NULL);
4778 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4779 l2arc_write_callback_t *, cb);
4781 if (zio->io_error != 0)
4782 ARCSTAT_BUMP(arcstat_l2_writes_error);
4784 mutex_enter(&l2arc_buflist_mtx);
4787 * All writes completed, or an error was hit.
4789 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
4790 hdr_prev = list_prev(buflist, hdr);
4791 abl2 = hdr->b_l2hdr;
4794 * Release the temporary compressed buffer as soon as possible.
4796 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4797 l2arc_release_cdata_buf(hdr);
4799 hash_lock = HDR_LOCK(hdr);
4800 if (!mutex_tryenter(hash_lock)) {
4802 * This buffer misses out. It may be in a stage
4803 * of eviction. Its ARC_L2_WRITING flag will be
4804 * left set, denying reads to this buffer.
4806 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4810 if (zio->io_error != 0) {
4812 * Error - drop L2ARC entry.
4814 list_remove(buflist, hdr);
4815 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4816 bytes_dropped += abl2->b_asize;
4817 hdr->b_l2hdr = NULL;
4818 trim_map_free(abl2->b_dev->l2ad_vdev, abl2->b_daddr,
4820 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4821 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
4825 * Allow ARC to begin reads to this L2ARC entry.
4827 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
4829 mutex_exit(hash_lock);
4832 atomic_inc_64(&l2arc_writes_done);
4833 list_remove(buflist, head);
4834 kmem_cache_free(hdr_cache, head);
4835 mutex_exit(&l2arc_buflist_mtx);
4837 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
4839 l2arc_do_free_on_write();
4841 kmem_free(cb, sizeof (l2arc_write_callback_t));
4845 * A read to a cache device completed. Validate buffer contents before
4846 * handing over to the regular ARC routines.
4849 l2arc_read_done(zio_t *zio)
4851 l2arc_read_callback_t *cb;
4854 kmutex_t *hash_lock;
4857 ASSERT(zio->io_vd != NULL);
4858 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4860 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4862 cb = zio->io_private;
4864 buf = cb->l2rcb_buf;
4865 ASSERT(buf != NULL);
4867 hash_lock = HDR_LOCK(buf->b_hdr);
4868 mutex_enter(hash_lock);
4870 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4873 * If the buffer was compressed, decompress it first.
4875 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4876 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4877 ASSERT(zio->io_data != NULL);
4880 * Check this survived the L2ARC journey.
4882 equal = arc_cksum_equal(buf);
4883 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4884 mutex_exit(hash_lock);
4885 zio->io_private = buf;
4886 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4887 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
4890 mutex_exit(hash_lock);
4892 * Buffer didn't survive caching. Increment stats and
4893 * reissue to the original storage device.
4895 if (zio->io_error != 0) {
4896 ARCSTAT_BUMP(arcstat_l2_io_error);
4898 zio->io_error = SET_ERROR(EIO);
4901 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4904 * If there's no waiter, issue an async i/o to the primary
4905 * storage now. If there *is* a waiter, the caller must
4906 * issue the i/o in a context where it's OK to block.
4908 if (zio->io_waiter == NULL) {
4909 zio_t *pio = zio_unique_parent(zio);
4911 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4913 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4914 buf->b_data, zio->io_size, arc_read_done, buf,
4915 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4919 kmem_free(cb, sizeof (l2arc_read_callback_t));
4923 * This is the list priority from which the L2ARC will search for pages to
4924 * cache. This is used within loops (0..3) to cycle through lists in the
4925 * desired order. This order can have a significant effect on cache
4928 * Currently the metadata lists are hit first, MFU then MRU, followed by
4929 * the data lists. This function returns a locked list, and also returns
4933 l2arc_list_locked(int list_num, kmutex_t **lock)
4935 list_t *list = NULL;
4938 ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
4940 if (list_num < ARC_BUFC_NUMMETADATALISTS) {
4942 list = &arc_mfu->arcs_lists[idx];
4943 *lock = ARCS_LOCK(arc_mfu, idx);
4944 } else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
4945 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4946 list = &arc_mru->arcs_lists[idx];
4947 *lock = ARCS_LOCK(arc_mru, idx);
4948 } else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
4949 ARC_BUFC_NUMDATALISTS)) {
4950 idx = list_num - ARC_BUFC_NUMMETADATALISTS;
4951 list = &arc_mfu->arcs_lists[idx];
4952 *lock = ARCS_LOCK(arc_mfu, idx);
4954 idx = list_num - ARC_BUFC_NUMLISTS;
4955 list = &arc_mru->arcs_lists[idx];
4956 *lock = ARCS_LOCK(arc_mru, idx);
4959 ASSERT(!(MUTEX_HELD(*lock)));
4965 * Evict buffers from the device write hand to the distance specified in
4966 * bytes. This distance may span populated buffers, it may span nothing.
4967 * This is clearing a region on the L2ARC device ready for writing.
4968 * If the 'all' boolean is set, every buffer is evicted.
4971 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4974 l2arc_buf_hdr_t *abl2;
4975 arc_buf_hdr_t *hdr, *hdr_prev;
4976 kmutex_t *hash_lock;
4978 int64_t bytes_evicted = 0;
4980 buflist = dev->l2ad_buflist;
4982 if (buflist == NULL)
4985 if (!all && dev->l2ad_first) {
4987 * This is the first sweep through the device. There is
4993 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4995 * When nearing the end of the device, evict to the end
4996 * before the device write hand jumps to the start.
4998 taddr = dev->l2ad_end;
5000 taddr = dev->l2ad_hand + distance;
5002 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
5003 uint64_t, taddr, boolean_t, all);
5006 mutex_enter(&l2arc_buflist_mtx);
5007 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
5008 hdr_prev = list_prev(buflist, hdr);
5010 hash_lock = HDR_LOCK(hdr);
5011 if (!mutex_tryenter(hash_lock)) {
5013 * Missed the hash lock. Retry.
5015 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
5016 mutex_exit(&l2arc_buflist_mtx);
5017 mutex_enter(hash_lock);
5018 mutex_exit(hash_lock);
5022 if (HDR_L2_WRITE_HEAD(hdr)) {
5024 * We hit a write head node. Leave it for
5025 * l2arc_write_done().
5027 list_remove(buflist, hdr);
5028 mutex_exit(hash_lock);
5032 if (!all && hdr->b_l2hdr != NULL &&
5033 (hdr->b_l2hdr->b_daddr > taddr ||
5034 hdr->b_l2hdr->b_daddr < dev->l2ad_hand)) {
5036 * We've evicted to the target address,
5037 * or the end of the device.
5039 mutex_exit(hash_lock);
5043 if (HDR_FREE_IN_PROGRESS(hdr)) {
5045 * Already on the path to destruction.
5047 mutex_exit(hash_lock);
5051 if (hdr->b_state == arc_l2c_only) {
5052 ASSERT(!HDR_L2_READING(hdr));
5054 * This doesn't exist in the ARC. Destroy.
5055 * arc_hdr_destroy() will call list_remove()
5056 * and decrement arcstat_l2_size.
5058 arc_change_state(arc_anon, hdr, hash_lock);
5059 arc_hdr_destroy(hdr);
5062 * Invalidate issued or about to be issued
5063 * reads, since we may be about to write
5064 * over this location.
5066 if (HDR_L2_READING(hdr)) {
5067 ARCSTAT_BUMP(arcstat_l2_evict_reading);
5068 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
5072 * Tell ARC this no longer exists in L2ARC.
5074 if (hdr->b_l2hdr != NULL) {
5075 abl2 = hdr->b_l2hdr;
5076 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
5077 bytes_evicted += abl2->b_asize;
5078 hdr->b_l2hdr = NULL;
5080 * We are destroying l2hdr, so ensure that
5081 * its compressed buffer, if any, is not leaked.
5083 ASSERT(abl2->b_tmp_cdata == NULL);
5084 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
5085 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5087 list_remove(buflist, hdr);
5090 * This may have been leftover after a
5093 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5095 mutex_exit(hash_lock);
5097 mutex_exit(&l2arc_buflist_mtx);
5099 vdev_space_update(dev->l2ad_vdev, -bytes_evicted, 0, 0);
5100 dev->l2ad_evict = taddr;
5104 * Find and write ARC buffers to the L2ARC device.
5106 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
5107 * for reading until they have completed writing.
5108 * The headroom_boost is an in-out parameter used to maintain headroom boost
5109 * state between calls to this function.
5111 * Returns the number of bytes actually written (which may be smaller than
5112 * the delta by which the device hand has changed due to alignment).
5115 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5116 boolean_t *headroom_boost)
5118 arc_buf_hdr_t *hdr, *hdr_prev, *head;
5120 uint64_t write_asize, write_sz, headroom, buf_compress_minsz;
5122 kmutex_t *list_lock;
5124 l2arc_write_callback_t *cb;
5126 uint64_t guid = spa_load_guid(spa);
5127 const boolean_t do_headroom_boost = *headroom_boost;
5130 ASSERT(dev->l2ad_vdev != NULL);
5132 /* Lower the flag now, we might want to raise it again later. */
5133 *headroom_boost = B_FALSE;
5136 write_sz = write_asize = 0;
5138 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
5139 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
5141 ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
5143 * We will want to try to compress buffers that are at least 2x the
5144 * device sector size.
5146 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5149 * Copy buffers for L2ARC writing.
5151 mutex_enter(&l2arc_buflist_mtx);
5152 for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
5153 uint64_t passed_sz = 0;
5155 list = l2arc_list_locked(try, &list_lock);
5156 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
5159 * L2ARC fast warmup.
5161 * Until the ARC is warm and starts to evict, read from the
5162 * head of the ARC lists rather than the tail.
5164 if (arc_warm == B_FALSE)
5165 hdr = list_head(list);
5167 hdr = list_tail(list);
5169 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
5171 headroom = target_sz * l2arc_headroom * 2 / ARC_BUFC_NUMLISTS;
5172 if (do_headroom_boost)
5173 headroom = (headroom * l2arc_headroom_boost) / 100;
5175 for (; hdr; hdr = hdr_prev) {
5176 l2arc_buf_hdr_t *l2hdr;
5177 kmutex_t *hash_lock;
5181 if (arc_warm == B_FALSE)
5182 hdr_prev = list_next(list, hdr);
5184 hdr_prev = list_prev(list, hdr);
5185 ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
5187 hash_lock = HDR_LOCK(hdr);
5188 if (!mutex_tryenter(hash_lock)) {
5189 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5191 * Skip this buffer rather than waiting.
5196 passed_sz += hdr->b_size;
5197 if (passed_sz > headroom) {
5201 mutex_exit(hash_lock);
5202 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5206 if (!l2arc_write_eligible(guid, hdr)) {
5207 mutex_exit(hash_lock);
5212 * Assume that the buffer is not going to be compressed
5213 * and could take more space on disk because of a larger
5216 buf_sz = hdr->b_size;
5217 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5219 if ((write_asize + buf_a_sz) > target_sz) {
5221 mutex_exit(hash_lock);
5222 ARCSTAT_BUMP(arcstat_l2_write_full);
5228 * Insert a dummy header on the buflist so
5229 * l2arc_write_done() can find where the
5230 * write buffers begin without searching.
5232 list_insert_head(dev->l2ad_buflist, head);
5235 sizeof (l2arc_write_callback_t), KM_SLEEP);
5236 cb->l2wcb_dev = dev;
5237 cb->l2wcb_head = head;
5238 pio = zio_root(spa, l2arc_write_done, cb,
5240 ARCSTAT_BUMP(arcstat_l2_write_pios);
5244 * Create and add a new L2ARC header.
5246 l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
5248 hdr->b_flags |= ARC_FLAG_L2_WRITING;
5251 * Temporarily stash the data buffer in b_tmp_cdata.
5252 * The subsequent write step will pick it up from
5253 * there. This is because can't access hdr->b_buf
5254 * without holding the hash_lock, which we in turn
5255 * can't access without holding the ARC list locks
5256 * (which we want to avoid during compression/writing).
5258 l2hdr->b_compress = ZIO_COMPRESS_OFF;
5259 l2hdr->b_asize = hdr->b_size;
5260 l2hdr->b_tmp_cdata = hdr->b_buf->b_data;
5262 hdr->b_l2hdr = l2hdr;
5264 list_insert_head(dev->l2ad_buflist, hdr);
5267 * Compute and store the buffer cksum before
5268 * writing. On debug the cksum is verified first.
5270 arc_cksum_verify(hdr->b_buf);
5271 arc_cksum_compute(hdr->b_buf, B_TRUE);
5273 mutex_exit(hash_lock);
5276 write_asize += buf_a_sz;
5279 mutex_exit(list_lock);
5285 /* No buffers selected for writing? */
5288 mutex_exit(&l2arc_buflist_mtx);
5289 kmem_cache_free(hdr_cache, head);
5294 * Note that elsewhere in this file arcstat_l2_asize
5295 * and the used space on l2ad_vdev are updated using b_asize,
5296 * which is not necessarily rounded up to the device block size.
5297 * Too keep accounting consistent we do the same here as well:
5298 * stats_size accumulates the sum of b_asize of the written buffers,
5299 * while write_asize accumulates the sum of b_asize rounded up
5300 * to the device block size.
5301 * The latter sum is used only to validate the corectness of the code.
5303 uint64_t stats_size = 0;
5307 * Now start writing the buffers. We're starting at the write head
5308 * and work backwards, retracing the course of the buffer selector
5311 for (hdr = list_prev(dev->l2ad_buflist, head); hdr;
5312 hdr = list_prev(dev->l2ad_buflist, hdr)) {
5313 l2arc_buf_hdr_t *l2hdr;
5317 * We shouldn't need to lock the buffer here, since we flagged
5318 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
5319 * take care to only access its L2 cache parameters. In
5320 * particular, hdr->b_buf may be invalid by now due to
5323 l2hdr = hdr->b_l2hdr;
5324 l2hdr->b_daddr = dev->l2ad_hand;
5326 if ((hdr->b_flags & ARC_FLAG_L2COMPRESS) &&
5327 l2hdr->b_asize >= buf_compress_minsz) {
5328 if (l2arc_compress_buf(l2hdr)) {
5330 * If compression succeeded, enable headroom
5331 * boost on the next scan cycle.
5333 *headroom_boost = B_TRUE;
5338 * Pick up the buffer data we had previously stashed away
5339 * (and now potentially also compressed).
5341 buf_data = l2hdr->b_tmp_cdata;
5342 buf_sz = l2hdr->b_asize;
5345 * If the data has not been compressed, then clear b_tmp_cdata
5346 * to make sure that it points only to a temporary compression
5349 if (!L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress))
5350 l2hdr->b_tmp_cdata = NULL;
5352 /* Compression may have squashed the buffer to zero length. */
5356 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5357 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5358 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5359 ZIO_FLAG_CANFAIL, B_FALSE);
5361 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5363 (void) zio_nowait(wzio);
5365 stats_size += buf_sz;
5367 * Keep the clock hand suitably device-aligned.
5369 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5370 write_asize += buf_a_sz;
5371 dev->l2ad_hand += buf_a_sz;
5375 mutex_exit(&l2arc_buflist_mtx);
5377 ASSERT3U(write_asize, <=, target_sz);
5378 ARCSTAT_BUMP(arcstat_l2_writes_sent);
5379 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5380 ARCSTAT_INCR(arcstat_l2_size, write_sz);
5381 ARCSTAT_INCR(arcstat_l2_asize, stats_size);
5382 vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
5385 * Bump device hand to the device start if it is approaching the end.
5386 * l2arc_evict() will already have evicted ahead for this case.
5388 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5389 dev->l2ad_hand = dev->l2ad_start;
5390 dev->l2ad_evict = dev->l2ad_start;
5391 dev->l2ad_first = B_FALSE;
5394 dev->l2ad_writing = B_TRUE;
5395 (void) zio_wait(pio);
5396 dev->l2ad_writing = B_FALSE;
5398 return (write_asize);
5402 * Compresses an L2ARC buffer.
5403 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5404 * size in l2hdr->b_asize. This routine tries to compress the data and
5405 * depending on the compression result there are three possible outcomes:
5406 * *) The buffer was incompressible. The original l2hdr contents were left
5407 * untouched and are ready for writing to an L2 device.
5408 * *) The buffer was all-zeros, so there is no need to write it to an L2
5409 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5410 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5411 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5412 * data buffer which holds the compressed data to be written, and b_asize
5413 * tells us how much data there is. b_compress is set to the appropriate
5414 * compression algorithm. Once writing is done, invoke
5415 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5417 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5418 * buffer was incompressible).
5421 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5424 size_t csize, len, rounded;
5426 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5427 ASSERT(l2hdr->b_tmp_cdata != NULL);
5429 len = l2hdr->b_asize;
5430 cdata = zio_data_buf_alloc(len);
5431 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5432 cdata, l2hdr->b_asize);
5435 /* zero block, indicate that there's nothing to write */
5436 zio_data_buf_free(cdata, len);
5437 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5439 l2hdr->b_tmp_cdata = NULL;
5440 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5444 rounded = P2ROUNDUP(csize,
5445 (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
5446 if (rounded < len) {
5448 * Compression succeeded, we'll keep the cdata around for
5449 * writing and release it afterwards.
5451 if (rounded > csize) {
5452 bzero((char *)cdata + csize, rounded - csize);
5455 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5456 l2hdr->b_asize = csize;
5457 l2hdr->b_tmp_cdata = cdata;
5458 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5462 * Compression failed, release the compressed buffer.
5463 * l2hdr will be left unmodified.
5465 zio_data_buf_free(cdata, len);
5466 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5472 * Decompresses a zio read back from an l2arc device. On success, the
5473 * underlying zio's io_data buffer is overwritten by the uncompressed
5474 * version. On decompression error (corrupt compressed stream), the
5475 * zio->io_error value is set to signal an I/O error.
5477 * Please note that the compressed data stream is not checksummed, so
5478 * if the underlying device is experiencing data corruption, we may feed
5479 * corrupt data to the decompressor, so the decompressor needs to be
5480 * able to handle this situation (LZ4 does).
5483 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5485 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5487 if (zio->io_error != 0) {
5489 * An io error has occured, just restore the original io
5490 * size in preparation for a main pool read.
5492 zio->io_orig_size = zio->io_size = hdr->b_size;
5496 if (c == ZIO_COMPRESS_EMPTY) {
5498 * An empty buffer results in a null zio, which means we
5499 * need to fill its io_data after we're done restoring the
5500 * buffer's contents.
5502 ASSERT(hdr->b_buf != NULL);
5503 bzero(hdr->b_buf->b_data, hdr->b_size);
5504 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5506 ASSERT(zio->io_data != NULL);
5508 * We copy the compressed data from the start of the arc buffer
5509 * (the zio_read will have pulled in only what we need, the
5510 * rest is garbage which we will overwrite at decompression)
5511 * and then decompress back to the ARC data buffer. This way we
5512 * can minimize copying by simply decompressing back over the
5513 * original compressed data (rather than decompressing to an
5514 * aux buffer and then copying back the uncompressed buffer,
5515 * which is likely to be much larger).
5520 csize = zio->io_size;
5521 cdata = zio_data_buf_alloc(csize);
5522 bcopy(zio->io_data, cdata, csize);
5523 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5525 zio->io_error = EIO;
5526 zio_data_buf_free(cdata, csize);
5529 /* Restore the expected uncompressed IO size. */
5530 zio->io_orig_size = zio->io_size = hdr->b_size;
5534 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5535 * This buffer serves as a temporary holder of compressed data while
5536 * the buffer entry is being written to an l2arc device. Once that is
5537 * done, we can dispose of it.
5540 l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
5542 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
5544 ASSERT(L2ARC_IS_VALID_COMPRESS(l2hdr->b_compress));
5545 if (l2hdr->b_compress != ZIO_COMPRESS_EMPTY) {
5547 * If the data was compressed, then we've allocated a
5548 * temporary buffer for it, so now we need to release it.
5550 ASSERT(l2hdr->b_tmp_cdata != NULL);
5551 zio_data_buf_free(l2hdr->b_tmp_cdata, hdr->b_size);
5552 l2hdr->b_tmp_cdata = NULL;
5554 ASSERT(l2hdr->b_tmp_cdata == NULL);
5559 * This thread feeds the L2ARC at regular intervals. This is the beating
5560 * heart of the L2ARC.
5563 l2arc_feed_thread(void *dummy __unused)
5568 uint64_t size, wrote;
5569 clock_t begin, next = ddi_get_lbolt();
5570 boolean_t headroom_boost = B_FALSE;
5572 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5574 mutex_enter(&l2arc_feed_thr_lock);
5576 while (l2arc_thread_exit == 0) {
5577 CALLB_CPR_SAFE_BEGIN(&cpr);
5578 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
5579 next - ddi_get_lbolt());
5580 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5581 next = ddi_get_lbolt() + hz;
5584 * Quick check for L2ARC devices.
5586 mutex_enter(&l2arc_dev_mtx);
5587 if (l2arc_ndev == 0) {
5588 mutex_exit(&l2arc_dev_mtx);
5591 mutex_exit(&l2arc_dev_mtx);
5592 begin = ddi_get_lbolt();
5595 * This selects the next l2arc device to write to, and in
5596 * doing so the next spa to feed from: dev->l2ad_spa. This
5597 * will return NULL if there are now no l2arc devices or if
5598 * they are all faulted.
5600 * If a device is returned, its spa's config lock is also
5601 * held to prevent device removal. l2arc_dev_get_next()
5602 * will grab and release l2arc_dev_mtx.
5604 if ((dev = l2arc_dev_get_next()) == NULL)
5607 spa = dev->l2ad_spa;
5608 ASSERT(spa != NULL);
5611 * If the pool is read-only then force the feed thread to
5612 * sleep a little longer.
5614 if (!spa_writeable(spa)) {
5615 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5616 spa_config_exit(spa, SCL_L2ARC, dev);
5621 * Avoid contributing to memory pressure.
5623 if (arc_reclaim_needed()) {
5624 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5625 spa_config_exit(spa, SCL_L2ARC, dev);
5629 ARCSTAT_BUMP(arcstat_l2_feeds);
5631 size = l2arc_write_size();
5634 * Evict L2ARC buffers that will be overwritten.
5636 l2arc_evict(dev, size, B_FALSE);
5639 * Write ARC buffers.
5641 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5644 * Calculate interval between writes.
5646 next = l2arc_write_interval(begin, size, wrote);
5647 spa_config_exit(spa, SCL_L2ARC, dev);
5650 l2arc_thread_exit = 0;
5651 cv_broadcast(&l2arc_feed_thr_cv);
5652 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5657 l2arc_vdev_present(vdev_t *vd)
5661 mutex_enter(&l2arc_dev_mtx);
5662 for (dev = list_head(l2arc_dev_list); dev != NULL;
5663 dev = list_next(l2arc_dev_list, dev)) {
5664 if (dev->l2ad_vdev == vd)
5667 mutex_exit(&l2arc_dev_mtx);
5669 return (dev != NULL);
5673 * Add a vdev for use by the L2ARC. By this point the spa has already
5674 * validated the vdev and opened it.
5677 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5679 l2arc_dev_t *adddev;
5681 ASSERT(!l2arc_vdev_present(vd));
5683 vdev_ashift_optimize(vd);
5686 * Create a new l2arc device entry.
5688 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5689 adddev->l2ad_spa = spa;
5690 adddev->l2ad_vdev = vd;
5691 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5692 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5693 adddev->l2ad_hand = adddev->l2ad_start;
5694 adddev->l2ad_evict = adddev->l2ad_start;
5695 adddev->l2ad_first = B_TRUE;
5696 adddev->l2ad_writing = B_FALSE;
5699 * This is a list of all ARC buffers that are still valid on the
5702 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5703 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5704 offsetof(arc_buf_hdr_t, b_l2node));
5706 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5709 * Add device to global list
5711 mutex_enter(&l2arc_dev_mtx);
5712 list_insert_head(l2arc_dev_list, adddev);
5713 atomic_inc_64(&l2arc_ndev);
5714 mutex_exit(&l2arc_dev_mtx);
5718 * Remove a vdev from the L2ARC.
5721 l2arc_remove_vdev(vdev_t *vd)
5723 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5726 * Find the device by vdev
5728 mutex_enter(&l2arc_dev_mtx);
5729 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5730 nextdev = list_next(l2arc_dev_list, dev);
5731 if (vd == dev->l2ad_vdev) {
5736 ASSERT(remdev != NULL);
5739 * Remove device from global list
5741 list_remove(l2arc_dev_list, remdev);
5742 l2arc_dev_last = NULL; /* may have been invalidated */
5743 atomic_dec_64(&l2arc_ndev);
5744 mutex_exit(&l2arc_dev_mtx);
5747 * Clear all buflists and ARC references. L2ARC device flush.
5749 l2arc_evict(remdev, 0, B_TRUE);
5750 list_destroy(remdev->l2ad_buflist);
5751 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5752 kmem_free(remdev, sizeof (l2arc_dev_t));
5758 l2arc_thread_exit = 0;
5760 l2arc_writes_sent = 0;
5761 l2arc_writes_done = 0;
5763 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5764 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5765 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5766 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5767 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5769 l2arc_dev_list = &L2ARC_dev_list;
5770 l2arc_free_on_write = &L2ARC_free_on_write;
5771 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5772 offsetof(l2arc_dev_t, l2ad_node));
5773 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5774 offsetof(l2arc_data_free_t, l2df_list_node));
5781 * This is called from dmu_fini(), which is called from spa_fini();
5782 * Because of this, we can assume that all l2arc devices have
5783 * already been removed when the pools themselves were removed.
5786 l2arc_do_free_on_write();
5788 mutex_destroy(&l2arc_feed_thr_lock);
5789 cv_destroy(&l2arc_feed_thr_cv);
5790 mutex_destroy(&l2arc_dev_mtx);
5791 mutex_destroy(&l2arc_buflist_mtx);
5792 mutex_destroy(&l2arc_free_on_write_mtx);
5794 list_destroy(l2arc_dev_list);
5795 list_destroy(l2arc_free_on_write);
5801 if (!(spa_mode_global & FWRITE))
5804 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5805 TS_RUN, minclsyspri);
5811 if (!(spa_mode_global & FWRITE))
5814 mutex_enter(&l2arc_feed_thr_lock);
5815 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5816 l2arc_thread_exit = 1;
5817 while (l2arc_thread_exit != 0)
5818 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5819 mutex_exit(&l2arc_feed_thr_lock);