]> git.proxmox.com Git - mirror_zfs.git/blame - module/zfs/arc.c
Fix arc_prune_task use-after-free
[mirror_zfs.git] / module / zfs / arc.c
CommitLineData
34dc7c2f
BB
1/*
2 * CDDL HEADER START
3 *
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.
7 *
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.
12 *
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]
18 *
19 * CDDL HEADER END
20 */
21/*
428870ff 22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
36da08ef
PS
23 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
24 * Copyright (c) 2011, 2015 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
3bec585e 26 * Copyright 2014 Nexenta Systems, Inc. All rights reserved.
34dc7c2f
BB
27 */
28
34dc7c2f
BB
29/*
30 * DVA-based Adjustable Replacement Cache
31 *
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:
36 *
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.
47 *
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.
53 *
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
59 * tight.
60 *
61 * 3. The Megiddo and Modha model assumes a fixed page size. All
d3cc8b15 62 * elements of the cache are therefore exactly the same size. So
34dc7c2f
BB
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
d3cc8b15 66 * 128K bytes). We therefore choose a set of blocks to evict to make
34dc7c2f
BB
67 * space for a cache miss that approximates as closely as possible
68 * the space used by the new block.
69 *
70 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71 * by N. Megiddo & D. Modha, FAST 2003
72 */
73
74/*
75 * The locking model:
76 *
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
d3cc8b15 81 * adjusting the cache use method 2. We therefore provide two
34dc7c2f
BB
82 * types of locks: 1) the hash table lock array, and 2) the
83 * arc list locks.
84 *
5c839890
BC
85 * Buffers do not have their own mutexes, rather they rely on the
86 * hash table mutexes for the bulk of their protection (i.e. most
87 * fields in the arc_buf_hdr_t are protected by these mutexes).
34dc7c2f
BB
88 *
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.
92 *
93 * buf_hash_remove() expects the appropriate hash mutex to be
94 * already held before it is invoked.
95 *
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.
101 *
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
bd089c54 108 * protected from simultaneous callbacks from arc_clear_callback()
34dc7c2f
BB
109 * and arc_do_user_evicts().
110 *
ab26409d
BB
111 * It as also possible to register a callback which is run when the
112 * arc_meta_limit is reached and no buffers can be safely evicted. In
113 * this case the arc user should drop a reference on some arc buffers so
114 * they can be reclaimed and the arc_meta_limit honored. For example,
115 * when using the ZPL each dentry holds a references on a znode. These
116 * dentries must be pruned before the arc buffer holding the znode can
117 * be safely evicted.
118 *
34dc7c2f
BB
119 * Note that the majority of the performance stats are manipulated
120 * with atomic operations.
121 *
b9541d6b 122 * The L2ARC uses the l2ad_mtx on each vdev for the following:
34dc7c2f
BB
123 *
124 * - L2ARC buflist creation
125 * - L2ARC buflist eviction
126 * - L2ARC write completion, which walks L2ARC buflists
127 * - ARC header destruction, as it removes from L2ARC buflists
128 * - ARC header release, as it removes from L2ARC buflists
129 */
130
131#include <sys/spa.h>
132#include <sys/zio.h>
3a17a7a9 133#include <sys/zio_compress.h>
34dc7c2f
BB
134#include <sys/zfs_context.h>
135#include <sys/arc.h>
36da08ef 136#include <sys/refcount.h>
b128c09f 137#include <sys/vdev.h>
9babb374 138#include <sys/vdev_impl.h>
e8b96c60 139#include <sys/dsl_pool.h>
ca0bf58d 140#include <sys/multilist.h>
34dc7c2f
BB
141#ifdef _KERNEL
142#include <sys/vmsystm.h>
143#include <vm/anon.h>
144#include <sys/fs/swapnode.h>
ab26409d 145#include <sys/zpl.h>
aaed7c40 146#include <linux/mm_compat.h>
34dc7c2f
BB
147#endif
148#include <sys/callb.h>
149#include <sys/kstat.h>
570827e1 150#include <sys/dmu_tx.h>
428870ff 151#include <zfs_fletcher.h>
59ec819a 152#include <sys/arc_impl.h>
49ee64e5 153#include <sys/trace_arc.h>
34dc7c2f 154
498877ba
MA
155#ifndef _KERNEL
156/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
157boolean_t arc_watch = B_FALSE;
158#endif
159
ca0bf58d
PS
160static kmutex_t arc_reclaim_lock;
161static kcondvar_t arc_reclaim_thread_cv;
162static boolean_t arc_reclaim_thread_exit;
163static kcondvar_t arc_reclaim_waiters_cv;
164
165static kmutex_t arc_user_evicts_lock;
166static kcondvar_t arc_user_evicts_cv;
167static boolean_t arc_user_evicts_thread_exit;
34dc7c2f 168
e8b96c60 169/*
ca0bf58d
PS
170 * The number of headers to evict in arc_evict_state_impl() before
171 * dropping the sublist lock and evicting from another sublist. A lower
172 * value means we're more likely to evict the "correct" header (i.e. the
173 * oldest header in the arc state), but comes with higher overhead
174 * (i.e. more invocations of arc_evict_state_impl()).
175 */
176int zfs_arc_evict_batch_limit = 10;
177
178/*
179 * The number of sublists used for each of the arc state lists. If this
180 * is not set to a suitable value by the user, it will be configured to
181 * the number of CPUs on the system in arc_init().
e8b96c60 182 */
ca0bf58d 183int zfs_arc_num_sublists_per_state = 0;
e8b96c60 184
34dc7c2f 185/* number of seconds before growing cache again */
ca67b33a 186static int arc_grow_retry = 5;
34dc7c2f 187
ca0bf58d 188/* shift of arc_c for calculating overflow limit in arc_get_data_buf */
ca67b33a 189int zfs_arc_overflow_shift = 8;
62422785 190
728d6ae9
BB
191/* shift of arc_c for calculating both min and max arc_p */
192static int arc_p_min_shift = 4;
193
d164b209 194/* log2(fraction of arc to reclaim) */
ca67b33a 195static int arc_shrink_shift = 7;
d164b209 196
34dc7c2f 197/*
ca67b33a
MA
198 * log2(fraction of ARC which must be free to allow growing).
199 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
200 * when reading a new block into the ARC, we will evict an equal-sized block
201 * from the ARC.
202 *
203 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
204 * we will still not allow it to grow.
34dc7c2f 205 */
ca67b33a 206int arc_no_grow_shift = 5;
bce45ec9 207
49ddb315 208
ca0bf58d
PS
209/*
210 * minimum lifespan of a prefetch block in clock ticks
211 * (initialized in arc_init())
212 */
ca67b33a 213static int arc_min_prefetch_lifespan;
ca0bf58d 214
e8b96c60
MA
215/*
216 * If this percent of memory is free, don't throttle.
217 */
218int arc_lotsfree_percent = 10;
219
34dc7c2f
BB
220static int arc_dead;
221
b128c09f
BB
222/*
223 * The arc has filled available memory and has now warmed up.
224 */
225static boolean_t arc_warm;
226
34dc7c2f
BB
227/*
228 * These tunables are for performance analysis.
229 */
c28b2279
BB
230unsigned long zfs_arc_max = 0;
231unsigned long zfs_arc_min = 0;
232unsigned long zfs_arc_meta_limit = 0;
ca0bf58d 233unsigned long zfs_arc_meta_min = 0;
ca67b33a
MA
234int zfs_arc_grow_retry = 0;
235int zfs_arc_shrink_shift = 0;
728d6ae9 236int zfs_arc_p_min_shift = 0;
ca67b33a
MA
237int zfs_disable_dup_eviction = 0;
238int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
34dc7c2f 239
bc888666 240/*
ca67b33a 241 * These tunables are Linux specific
bc888666 242 */
11f552fa 243unsigned long zfs_arc_sys_free = 0;
ca67b33a
MA
244int zfs_arc_min_prefetch_lifespan = 0;
245int zfs_arc_p_aggressive_disable = 1;
246int zfs_arc_p_dampener_disable = 1;
247int zfs_arc_meta_prune = 10000;
248int zfs_arc_meta_strategy = ARC_STRATEGY_META_BALANCED;
249int zfs_arc_meta_adjust_restarts = 4096;
7e8bddd0 250int zfs_arc_lotsfree_percent = 10;
bc888666 251
34dc7c2f
BB
252/* The 6 states: */
253static arc_state_t ARC_anon;
254static arc_state_t ARC_mru;
255static arc_state_t ARC_mru_ghost;
256static arc_state_t ARC_mfu;
257static arc_state_t ARC_mfu_ghost;
258static arc_state_t ARC_l2c_only;
259
260typedef struct arc_stats {
261 kstat_named_t arcstat_hits;
262 kstat_named_t arcstat_misses;
263 kstat_named_t arcstat_demand_data_hits;
264 kstat_named_t arcstat_demand_data_misses;
265 kstat_named_t arcstat_demand_metadata_hits;
266 kstat_named_t arcstat_demand_metadata_misses;
267 kstat_named_t arcstat_prefetch_data_hits;
268 kstat_named_t arcstat_prefetch_data_misses;
269 kstat_named_t arcstat_prefetch_metadata_hits;
270 kstat_named_t arcstat_prefetch_metadata_misses;
271 kstat_named_t arcstat_mru_hits;
272 kstat_named_t arcstat_mru_ghost_hits;
273 kstat_named_t arcstat_mfu_hits;
274 kstat_named_t arcstat_mfu_ghost_hits;
275 kstat_named_t arcstat_deleted;
e49f1e20
WA
276 /*
277 * Number of buffers that could not be evicted because the hash lock
278 * was held by another thread. The lock may not necessarily be held
279 * by something using the same buffer, since hash locks are shared
280 * by multiple buffers.
281 */
34dc7c2f 282 kstat_named_t arcstat_mutex_miss;
e49f1e20
WA
283 /*
284 * Number of buffers skipped because they have I/O in progress, are
285 * indrect prefetch buffers that have not lived long enough, or are
286 * not from the spa we're trying to evict from.
287 */
34dc7c2f 288 kstat_named_t arcstat_evict_skip;
ca0bf58d
PS
289 /*
290 * Number of times arc_evict_state() was unable to evict enough
291 * buffers to reach its target amount.
292 */
293 kstat_named_t arcstat_evict_not_enough;
428870ff
BB
294 kstat_named_t arcstat_evict_l2_cached;
295 kstat_named_t arcstat_evict_l2_eligible;
296 kstat_named_t arcstat_evict_l2_ineligible;
ca0bf58d 297 kstat_named_t arcstat_evict_l2_skip;
34dc7c2f
BB
298 kstat_named_t arcstat_hash_elements;
299 kstat_named_t arcstat_hash_elements_max;
300 kstat_named_t arcstat_hash_collisions;
301 kstat_named_t arcstat_hash_chains;
302 kstat_named_t arcstat_hash_chain_max;
303 kstat_named_t arcstat_p;
304 kstat_named_t arcstat_c;
305 kstat_named_t arcstat_c_min;
306 kstat_named_t arcstat_c_max;
307 kstat_named_t arcstat_size;
500445c0
PS
308 /*
309 * Number of bytes consumed by internal ARC structures necessary
310 * for tracking purposes; these structures are not actually
311 * backed by ARC buffers. This includes arc_buf_hdr_t structures
312 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
313 * caches), and arc_buf_t structures (allocated via arc_buf_t
314 * cache).
315 */
34dc7c2f 316 kstat_named_t arcstat_hdr_size;
500445c0
PS
317 /*
318 * Number of bytes consumed by ARC buffers of type equal to
319 * ARC_BUFC_DATA. This is generally consumed by buffers backing
320 * on disk user data (e.g. plain file contents).
321 */
d164b209 322 kstat_named_t arcstat_data_size;
500445c0
PS
323 /*
324 * Number of bytes consumed by ARC buffers of type equal to
325 * ARC_BUFC_METADATA. This is generally consumed by buffers
326 * backing on disk data that is used for internal ZFS
327 * structures (e.g. ZAP, dnode, indirect blocks, etc).
328 */
329 kstat_named_t arcstat_metadata_size;
330 /*
331 * Number of bytes consumed by various buffers and structures
332 * not actually backed with ARC buffers. This includes bonus
333 * buffers (allocated directly via zio_buf_* functions),
334 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
335 * cache), and dnode_t structures (allocated via dnode_t cache).
336 */
d164b209 337 kstat_named_t arcstat_other_size;
500445c0
PS
338 /*
339 * Total number of bytes consumed by ARC buffers residing in the
340 * arc_anon state. This includes *all* buffers in the arc_anon
341 * state; e.g. data, metadata, evictable, and unevictable buffers
342 * are all included in this value.
343 */
13be560d 344 kstat_named_t arcstat_anon_size;
500445c0
PS
345 /*
346 * Number of bytes consumed by ARC buffers that meet the
347 * following criteria: backing buffers of type ARC_BUFC_DATA,
348 * residing in the arc_anon state, and are eligible for eviction
349 * (e.g. have no outstanding holds on the buffer).
350 */
351 kstat_named_t arcstat_anon_evictable_data;
352 /*
353 * Number of bytes consumed by ARC buffers that meet the
354 * following criteria: backing buffers of type ARC_BUFC_METADATA,
355 * residing in the arc_anon state, and are eligible for eviction
356 * (e.g. have no outstanding holds on the buffer).
357 */
358 kstat_named_t arcstat_anon_evictable_metadata;
359 /*
360 * Total number of bytes consumed by ARC buffers residing in the
361 * arc_mru state. This includes *all* buffers in the arc_mru
362 * state; e.g. data, metadata, evictable, and unevictable buffers
363 * are all included in this value.
364 */
13be560d 365 kstat_named_t arcstat_mru_size;
500445c0
PS
366 /*
367 * Number of bytes consumed by ARC buffers that meet the
368 * following criteria: backing buffers of type ARC_BUFC_DATA,
369 * residing in the arc_mru state, and are eligible for eviction
370 * (e.g. have no outstanding holds on the buffer).
371 */
372 kstat_named_t arcstat_mru_evictable_data;
373 /*
374 * Number of bytes consumed by ARC buffers that meet the
375 * following criteria: backing buffers of type ARC_BUFC_METADATA,
376 * residing in the arc_mru state, and are eligible for eviction
377 * (e.g. have no outstanding holds on the buffer).
378 */
379 kstat_named_t arcstat_mru_evictable_metadata;
380 /*
381 * Total number of bytes that *would have been* consumed by ARC
382 * buffers in the arc_mru_ghost state. The key thing to note
383 * here, is the fact that this size doesn't actually indicate
384 * RAM consumption. The ghost lists only consist of headers and
385 * don't actually have ARC buffers linked off of these headers.
386 * Thus, *if* the headers had associated ARC buffers, these
387 * buffers *would have* consumed this number of bytes.
388 */
13be560d 389 kstat_named_t arcstat_mru_ghost_size;
500445c0
PS
390 /*
391 * Number of bytes that *would have been* consumed by ARC
392 * buffers that are eligible for eviction, of type
393 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
394 */
395 kstat_named_t arcstat_mru_ghost_evictable_data;
396 /*
397 * Number of bytes that *would have been* consumed by ARC
398 * buffers that are eligible for eviction, of type
399 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
400 */
401 kstat_named_t arcstat_mru_ghost_evictable_metadata;
402 /*
403 * Total number of bytes consumed by ARC buffers residing in the
404 * arc_mfu state. This includes *all* buffers in the arc_mfu
405 * state; e.g. data, metadata, evictable, and unevictable buffers
406 * are all included in this value.
407 */
13be560d 408 kstat_named_t arcstat_mfu_size;
500445c0
PS
409 /*
410 * Number of bytes consumed by ARC buffers that are eligible for
411 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
412 * state.
413 */
414 kstat_named_t arcstat_mfu_evictable_data;
415 /*
416 * Number of bytes consumed by ARC buffers that are eligible for
417 * eviction, of type ARC_BUFC_METADATA, and reside in the
418 * arc_mfu state.
419 */
420 kstat_named_t arcstat_mfu_evictable_metadata;
421 /*
422 * Total number of bytes that *would have been* consumed by ARC
423 * buffers in the arc_mfu_ghost state. See the comment above
424 * arcstat_mru_ghost_size for more details.
425 */
13be560d 426 kstat_named_t arcstat_mfu_ghost_size;
500445c0
PS
427 /*
428 * Number of bytes that *would have been* consumed by ARC
429 * buffers that are eligible for eviction, of type
430 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
431 */
432 kstat_named_t arcstat_mfu_ghost_evictable_data;
433 /*
434 * Number of bytes that *would have been* consumed by ARC
435 * buffers that are eligible for eviction, of type
436 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
437 */
438 kstat_named_t arcstat_mfu_ghost_evictable_metadata;
34dc7c2f
BB
439 kstat_named_t arcstat_l2_hits;
440 kstat_named_t arcstat_l2_misses;
441 kstat_named_t arcstat_l2_feeds;
442 kstat_named_t arcstat_l2_rw_clash;
d164b209
BB
443 kstat_named_t arcstat_l2_read_bytes;
444 kstat_named_t arcstat_l2_write_bytes;
34dc7c2f
BB
445 kstat_named_t arcstat_l2_writes_sent;
446 kstat_named_t arcstat_l2_writes_done;
447 kstat_named_t arcstat_l2_writes_error;
ca0bf58d 448 kstat_named_t arcstat_l2_writes_lock_retry;
8a09d5fd 449 kstat_named_t arcstat_l2_writes_skip_toobig;
34dc7c2f
BB
450 kstat_named_t arcstat_l2_evict_lock_retry;
451 kstat_named_t arcstat_l2_evict_reading;
b9541d6b 452 kstat_named_t arcstat_l2_evict_l1cached;
34dc7c2f 453 kstat_named_t arcstat_l2_free_on_write;
ca0bf58d 454 kstat_named_t arcstat_l2_cdata_free_on_write;
34dc7c2f
BB
455 kstat_named_t arcstat_l2_abort_lowmem;
456 kstat_named_t arcstat_l2_cksum_bad;
457 kstat_named_t arcstat_l2_io_error;
458 kstat_named_t arcstat_l2_size;
3a17a7a9 459 kstat_named_t arcstat_l2_asize;
34dc7c2f 460 kstat_named_t arcstat_l2_hdr_size;
3a17a7a9
SK
461 kstat_named_t arcstat_l2_compress_successes;
462 kstat_named_t arcstat_l2_compress_zeros;
463 kstat_named_t arcstat_l2_compress_failures;
34dc7c2f 464 kstat_named_t arcstat_memory_throttle_count;
1eb5bfa3
GW
465 kstat_named_t arcstat_duplicate_buffers;
466 kstat_named_t arcstat_duplicate_buffers_size;
467 kstat_named_t arcstat_duplicate_reads;
7cb67b45
BB
468 kstat_named_t arcstat_memory_direct_count;
469 kstat_named_t arcstat_memory_indirect_count;
1834f2d8
BB
470 kstat_named_t arcstat_no_grow;
471 kstat_named_t arcstat_tempreserve;
472 kstat_named_t arcstat_loaned_bytes;
ab26409d 473 kstat_named_t arcstat_prune;
1834f2d8
BB
474 kstat_named_t arcstat_meta_used;
475 kstat_named_t arcstat_meta_limit;
476 kstat_named_t arcstat_meta_max;
ca0bf58d 477 kstat_named_t arcstat_meta_min;
7f60329a
MA
478 kstat_named_t arcstat_sync_wait_for_async;
479 kstat_named_t arcstat_demand_hit_predictive_prefetch;
11f552fa
BB
480 kstat_named_t arcstat_need_free;
481 kstat_named_t arcstat_sys_free;
34dc7c2f
BB
482} arc_stats_t;
483
484static arc_stats_t arc_stats = {
485 { "hits", KSTAT_DATA_UINT64 },
486 { "misses", KSTAT_DATA_UINT64 },
487 { "demand_data_hits", KSTAT_DATA_UINT64 },
488 { "demand_data_misses", KSTAT_DATA_UINT64 },
489 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
490 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
491 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
492 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
493 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
494 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
495 { "mru_hits", KSTAT_DATA_UINT64 },
496 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
497 { "mfu_hits", KSTAT_DATA_UINT64 },
498 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
499 { "deleted", KSTAT_DATA_UINT64 },
34dc7c2f
BB
500 { "mutex_miss", KSTAT_DATA_UINT64 },
501 { "evict_skip", KSTAT_DATA_UINT64 },
ca0bf58d 502 { "evict_not_enough", KSTAT_DATA_UINT64 },
428870ff
BB
503 { "evict_l2_cached", KSTAT_DATA_UINT64 },
504 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
505 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
ca0bf58d 506 { "evict_l2_skip", KSTAT_DATA_UINT64 },
34dc7c2f
BB
507 { "hash_elements", KSTAT_DATA_UINT64 },
508 { "hash_elements_max", KSTAT_DATA_UINT64 },
509 { "hash_collisions", KSTAT_DATA_UINT64 },
510 { "hash_chains", KSTAT_DATA_UINT64 },
511 { "hash_chain_max", KSTAT_DATA_UINT64 },
512 { "p", KSTAT_DATA_UINT64 },
513 { "c", KSTAT_DATA_UINT64 },
514 { "c_min", KSTAT_DATA_UINT64 },
515 { "c_max", KSTAT_DATA_UINT64 },
516 { "size", KSTAT_DATA_UINT64 },
517 { "hdr_size", KSTAT_DATA_UINT64 },
d164b209 518 { "data_size", KSTAT_DATA_UINT64 },
500445c0 519 { "metadata_size", KSTAT_DATA_UINT64 },
d164b209 520 { "other_size", KSTAT_DATA_UINT64 },
13be560d 521 { "anon_size", KSTAT_DATA_UINT64 },
500445c0
PS
522 { "anon_evictable_data", KSTAT_DATA_UINT64 },
523 { "anon_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 524 { "mru_size", KSTAT_DATA_UINT64 },
500445c0
PS
525 { "mru_evictable_data", KSTAT_DATA_UINT64 },
526 { "mru_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 527 { "mru_ghost_size", KSTAT_DATA_UINT64 },
500445c0
PS
528 { "mru_ghost_evictable_data", KSTAT_DATA_UINT64 },
529 { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 530 { "mfu_size", KSTAT_DATA_UINT64 },
500445c0
PS
531 { "mfu_evictable_data", KSTAT_DATA_UINT64 },
532 { "mfu_evictable_metadata", KSTAT_DATA_UINT64 },
13be560d 533 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
500445c0
PS
534 { "mfu_ghost_evictable_data", KSTAT_DATA_UINT64 },
535 { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
34dc7c2f
BB
536 { "l2_hits", KSTAT_DATA_UINT64 },
537 { "l2_misses", KSTAT_DATA_UINT64 },
538 { "l2_feeds", KSTAT_DATA_UINT64 },
539 { "l2_rw_clash", KSTAT_DATA_UINT64 },
d164b209
BB
540 { "l2_read_bytes", KSTAT_DATA_UINT64 },
541 { "l2_write_bytes", KSTAT_DATA_UINT64 },
34dc7c2f
BB
542 { "l2_writes_sent", KSTAT_DATA_UINT64 },
543 { "l2_writes_done", KSTAT_DATA_UINT64 },
544 { "l2_writes_error", KSTAT_DATA_UINT64 },
ca0bf58d 545 { "l2_writes_lock_retry", KSTAT_DATA_UINT64 },
8a09d5fd 546 { "l2_writes_skip_toobig", KSTAT_DATA_UINT64 },
34dc7c2f
BB
547 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
548 { "l2_evict_reading", KSTAT_DATA_UINT64 },
b9541d6b 549 { "l2_evict_l1cached", KSTAT_DATA_UINT64 },
34dc7c2f 550 { "l2_free_on_write", KSTAT_DATA_UINT64 },
ca0bf58d 551 { "l2_cdata_free_on_write", KSTAT_DATA_UINT64 },
34dc7c2f
BB
552 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
553 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
554 { "l2_io_error", KSTAT_DATA_UINT64 },
555 { "l2_size", KSTAT_DATA_UINT64 },
3a17a7a9 556 { "l2_asize", KSTAT_DATA_UINT64 },
34dc7c2f 557 { "l2_hdr_size", KSTAT_DATA_UINT64 },
3a17a7a9
SK
558 { "l2_compress_successes", KSTAT_DATA_UINT64 },
559 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
560 { "l2_compress_failures", KSTAT_DATA_UINT64 },
1834f2d8 561 { "memory_throttle_count", KSTAT_DATA_UINT64 },
1eb5bfa3
GW
562 { "duplicate_buffers", KSTAT_DATA_UINT64 },
563 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
564 { "duplicate_reads", KSTAT_DATA_UINT64 },
7cb67b45
BB
565 { "memory_direct_count", KSTAT_DATA_UINT64 },
566 { "memory_indirect_count", KSTAT_DATA_UINT64 },
1834f2d8
BB
567 { "arc_no_grow", KSTAT_DATA_UINT64 },
568 { "arc_tempreserve", KSTAT_DATA_UINT64 },
569 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
ab26409d 570 { "arc_prune", KSTAT_DATA_UINT64 },
1834f2d8
BB
571 { "arc_meta_used", KSTAT_DATA_UINT64 },
572 { "arc_meta_limit", KSTAT_DATA_UINT64 },
573 { "arc_meta_max", KSTAT_DATA_UINT64 },
11f552fa 574 { "arc_meta_min", KSTAT_DATA_UINT64 },
7f60329a
MA
575 { "sync_wait_for_async", KSTAT_DATA_UINT64 },
576 { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
11f552fa
BB
577 { "arc_need_free", KSTAT_DATA_UINT64 },
578 { "arc_sys_free", KSTAT_DATA_UINT64 }
34dc7c2f
BB
579};
580
581#define ARCSTAT(stat) (arc_stats.stat.value.ui64)
582
583#define ARCSTAT_INCR(stat, val) \
d3cc8b15 584 atomic_add_64(&arc_stats.stat.value.ui64, (val))
34dc7c2f 585
428870ff 586#define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
34dc7c2f
BB
587#define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
588
589#define ARCSTAT_MAX(stat, val) { \
590 uint64_t m; \
591 while ((val) > (m = arc_stats.stat.value.ui64) && \
592 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
593 continue; \
594}
595
596#define ARCSTAT_MAXSTAT(stat) \
597 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
598
599/*
600 * We define a macro to allow ARC hits/misses to be easily broken down by
601 * two separate conditions, giving a total of four different subtypes for
602 * each of hits and misses (so eight statistics total).
603 */
604#define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
605 if (cond1) { \
606 if (cond2) { \
607 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
608 } else { \
609 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
610 } \
611 } else { \
612 if (cond2) { \
613 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
614 } else { \
615 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
616 } \
617 }
618
619kstat_t *arc_ksp;
428870ff 620static arc_state_t *arc_anon;
34dc7c2f
BB
621static arc_state_t *arc_mru;
622static arc_state_t *arc_mru_ghost;
623static arc_state_t *arc_mfu;
624static arc_state_t *arc_mfu_ghost;
625static arc_state_t *arc_l2c_only;
626
627/*
628 * There are several ARC variables that are critical to export as kstats --
629 * but we don't want to have to grovel around in the kstat whenever we wish to
630 * manipulate them. For these variables, we therefore define them to be in
631 * terms of the statistic variable. This assures that we are not introducing
632 * the possibility of inconsistency by having shadow copies of the variables,
633 * while still allowing the code to be readable.
634 */
635#define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
636#define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
637#define arc_c ARCSTAT(arcstat_c) /* target size of cache */
638#define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
639#define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
1834f2d8
BB
640#define arc_no_grow ARCSTAT(arcstat_no_grow)
641#define arc_tempreserve ARCSTAT(arcstat_tempreserve)
642#define arc_loaned_bytes ARCSTAT(arcstat_loaned_bytes)
23c0a133 643#define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
ca0bf58d 644#define arc_meta_min ARCSTAT(arcstat_meta_min) /* min size for metadata */
23c0a133
GW
645#define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
646#define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
11f552fa
BB
647#define arc_need_free ARCSTAT(arcstat_need_free) /* bytes to be freed */
648#define arc_sys_free ARCSTAT(arcstat_sys_free) /* target system free bytes */
34dc7c2f 649
3a17a7a9
SK
650#define L2ARC_IS_VALID_COMPRESS(_c_) \
651 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
652
ab26409d
BB
653static list_t arc_prune_list;
654static kmutex_t arc_prune_mtx;
f6046738 655static taskq_t *arc_prune_taskq;
34dc7c2f 656static arc_buf_t *arc_eviction_list;
34dc7c2f 657static arc_buf_hdr_t arc_eviction_hdr;
428870ff 658
34dc7c2f
BB
659#define GHOST_STATE(state) \
660 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
661 (state) == arc_l2c_only)
662
2a432414
GW
663#define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
664#define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
665#define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
666#define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_FLAG_PREFETCH)
667#define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
668#define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
b9541d6b 669
2a432414 670#define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_FLAG_L2CACHE)
b9541d6b 671#define HDR_L2COMPRESS(hdr) ((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
2a432414 672#define HDR_L2_READING(hdr) \
b9541d6b
CW
673 (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) && \
674 ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
2a432414
GW
675#define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
676#define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
677#define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
34dc7c2f 678
b9541d6b
CW
679#define HDR_ISTYPE_METADATA(hdr) \
680 ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
681#define HDR_ISTYPE_DATA(hdr) (!HDR_ISTYPE_METADATA(hdr))
682
683#define HDR_HAS_L1HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
684#define HDR_HAS_L2HDR(hdr) ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
685
34dc7c2f
BB
686/*
687 * Other sizes
688 */
689
b9541d6b
CW
690#define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
691#define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
34dc7c2f
BB
692
693/*
694 * Hash table routines
695 */
696
00b46022
BB
697#define HT_LOCK_ALIGN 64
698#define HT_LOCK_PAD (P2NPHASE(sizeof (kmutex_t), (HT_LOCK_ALIGN)))
34dc7c2f
BB
699
700struct ht_lock {
701 kmutex_t ht_lock;
702#ifdef _KERNEL
00b46022 703 unsigned char pad[HT_LOCK_PAD];
34dc7c2f
BB
704#endif
705};
706
b31d8ea7 707#define BUF_LOCKS 8192
34dc7c2f
BB
708typedef struct buf_hash_table {
709 uint64_t ht_mask;
710 arc_buf_hdr_t **ht_table;
711 struct ht_lock ht_locks[BUF_LOCKS];
712} buf_hash_table_t;
713
714static buf_hash_table_t buf_hash_table;
715
716#define BUF_HASH_INDEX(spa, dva, birth) \
717 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
718#define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
719#define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
428870ff
BB
720#define HDR_LOCK(hdr) \
721 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
34dc7c2f
BB
722
723uint64_t zfs_crc64_table[256];
724
725/*
726 * Level 2 ARC
727 */
728
729#define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
3a17a7a9 730#define L2ARC_HEADROOM 2 /* num of writes */
8a09d5fd
BB
731#define L2ARC_MAX_BLOCK_SIZE (16 * 1024 * 1024) /* max compress size */
732
3a17a7a9
SK
733/*
734 * If we discover during ARC scan any buffers to be compressed, we boost
735 * our headroom for the next scanning cycle by this percentage multiple.
736 */
737#define L2ARC_HEADROOM_BOOST 200
d164b209
BB
738#define L2ARC_FEED_SECS 1 /* caching interval secs */
739#define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
34dc7c2f 740
8a09d5fd 741
d962d5da
PS
742/*
743 * Used to distinguish headers that are being process by
744 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
745 * address. This can happen when the header is added to the l2arc's list
746 * of buffers to write in the first stage of l2arc_write_buffers(), but
747 * has not yet been written out which happens in the second stage of
748 * l2arc_write_buffers().
749 */
750#define L2ARC_ADDR_UNSET ((uint64_t)(-1))
751
34dc7c2f
BB
752#define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
753#define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
754
d3cc8b15 755/* L2ARC Performance Tunables */
abd8610c
BB
756unsigned long l2arc_write_max = L2ARC_WRITE_SIZE; /* def max write size */
757unsigned long l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra warmup write */
758unsigned long l2arc_headroom = L2ARC_HEADROOM; /* # of dev writes */
3a17a7a9 759unsigned long l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
8a09d5fd 760unsigned long l2arc_max_block_size = L2ARC_MAX_BLOCK_SIZE;
abd8610c
BB
761unsigned long l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
762unsigned long l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval msecs */
763int l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
3a17a7a9 764int l2arc_nocompress = B_FALSE; /* don't compress bufs */
abd8610c 765int l2arc_feed_again = B_TRUE; /* turbo warmup */
c93504f0 766int l2arc_norw = B_FALSE; /* no reads during writes */
34dc7c2f
BB
767
768/*
769 * L2ARC Internals
770 */
34dc7c2f
BB
771static list_t L2ARC_dev_list; /* device list */
772static list_t *l2arc_dev_list; /* device list pointer */
773static kmutex_t l2arc_dev_mtx; /* device list mutex */
774static l2arc_dev_t *l2arc_dev_last; /* last device used */
34dc7c2f
BB
775static list_t L2ARC_free_on_write; /* free after write buf list */
776static list_t *l2arc_free_on_write; /* free after write list ptr */
777static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
778static uint64_t l2arc_ndev; /* number of devices */
779
780typedef struct l2arc_read_callback {
3a17a7a9
SK
781 arc_buf_t *l2rcb_buf; /* read buffer */
782 spa_t *l2rcb_spa; /* spa */
783 blkptr_t l2rcb_bp; /* original blkptr */
5dbd68a3 784 zbookmark_phys_t l2rcb_zb; /* original bookmark */
3a17a7a9
SK
785 int l2rcb_flags; /* original flags */
786 enum zio_compress l2rcb_compress; /* applied compress */
34dc7c2f
BB
787} l2arc_read_callback_t;
788
34dc7c2f
BB
789typedef struct l2arc_data_free {
790 /* protected by l2arc_free_on_write_mtx */
791 void *l2df_data;
792 size_t l2df_size;
793 void (*l2df_func)(void *, size_t);
794 list_node_t l2df_list_node;
795} l2arc_data_free_t;
796
797static kmutex_t l2arc_feed_thr_lock;
798static kcondvar_t l2arc_feed_thr_cv;
799static uint8_t l2arc_thread_exit;
800
2a432414
GW
801static void arc_get_data_buf(arc_buf_t *);
802static void arc_access(arc_buf_hdr_t *, kmutex_t *);
ca0bf58d 803static boolean_t arc_is_overflowing(void);
2a432414 804static void arc_buf_watch(arc_buf_t *);
ca67b33a 805static void arc_tuning_update(void);
2a432414 806
b9541d6b
CW
807static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
808static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
809
2a432414
GW
810static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
811static void l2arc_read_done(zio_t *);
34dc7c2f 812
b9541d6b 813static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
2a432414
GW
814static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
815static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
3a17a7a9 816
34dc7c2f 817static uint64_t
d164b209 818buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
34dc7c2f 819{
34dc7c2f
BB
820 uint8_t *vdva = (uint8_t *)dva;
821 uint64_t crc = -1ULL;
822 int i;
823
824 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
825
826 for (i = 0; i < sizeof (dva_t); i++)
827 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
828
d164b209 829 crc ^= (spa>>8) ^ birth;
34dc7c2f
BB
830
831 return (crc);
832}
833
834#define BUF_EMPTY(buf) \
835 ((buf)->b_dva.dva_word[0] == 0 && \
b9541d6b 836 (buf)->b_dva.dva_word[1] == 0)
34dc7c2f
BB
837
838#define BUF_EQUAL(spa, dva, birth, buf) \
839 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
840 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
841 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
842
428870ff
BB
843static void
844buf_discard_identity(arc_buf_hdr_t *hdr)
845{
846 hdr->b_dva.dva_word[0] = 0;
847 hdr->b_dva.dva_word[1] = 0;
848 hdr->b_birth = 0;
428870ff
BB
849}
850
34dc7c2f 851static arc_buf_hdr_t *
9b67f605 852buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
34dc7c2f 853{
9b67f605
MA
854 const dva_t *dva = BP_IDENTITY(bp);
855 uint64_t birth = BP_PHYSICAL_BIRTH(bp);
34dc7c2f
BB
856 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
857 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
2a432414 858 arc_buf_hdr_t *hdr;
34dc7c2f
BB
859
860 mutex_enter(hash_lock);
2a432414
GW
861 for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
862 hdr = hdr->b_hash_next) {
863 if (BUF_EQUAL(spa, dva, birth, hdr)) {
34dc7c2f 864 *lockp = hash_lock;
2a432414 865 return (hdr);
34dc7c2f
BB
866 }
867 }
868 mutex_exit(hash_lock);
869 *lockp = NULL;
870 return (NULL);
871}
872
873/*
874 * Insert an entry into the hash table. If there is already an element
875 * equal to elem in the hash table, then the already existing element
876 * will be returned and the new element will not be inserted.
877 * Otherwise returns NULL.
b9541d6b 878 * If lockp == NULL, the caller is assumed to already hold the hash lock.
34dc7c2f
BB
879 */
880static arc_buf_hdr_t *
2a432414 881buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
34dc7c2f 882{
2a432414 883 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
34dc7c2f 884 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
2a432414 885 arc_buf_hdr_t *fhdr;
34dc7c2f
BB
886 uint32_t i;
887
2a432414
GW
888 ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
889 ASSERT(hdr->b_birth != 0);
890 ASSERT(!HDR_IN_HASH_TABLE(hdr));
b9541d6b
CW
891
892 if (lockp != NULL) {
893 *lockp = hash_lock;
894 mutex_enter(hash_lock);
895 } else {
896 ASSERT(MUTEX_HELD(hash_lock));
897 }
898
2a432414
GW
899 for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
900 fhdr = fhdr->b_hash_next, i++) {
901 if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
902 return (fhdr);
34dc7c2f
BB
903 }
904
2a432414
GW
905 hdr->b_hash_next = buf_hash_table.ht_table[idx];
906 buf_hash_table.ht_table[idx] = hdr;
907 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
34dc7c2f
BB
908
909 /* collect some hash table performance data */
910 if (i > 0) {
911 ARCSTAT_BUMP(arcstat_hash_collisions);
912 if (i == 1)
913 ARCSTAT_BUMP(arcstat_hash_chains);
914
915 ARCSTAT_MAX(arcstat_hash_chain_max, i);
916 }
917
918 ARCSTAT_BUMP(arcstat_hash_elements);
919 ARCSTAT_MAXSTAT(arcstat_hash_elements);
920
921 return (NULL);
922}
923
924static void
2a432414 925buf_hash_remove(arc_buf_hdr_t *hdr)
34dc7c2f 926{
2a432414
GW
927 arc_buf_hdr_t *fhdr, **hdrp;
928 uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
34dc7c2f
BB
929
930 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
2a432414 931 ASSERT(HDR_IN_HASH_TABLE(hdr));
34dc7c2f 932
2a432414
GW
933 hdrp = &buf_hash_table.ht_table[idx];
934 while ((fhdr = *hdrp) != hdr) {
935 ASSERT(fhdr != NULL);
936 hdrp = &fhdr->b_hash_next;
34dc7c2f 937 }
2a432414
GW
938 *hdrp = hdr->b_hash_next;
939 hdr->b_hash_next = NULL;
940 hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
34dc7c2f
BB
941
942 /* collect some hash table performance data */
943 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
944
945 if (buf_hash_table.ht_table[idx] &&
946 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
947 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
948}
949
950/*
951 * Global data structures and functions for the buf kmem cache.
952 */
b9541d6b
CW
953static kmem_cache_t *hdr_full_cache;
954static kmem_cache_t *hdr_l2only_cache;
34dc7c2f
BB
955static kmem_cache_t *buf_cache;
956
957static void
958buf_fini(void)
959{
960 int i;
961
00b46022 962#if defined(_KERNEL) && defined(HAVE_SPL)
d1d7e268
MK
963 /*
964 * Large allocations which do not require contiguous pages
965 * should be using vmem_free() in the linux kernel\
966 */
00b46022
BB
967 vmem_free(buf_hash_table.ht_table,
968 (buf_hash_table.ht_mask + 1) * sizeof (void *));
969#else
34dc7c2f
BB
970 kmem_free(buf_hash_table.ht_table,
971 (buf_hash_table.ht_mask + 1) * sizeof (void *));
00b46022 972#endif
34dc7c2f
BB
973 for (i = 0; i < BUF_LOCKS; i++)
974 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
b9541d6b
CW
975 kmem_cache_destroy(hdr_full_cache);
976 kmem_cache_destroy(hdr_l2only_cache);
34dc7c2f
BB
977 kmem_cache_destroy(buf_cache);
978}
979
980/*
981 * Constructor callback - called when the cache is empty
982 * and a new buf is requested.
983 */
984/* ARGSUSED */
985static int
b9541d6b
CW
986hdr_full_cons(void *vbuf, void *unused, int kmflag)
987{
988 arc_buf_hdr_t *hdr = vbuf;
989
990 bzero(hdr, HDR_FULL_SIZE);
991 cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
992 refcount_create(&hdr->b_l1hdr.b_refcnt);
993 mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
994 list_link_init(&hdr->b_l1hdr.b_arc_node);
995 list_link_init(&hdr->b_l2hdr.b_l2node);
ca0bf58d 996 multilist_link_init(&hdr->b_l1hdr.b_arc_node);
b9541d6b
CW
997 arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
998
999 return (0);
1000}
1001
1002/* ARGSUSED */
1003static int
1004hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
34dc7c2f 1005{
2a432414
GW
1006 arc_buf_hdr_t *hdr = vbuf;
1007
b9541d6b
CW
1008 bzero(hdr, HDR_L2ONLY_SIZE);
1009 arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f 1010
34dc7c2f
BB
1011 return (0);
1012}
1013
b128c09f
BB
1014/* ARGSUSED */
1015static int
1016buf_cons(void *vbuf, void *unused, int kmflag)
1017{
1018 arc_buf_t *buf = vbuf;
1019
1020 bzero(buf, sizeof (arc_buf_t));
428870ff 1021 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
d164b209
BB
1022 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1023
b128c09f
BB
1024 return (0);
1025}
1026
34dc7c2f
BB
1027/*
1028 * Destructor callback - called when a cached buf is
1029 * no longer required.
1030 */
1031/* ARGSUSED */
1032static void
b9541d6b 1033hdr_full_dest(void *vbuf, void *unused)
34dc7c2f 1034{
2a432414 1035 arc_buf_hdr_t *hdr = vbuf;
34dc7c2f 1036
2a432414 1037 ASSERT(BUF_EMPTY(hdr));
b9541d6b
CW
1038 cv_destroy(&hdr->b_l1hdr.b_cv);
1039 refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1040 mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
ca0bf58d 1041 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
b9541d6b
CW
1042 arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1043}
1044
1045/* ARGSUSED */
1046static void
1047hdr_l2only_dest(void *vbuf, void *unused)
1048{
1049 ASSERTV(arc_buf_hdr_t *hdr = vbuf);
1050
1051 ASSERT(BUF_EMPTY(hdr));
1052 arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
34dc7c2f
BB
1053}
1054
b128c09f
BB
1055/* ARGSUSED */
1056static void
1057buf_dest(void *vbuf, void *unused)
1058{
1059 arc_buf_t *buf = vbuf;
1060
428870ff 1061 mutex_destroy(&buf->b_evict_lock);
d164b209 1062 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
b128c09f
BB
1063}
1064
8c8af9d8
BB
1065/*
1066 * Reclaim callback -- invoked when memory is low.
1067 */
1068/* ARGSUSED */
1069static void
1070hdr_recl(void *unused)
1071{
1072 dprintf("hdr_recl called\n");
1073 /*
1074 * umem calls the reclaim func when we destroy the buf cache,
1075 * which is after we do arc_fini().
1076 */
1077 if (!arc_dead)
1078 cv_signal(&arc_reclaim_thread_cv);
1079}
1080
34dc7c2f
BB
1081static void
1082buf_init(void)
1083{
1084 uint64_t *ct;
1085 uint64_t hsize = 1ULL << 12;
1086 int i, j;
1087
1088 /*
1089 * The hash table is big enough to fill all of physical memory
49ddb315
MA
1090 * with an average block size of zfs_arc_average_blocksize (default 8K).
1091 * By default, the table will take up
1092 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
34dc7c2f 1093 */
49ddb315 1094 while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
34dc7c2f
BB
1095 hsize <<= 1;
1096retry:
1097 buf_hash_table.ht_mask = hsize - 1;
00b46022 1098#if defined(_KERNEL) && defined(HAVE_SPL)
d1d7e268
MK
1099 /*
1100 * Large allocations which do not require contiguous pages
1101 * should be using vmem_alloc() in the linux kernel
1102 */
00b46022
BB
1103 buf_hash_table.ht_table =
1104 vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1105#else
34dc7c2f
BB
1106 buf_hash_table.ht_table =
1107 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
00b46022 1108#endif
34dc7c2f
BB
1109 if (buf_hash_table.ht_table == NULL) {
1110 ASSERT(hsize > (1ULL << 8));
1111 hsize >>= 1;
1112 goto retry;
1113 }
1114
b9541d6b 1115 hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
8c8af9d8 1116 0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
b9541d6b 1117 hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
8c8af9d8 1118 HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
b9541d6b 1119 NULL, NULL, 0);
34dc7c2f 1120 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
b128c09f 1121 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
34dc7c2f
BB
1122
1123 for (i = 0; i < 256; i++)
1124 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1125 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1126
1127 for (i = 0; i < BUF_LOCKS; i++) {
1128 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
40d06e3c 1129 NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
1130 }
1131}
1132
b9541d6b
CW
1133/*
1134 * Transition between the two allocation states for the arc_buf_hdr struct.
1135 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1136 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1137 * version is used when a cache buffer is only in the L2ARC in order to reduce
1138 * memory usage.
1139 */
1140static arc_buf_hdr_t *
1141arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1142{
1143 arc_buf_hdr_t *nhdr;
1144 l2arc_dev_t *dev;
1145
1146 ASSERT(HDR_HAS_L2HDR(hdr));
1147 ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1148 (old == hdr_l2only_cache && new == hdr_full_cache));
1149
1150 dev = hdr->b_l2hdr.b_dev;
1151 nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1152
1153 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1154 buf_hash_remove(hdr);
1155
1156 bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
d962d5da 1157
b9541d6b
CW
1158 if (new == hdr_full_cache) {
1159 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1160 /*
1161 * arc_access and arc_change_state need to be aware that a
1162 * header has just come out of L2ARC, so we set its state to
1163 * l2c_only even though it's about to change.
1164 */
1165 nhdr->b_l1hdr.b_state = arc_l2c_only;
ca0bf58d
PS
1166
1167 /* Verify previous threads set to NULL before freeing */
1168 ASSERT3P(nhdr->b_l1hdr.b_tmp_cdata, ==, NULL);
b9541d6b
CW
1169 } else {
1170 ASSERT(hdr->b_l1hdr.b_buf == NULL);
1171 ASSERT0(hdr->b_l1hdr.b_datacnt);
ca0bf58d
PS
1172
1173 /*
1174 * If we've reached here, We must have been called from
1175 * arc_evict_hdr(), as such we should have already been
1176 * removed from any ghost list we were previously on
1177 * (which protects us from racing with arc_evict_state),
1178 * thus no locking is needed during this check.
1179 */
1180 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1181
b9541d6b 1182 /*
ca0bf58d
PS
1183 * A buffer must not be moved into the arc_l2c_only
1184 * state if it's not finished being written out to the
1185 * l2arc device. Otherwise, the b_l1hdr.b_tmp_cdata field
1186 * might try to be accessed, even though it was removed.
b9541d6b 1187 */
ca0bf58d
PS
1188 VERIFY(!HDR_L2_WRITING(hdr));
1189 VERIFY3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1190
b9541d6b
CW
1191 nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1192 }
1193 /*
1194 * The header has been reallocated so we need to re-insert it into any
1195 * lists it was on.
1196 */
1197 (void) buf_hash_insert(nhdr, NULL);
1198
1199 ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1200
1201 mutex_enter(&dev->l2ad_mtx);
1202
1203 /*
1204 * We must place the realloc'ed header back into the list at
1205 * the same spot. Otherwise, if it's placed earlier in the list,
1206 * l2arc_write_buffers() could find it during the function's
1207 * write phase, and try to write it out to the l2arc.
1208 */
1209 list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1210 list_remove(&dev->l2ad_buflist, hdr);
1211
1212 mutex_exit(&dev->l2ad_mtx);
1213
d962d5da
PS
1214 /*
1215 * Since we're using the pointer address as the tag when
1216 * incrementing and decrementing the l2ad_alloc refcount, we
1217 * must remove the old pointer (that we're about to destroy) and
1218 * add the new pointer to the refcount. Otherwise we'd remove
1219 * the wrong pointer address when calling arc_hdr_destroy() later.
1220 */
1221
1222 (void) refcount_remove_many(&dev->l2ad_alloc,
1223 hdr->b_l2hdr.b_asize, hdr);
1224
1225 (void) refcount_add_many(&dev->l2ad_alloc,
1226 nhdr->b_l2hdr.b_asize, nhdr);
1227
b9541d6b
CW
1228 buf_discard_identity(hdr);
1229 hdr->b_freeze_cksum = NULL;
1230 kmem_cache_free(old, hdr);
1231
1232 return (nhdr);
1233}
1234
1235
34dc7c2f
BB
1236#define ARC_MINTIME (hz>>4) /* 62 ms */
1237
1238static void
1239arc_cksum_verify(arc_buf_t *buf)
1240{
1241 zio_cksum_t zc;
1242
1243 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1244 return;
1245
b9541d6b
CW
1246 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1247 if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1248 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1249 return;
1250 }
1251 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1252 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1253 panic("buffer modified while frozen!");
b9541d6b 1254 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1255}
1256
1257static int
1258arc_cksum_equal(arc_buf_t *buf)
1259{
1260 zio_cksum_t zc;
1261 int equal;
1262
b9541d6b 1263 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1264 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1265 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
b9541d6b 1266 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1267
1268 return (equal);
1269}
1270
1271static void
1272arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1273{
1274 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1275 return;
1276
b9541d6b 1277 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f 1278 if (buf->b_hdr->b_freeze_cksum != NULL) {
b9541d6b 1279 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1280 return;
1281 }
96c080cb 1282 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
34dc7c2f
BB
1283 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1284 buf->b_hdr->b_freeze_cksum);
b9541d6b 1285 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
498877ba
MA
1286 arc_buf_watch(buf);
1287}
1288
1289#ifndef _KERNEL
1290void
1291arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1292{
1293 panic("Got SIGSEGV at address: 0x%lx\n", (long) si->si_addr);
1294}
1295#endif
1296
1297/* ARGSUSED */
1298static void
1299arc_buf_unwatch(arc_buf_t *buf)
1300{
1301#ifndef _KERNEL
1302 if (arc_watch) {
1303 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size,
1304 PROT_READ | PROT_WRITE));
1305 }
1306#endif
1307}
1308
1309/* ARGSUSED */
1310static void
1311arc_buf_watch(arc_buf_t *buf)
1312{
1313#ifndef _KERNEL
1314 if (arc_watch)
1315 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size, PROT_READ));
1316#endif
34dc7c2f
BB
1317}
1318
b9541d6b
CW
1319static arc_buf_contents_t
1320arc_buf_type(arc_buf_hdr_t *hdr)
1321{
1322 if (HDR_ISTYPE_METADATA(hdr)) {
1323 return (ARC_BUFC_METADATA);
1324 } else {
1325 return (ARC_BUFC_DATA);
1326 }
1327}
1328
1329static uint32_t
1330arc_bufc_to_flags(arc_buf_contents_t type)
1331{
1332 switch (type) {
1333 case ARC_BUFC_DATA:
1334 /* metadata field is 0 if buffer contains normal data */
1335 return (0);
1336 case ARC_BUFC_METADATA:
1337 return (ARC_FLAG_BUFC_METADATA);
1338 default:
1339 break;
1340 }
1341 panic("undefined ARC buffer type!");
1342 return ((uint32_t)-1);
1343}
1344
34dc7c2f
BB
1345void
1346arc_buf_thaw(arc_buf_t *buf)
1347{
1348 if (zfs_flags & ZFS_DEBUG_MODIFY) {
b9541d6b 1349 if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
34dc7c2f 1350 panic("modifying non-anon buffer!");
b9541d6b 1351 if (HDR_IO_IN_PROGRESS(buf->b_hdr))
34dc7c2f
BB
1352 panic("modifying buffer while i/o in progress!");
1353 arc_cksum_verify(buf);
1354 }
1355
b9541d6b 1356 mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
1357 if (buf->b_hdr->b_freeze_cksum != NULL) {
1358 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1359 buf->b_hdr->b_freeze_cksum = NULL;
1360 }
428870ff 1361
b9541d6b 1362 mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
498877ba
MA
1363
1364 arc_buf_unwatch(buf);
34dc7c2f
BB
1365}
1366
1367void
1368arc_buf_freeze(arc_buf_t *buf)
1369{
428870ff
BB
1370 kmutex_t *hash_lock;
1371
34dc7c2f
BB
1372 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1373 return;
1374
428870ff
BB
1375 hash_lock = HDR_LOCK(buf->b_hdr);
1376 mutex_enter(hash_lock);
1377
34dc7c2f 1378 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
b9541d6b 1379 buf->b_hdr->b_l1hdr.b_state == arc_anon);
34dc7c2f 1380 arc_cksum_compute(buf, B_FALSE);
428870ff 1381 mutex_exit(hash_lock);
498877ba 1382
34dc7c2f
BB
1383}
1384
1385static void
2a432414 1386add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
34dc7c2f 1387{
b9541d6b
CW
1388 arc_state_t *state;
1389
1390 ASSERT(HDR_HAS_L1HDR(hdr));
34dc7c2f
BB
1391 ASSERT(MUTEX_HELD(hash_lock));
1392
b9541d6b
CW
1393 state = hdr->b_l1hdr.b_state;
1394
1395 if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1396 (state != arc_anon)) {
1397 /* We don't use the L2-only state list. */
1398 if (state != arc_l2c_only) {
ca0bf58d 1399 arc_buf_contents_t type = arc_buf_type(hdr);
b9541d6b 1400 uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
ca0bf58d
PS
1401 multilist_t *list = &state->arcs_list[type];
1402 uint64_t *size = &state->arcs_lsize[type];
1403
1404 multilist_remove(list, hdr);
b9541d6b 1405
b9541d6b
CW
1406 if (GHOST_STATE(state)) {
1407 ASSERT0(hdr->b_l1hdr.b_datacnt);
1408 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1409 delta = hdr->b_size;
1410 }
1411 ASSERT(delta > 0);
1412 ASSERT3U(*size, >=, delta);
1413 atomic_add_64(size, -delta);
34dc7c2f 1414 }
b128c09f 1415 /* remove the prefetch flag if we get a reference */
b9541d6b 1416 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
34dc7c2f
BB
1417 }
1418}
1419
1420static int
2a432414 1421remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
34dc7c2f
BB
1422{
1423 int cnt;
b9541d6b 1424 arc_state_t *state = hdr->b_l1hdr.b_state;
34dc7c2f 1425
b9541d6b 1426 ASSERT(HDR_HAS_L1HDR(hdr));
34dc7c2f
BB
1427 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1428 ASSERT(!GHOST_STATE(state));
1429
b9541d6b
CW
1430 /*
1431 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1432 * check to prevent usage of the arc_l2c_only list.
1433 */
1434 if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
34dc7c2f 1435 (state != arc_anon)) {
ca0bf58d
PS
1436 arc_buf_contents_t type = arc_buf_type(hdr);
1437 multilist_t *list = &state->arcs_list[type];
1438 uint64_t *size = &state->arcs_lsize[type];
1439
1440 multilist_insert(list, hdr);
34dc7c2f 1441
b9541d6b
CW
1442 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1443 atomic_add_64(size, hdr->b_size *
1444 hdr->b_l1hdr.b_datacnt);
34dc7c2f
BB
1445 }
1446 return (cnt);
1447}
1448
e0b0ca98
BB
1449/*
1450 * Returns detailed information about a specific arc buffer. When the
1451 * state_index argument is set the function will calculate the arc header
1452 * list position for its arc state. Since this requires a linear traversal
1453 * callers are strongly encourage not to do this. However, it can be helpful
1454 * for targeted analysis so the functionality is provided.
1455 */
1456void
1457arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
1458{
1459 arc_buf_hdr_t *hdr = ab->b_hdr;
b9541d6b
CW
1460 l1arc_buf_hdr_t *l1hdr = NULL;
1461 l2arc_buf_hdr_t *l2hdr = NULL;
1462 arc_state_t *state = NULL;
1463
1464 if (HDR_HAS_L1HDR(hdr)) {
1465 l1hdr = &hdr->b_l1hdr;
1466 state = l1hdr->b_state;
1467 }
1468 if (HDR_HAS_L2HDR(hdr))
1469 l2hdr = &hdr->b_l2hdr;
e0b0ca98 1470
d1d7e268 1471 memset(abi, 0, sizeof (arc_buf_info_t));
e0b0ca98 1472 abi->abi_flags = hdr->b_flags;
b9541d6b
CW
1473
1474 if (l1hdr) {
1475 abi->abi_datacnt = l1hdr->b_datacnt;
1476 abi->abi_access = l1hdr->b_arc_access;
1477 abi->abi_mru_hits = l1hdr->b_mru_hits;
1478 abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
1479 abi->abi_mfu_hits = l1hdr->b_mfu_hits;
1480 abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
1481 abi->abi_holds = refcount_count(&l1hdr->b_refcnt);
1482 }
1483
1484 if (l2hdr) {
1485 abi->abi_l2arc_dattr = l2hdr->b_daddr;
1486 abi->abi_l2arc_asize = l2hdr->b_asize;
4e0f33ff 1487 abi->abi_l2arc_compress = l2hdr->b_compress;
b9541d6b
CW
1488 abi->abi_l2arc_hits = l2hdr->b_hits;
1489 }
1490
e0b0ca98 1491 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
b9541d6b 1492 abi->abi_state_contents = arc_buf_type(hdr);
e0b0ca98 1493 abi->abi_size = hdr->b_size;
e0b0ca98
BB
1494}
1495
34dc7c2f 1496/*
ca0bf58d 1497 * Move the supplied buffer to the indicated state. The hash lock
34dc7c2f
BB
1498 * for the buffer must be held by the caller.
1499 */
1500static void
2a432414
GW
1501arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1502 kmutex_t *hash_lock)
34dc7c2f 1503{
b9541d6b
CW
1504 arc_state_t *old_state;
1505 int64_t refcnt;
1506 uint32_t datacnt;
34dc7c2f 1507 uint64_t from_delta, to_delta;
b9541d6b
CW
1508 arc_buf_contents_t buftype = arc_buf_type(hdr);
1509
1510 /*
1511 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1512 * in arc_read() when bringing a buffer out of the L2ARC. However, the
1513 * L1 hdr doesn't always exist when we change state to arc_anon before
1514 * destroying a header, in which case reallocating to add the L1 hdr is
1515 * pointless.
1516 */
1517 if (HDR_HAS_L1HDR(hdr)) {
1518 old_state = hdr->b_l1hdr.b_state;
1519 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1520 datacnt = hdr->b_l1hdr.b_datacnt;
1521 } else {
1522 old_state = arc_l2c_only;
1523 refcnt = 0;
1524 datacnt = 0;
1525 }
34dc7c2f
BB
1526
1527 ASSERT(MUTEX_HELD(hash_lock));
e8b96c60 1528 ASSERT3P(new_state, !=, old_state);
b9541d6b
CW
1529 ASSERT(refcnt == 0 || datacnt > 0);
1530 ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1531 ASSERT(old_state != arc_anon || datacnt <= 1);
34dc7c2f 1532
b9541d6b 1533 from_delta = to_delta = datacnt * hdr->b_size;
34dc7c2f
BB
1534
1535 /*
1536 * If this buffer is evictable, transfer it from the
1537 * old state list to the new state list.
1538 */
1539 if (refcnt == 0) {
b9541d6b 1540 if (old_state != arc_anon && old_state != arc_l2c_only) {
b9541d6b 1541 uint64_t *size = &old_state->arcs_lsize[buftype];
34dc7c2f 1542
b9541d6b 1543 ASSERT(HDR_HAS_L1HDR(hdr));
ca0bf58d 1544 multilist_remove(&old_state->arcs_list[buftype], hdr);
34dc7c2f
BB
1545
1546 /*
1547 * If prefetching out of the ghost cache,
428870ff 1548 * we will have a non-zero datacnt.
34dc7c2f 1549 */
b9541d6b 1550 if (GHOST_STATE(old_state) && datacnt == 0) {
34dc7c2f 1551 /* ghost elements have a ghost size */
b9541d6b 1552 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2a432414 1553 from_delta = hdr->b_size;
34dc7c2f
BB
1554 }
1555 ASSERT3U(*size, >=, from_delta);
1556 atomic_add_64(size, -from_delta);
34dc7c2f 1557 }
b9541d6b 1558 if (new_state != arc_anon && new_state != arc_l2c_only) {
b9541d6b 1559 uint64_t *size = &new_state->arcs_lsize[buftype];
34dc7c2f 1560
b9541d6b
CW
1561 /*
1562 * An L1 header always exists here, since if we're
1563 * moving to some L1-cached state (i.e. not l2c_only or
1564 * anonymous), we realloc the header to add an L1hdr
1565 * beforehand.
1566 */
1567 ASSERT(HDR_HAS_L1HDR(hdr));
ca0bf58d 1568 multilist_insert(&new_state->arcs_list[buftype], hdr);
34dc7c2f
BB
1569
1570 /* ghost elements have a ghost size */
1571 if (GHOST_STATE(new_state)) {
b9541d6b
CW
1572 ASSERT0(datacnt);
1573 ASSERT(hdr->b_l1hdr.b_buf == NULL);
2a432414 1574 to_delta = hdr->b_size;
34dc7c2f
BB
1575 }
1576 atomic_add_64(size, to_delta);
34dc7c2f
BB
1577 }
1578 }
1579
2a432414
GW
1580 ASSERT(!BUF_EMPTY(hdr));
1581 if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1582 buf_hash_remove(hdr);
34dc7c2f 1583
b9541d6b 1584 /* adjust state sizes (ignore arc_l2c_only) */
36da08ef
PS
1585
1586 if (to_delta && new_state != arc_l2c_only) {
1587 ASSERT(HDR_HAS_L1HDR(hdr));
1588 if (GHOST_STATE(new_state)) {
1589 ASSERT0(datacnt);
1590
1591 /*
1592 * We moving a header to a ghost state, we first
1593 * remove all arc buffers. Thus, we'll have a
1594 * datacnt of zero, and no arc buffer to use for
1595 * the reference. As a result, we use the arc
1596 * header pointer for the reference.
1597 */
1598 (void) refcount_add_many(&new_state->arcs_size,
1599 hdr->b_size, hdr);
1600 } else {
1601 arc_buf_t *buf;
1602 ASSERT3U(datacnt, !=, 0);
1603
1604 /*
1605 * Each individual buffer holds a unique reference,
1606 * thus we must remove each of these references one
1607 * at a time.
1608 */
1609 for (buf = hdr->b_l1hdr.b_buf; buf != NULL;
1610 buf = buf->b_next) {
1611 (void) refcount_add_many(&new_state->arcs_size,
1612 hdr->b_size, buf);
1613 }
1614 }
1615 }
1616
b9541d6b 1617 if (from_delta && old_state != arc_l2c_only) {
36da08ef
PS
1618 ASSERT(HDR_HAS_L1HDR(hdr));
1619 if (GHOST_STATE(old_state)) {
1620 /*
1621 * When moving a header off of a ghost state,
1622 * there's the possibility for datacnt to be
1623 * non-zero. This is because we first add the
1624 * arc buffer to the header prior to changing
1625 * the header's state. Since we used the header
1626 * for the reference when putting the header on
1627 * the ghost state, we must balance that and use
1628 * the header when removing off the ghost state
1629 * (even though datacnt is non zero).
1630 */
1631
1632 IMPLY(datacnt == 0, new_state == arc_anon ||
1633 new_state == arc_l2c_only);
1634
1635 (void) refcount_remove_many(&old_state->arcs_size,
1636 hdr->b_size, hdr);
1637 } else {
1638 arc_buf_t *buf;
1639 ASSERT3U(datacnt, !=, 0);
1640
1641 /*
1642 * Each individual buffer holds a unique reference,
1643 * thus we must remove each of these references one
1644 * at a time.
1645 */
1646 for (buf = hdr->b_l1hdr.b_buf; buf != NULL;
1647 buf = buf->b_next) {
1648 (void) refcount_remove_many(
1649 &old_state->arcs_size, hdr->b_size, buf);
1650 }
1651 }
34dc7c2f 1652 }
36da08ef 1653
b9541d6b
CW
1654 if (HDR_HAS_L1HDR(hdr))
1655 hdr->b_l1hdr.b_state = new_state;
34dc7c2f 1656
b9541d6b
CW
1657 /*
1658 * L2 headers should never be on the L2 state list since they don't
1659 * have L1 headers allocated.
1660 */
ca0bf58d
PS
1661 ASSERT(multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1662 multilist_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
34dc7c2f
BB
1663}
1664
1665void
d164b209 1666arc_space_consume(uint64_t space, arc_space_type_t type)
34dc7c2f 1667{
d164b209
BB
1668 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1669
1670 switch (type) {
e75c13c3
BB
1671 default:
1672 break;
d164b209
BB
1673 case ARC_SPACE_DATA:
1674 ARCSTAT_INCR(arcstat_data_size, space);
1675 break;
cc7f677c 1676 case ARC_SPACE_META:
500445c0 1677 ARCSTAT_INCR(arcstat_metadata_size, space);
cc7f677c 1678 break;
d164b209
BB
1679 case ARC_SPACE_OTHER:
1680 ARCSTAT_INCR(arcstat_other_size, space);
1681 break;
1682 case ARC_SPACE_HDRS:
1683 ARCSTAT_INCR(arcstat_hdr_size, space);
1684 break;
1685 case ARC_SPACE_L2HDRS:
1686 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1687 break;
1688 }
1689
500445c0 1690 if (type != ARC_SPACE_DATA)
cc7f677c
PS
1691 ARCSTAT_INCR(arcstat_meta_used, space);
1692
34dc7c2f
BB
1693 atomic_add_64(&arc_size, space);
1694}
1695
1696void
d164b209 1697arc_space_return(uint64_t space, arc_space_type_t type)
34dc7c2f 1698{
d164b209
BB
1699 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1700
1701 switch (type) {
e75c13c3
BB
1702 default:
1703 break;
d164b209
BB
1704 case ARC_SPACE_DATA:
1705 ARCSTAT_INCR(arcstat_data_size, -space);
1706 break;
cc7f677c 1707 case ARC_SPACE_META:
500445c0 1708 ARCSTAT_INCR(arcstat_metadata_size, -space);
cc7f677c 1709 break;
d164b209
BB
1710 case ARC_SPACE_OTHER:
1711 ARCSTAT_INCR(arcstat_other_size, -space);
1712 break;
1713 case ARC_SPACE_HDRS:
1714 ARCSTAT_INCR(arcstat_hdr_size, -space);
1715 break;
1716 case ARC_SPACE_L2HDRS:
1717 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1718 break;
1719 }
1720
cc7f677c
PS
1721 if (type != ARC_SPACE_DATA) {
1722 ASSERT(arc_meta_used >= space);
500445c0
PS
1723 if (arc_meta_max < arc_meta_used)
1724 arc_meta_max = arc_meta_used;
cc7f677c
PS
1725 ARCSTAT_INCR(arcstat_meta_used, -space);
1726 }
1727
34dc7c2f
BB
1728 ASSERT(arc_size >= space);
1729 atomic_add_64(&arc_size, -space);
1730}
1731
34dc7c2f 1732arc_buf_t *
5f6d0b6f 1733arc_buf_alloc(spa_t *spa, uint64_t size, void *tag, arc_buf_contents_t type)
34dc7c2f
BB
1734{
1735 arc_buf_hdr_t *hdr;
1736 arc_buf_t *buf;
1737
f1512ee6 1738 VERIFY3U(size, <=, spa_maxblocksize(spa));
b9541d6b 1739 hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
34dc7c2f 1740 ASSERT(BUF_EMPTY(hdr));
b9541d6b 1741 ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
34dc7c2f 1742 hdr->b_size = size;
3541dc6d 1743 hdr->b_spa = spa_load_guid(spa);
b9541d6b
CW
1744 hdr->b_l1hdr.b_mru_hits = 0;
1745 hdr->b_l1hdr.b_mru_ghost_hits = 0;
1746 hdr->b_l1hdr.b_mfu_hits = 0;
1747 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
1748 hdr->b_l1hdr.b_l2_hits = 0;
1749
34dc7c2f
BB
1750 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1751 buf->b_hdr = hdr;
1752 buf->b_data = NULL;
1753 buf->b_efunc = NULL;
1754 buf->b_private = NULL;
1755 buf->b_next = NULL;
b9541d6b
CW
1756
1757 hdr->b_flags = arc_bufc_to_flags(type);
1758 hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1759
1760 hdr->b_l1hdr.b_buf = buf;
1761 hdr->b_l1hdr.b_state = arc_anon;
1762 hdr->b_l1hdr.b_arc_access = 0;
1763 hdr->b_l1hdr.b_datacnt = 1;
ca0bf58d 1764 hdr->b_l1hdr.b_tmp_cdata = NULL;
b9541d6b 1765
34dc7c2f 1766 arc_get_data_buf(buf);
b9541d6b
CW
1767 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
1768 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
34dc7c2f
BB
1769
1770 return (buf);
1771}
1772
9babb374
BB
1773static char *arc_onloan_tag = "onloan";
1774
1775/*
1776 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1777 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1778 * buffers must be returned to the arc before they can be used by the DMU or
1779 * freed.
1780 */
1781arc_buf_t *
5f6d0b6f 1782arc_loan_buf(spa_t *spa, uint64_t size)
9babb374
BB
1783{
1784 arc_buf_t *buf;
1785
1786 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1787
1788 atomic_add_64(&arc_loaned_bytes, size);
1789 return (buf);
1790}
1791
1792/*
1793 * Return a loaned arc buffer to the arc.
1794 */
1795void
1796arc_return_buf(arc_buf_t *buf, void *tag)
1797{
1798 arc_buf_hdr_t *hdr = buf->b_hdr;
1799
9babb374 1800 ASSERT(buf->b_data != NULL);
b9541d6b
CW
1801 ASSERT(HDR_HAS_L1HDR(hdr));
1802 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1803 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
9babb374
BB
1804
1805 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1806}
1807
428870ff
BB
1808/* Detach an arc_buf from a dbuf (tag) */
1809void
1810arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1811{
b9541d6b 1812 arc_buf_hdr_t *hdr = buf->b_hdr;
428870ff
BB
1813
1814 ASSERT(buf->b_data != NULL);
b9541d6b
CW
1815 ASSERT(HDR_HAS_L1HDR(hdr));
1816 (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
1817 (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
428870ff
BB
1818 buf->b_efunc = NULL;
1819 buf->b_private = NULL;
1820
1821 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1822}
1823
34dc7c2f
BB
1824static arc_buf_t *
1825arc_buf_clone(arc_buf_t *from)
1826{
1827 arc_buf_t *buf;
1828 arc_buf_hdr_t *hdr = from->b_hdr;
1829 uint64_t size = hdr->b_size;
1830
b9541d6b
CW
1831 ASSERT(HDR_HAS_L1HDR(hdr));
1832 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
428870ff 1833
34dc7c2f
BB
1834 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1835 buf->b_hdr = hdr;
1836 buf->b_data = NULL;
1837 buf->b_efunc = NULL;
1838 buf->b_private = NULL;
b9541d6b
CW
1839 buf->b_next = hdr->b_l1hdr.b_buf;
1840 hdr->b_l1hdr.b_buf = buf;
34dc7c2f
BB
1841 arc_get_data_buf(buf);
1842 bcopy(from->b_data, buf->b_data, size);
1eb5bfa3
GW
1843
1844 /*
1845 * This buffer already exists in the arc so create a duplicate
1846 * copy for the caller. If the buffer is associated with user data
1847 * then track the size and number of duplicates. These stats will be
1848 * updated as duplicate buffers are created and destroyed.
1849 */
b9541d6b 1850 if (HDR_ISTYPE_DATA(hdr)) {
1eb5bfa3
GW
1851 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1852 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1853 }
b9541d6b 1854 hdr->b_l1hdr.b_datacnt += 1;
34dc7c2f
BB
1855 return (buf);
1856}
1857
1858void
1859arc_buf_add_ref(arc_buf_t *buf, void* tag)
1860{
1861 arc_buf_hdr_t *hdr;
1862 kmutex_t *hash_lock;
1863
1864 /*
b128c09f
BB
1865 * Check to see if this buffer is evicted. Callers
1866 * must verify b_data != NULL to know if the add_ref
1867 * was successful.
34dc7c2f 1868 */
428870ff 1869 mutex_enter(&buf->b_evict_lock);
b128c09f 1870 if (buf->b_data == NULL) {
428870ff 1871 mutex_exit(&buf->b_evict_lock);
34dc7c2f
BB
1872 return;
1873 }
428870ff 1874 hash_lock = HDR_LOCK(buf->b_hdr);
34dc7c2f 1875 mutex_enter(hash_lock);
428870ff 1876 hdr = buf->b_hdr;
b9541d6b 1877 ASSERT(HDR_HAS_L1HDR(hdr));
428870ff
BB
1878 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1879 mutex_exit(&buf->b_evict_lock);
34dc7c2f 1880
b9541d6b
CW
1881 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
1882 hdr->b_l1hdr.b_state == arc_mfu);
1883
34dc7c2f 1884 add_reference(hdr, hash_lock, tag);
d164b209 1885 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
34dc7c2f
BB
1886 arc_access(hdr, hash_lock);
1887 mutex_exit(hash_lock);
1888 ARCSTAT_BUMP(arcstat_hits);
b9541d6b
CW
1889 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
1890 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
34dc7c2f
BB
1891 data, metadata, hits);
1892}
1893
ca0bf58d
PS
1894static void
1895arc_buf_free_on_write(void *data, size_t size,
1896 void (*free_func)(void *, size_t))
1897{
1898 l2arc_data_free_t *df;
1899
1900 df = kmem_alloc(sizeof (*df), KM_SLEEP);
1901 df->l2df_data = data;
1902 df->l2df_size = size;
1903 df->l2df_func = free_func;
1904 mutex_enter(&l2arc_free_on_write_mtx);
1905 list_insert_head(l2arc_free_on_write, df);
1906 mutex_exit(&l2arc_free_on_write_mtx);
1907}
1908
34dc7c2f
BB
1909/*
1910 * Free the arc data buffer. If it is an l2arc write in progress,
1911 * the buffer is placed on l2arc_free_on_write to be freed later.
1912 */
1913static void
498877ba 1914arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
34dc7c2f 1915{
498877ba
MA
1916 arc_buf_hdr_t *hdr = buf->b_hdr;
1917
34dc7c2f 1918 if (HDR_L2_WRITING(hdr)) {
ca0bf58d 1919 arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
34dc7c2f
BB
1920 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1921 } else {
498877ba 1922 free_func(buf->b_data, hdr->b_size);
34dc7c2f
BB
1923 }
1924}
1925
ca0bf58d
PS
1926static void
1927arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
1928{
1929 ASSERT(HDR_HAS_L2HDR(hdr));
1930 ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
1931
1932 /*
1933 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
1934 * that doesn't exist, the header is in the arc_l2c_only state,
1935 * and there isn't anything to free (it's already been freed).
1936 */
1937 if (!HDR_HAS_L1HDR(hdr))
1938 return;
1939
1940 /*
1941 * The header isn't being written to the l2arc device, thus it
1942 * shouldn't have a b_tmp_cdata to free.
1943 */
1944 if (!HDR_L2_WRITING(hdr)) {
1945 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1946 return;
1947 }
1948
1949 /*
1950 * The header does not have compression enabled. This can be due
1951 * to the buffer not being compressible, or because we're
1952 * freeing the buffer before the second phase of
1953 * l2arc_write_buffer() has started (which does the compression
1954 * step). In either case, b_tmp_cdata does not point to a
1955 * separately compressed buffer, so there's nothing to free (it
1956 * points to the same buffer as the arc_buf_t's b_data field).
1957 */
4e0f33ff 1958 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_OFF) {
ca0bf58d
PS
1959 hdr->b_l1hdr.b_tmp_cdata = NULL;
1960 return;
1961 }
1962
1963 /*
1964 * There's nothing to free since the buffer was all zero's and
1965 * compressed to a zero length buffer.
1966 */
4e0f33ff 1967 if (hdr->b_l2hdr.b_compress == ZIO_COMPRESS_EMPTY) {
ca0bf58d
PS
1968 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
1969 return;
1970 }
1971
4e0f33ff 1972 ASSERT(L2ARC_IS_VALID_COMPRESS(hdr->b_l2hdr.b_compress));
ca0bf58d
PS
1973
1974 arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata,
1975 hdr->b_size, zio_data_buf_free);
1976
1977 ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
1978 hdr->b_l1hdr.b_tmp_cdata = NULL;
1979}
1980
bd089c54
MA
1981/*
1982 * Free up buf->b_data and if 'remove' is set, then pull the
1983 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
1984 */
34dc7c2f 1985static void
ca0bf58d 1986arc_buf_destroy(arc_buf_t *buf, boolean_t remove)
34dc7c2f
BB
1987{
1988 arc_buf_t **bufp;
1989
1990 /* free up data associated with the buf */
b9541d6b
CW
1991 if (buf->b_data != NULL) {
1992 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
34dc7c2f 1993 uint64_t size = buf->b_hdr->b_size;
b9541d6b 1994 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
34dc7c2f
BB
1995
1996 arc_cksum_verify(buf);
498877ba 1997 arc_buf_unwatch(buf);
428870ff 1998
ca0bf58d
PS
1999 if (type == ARC_BUFC_METADATA) {
2000 arc_buf_data_free(buf, zio_buf_free);
2001 arc_space_return(size, ARC_SPACE_META);
2002 } else {
2003 ASSERT(type == ARC_BUFC_DATA);
2004 arc_buf_data_free(buf, zio_data_buf_free);
2005 arc_space_return(size, ARC_SPACE_DATA);
34dc7c2f 2006 }
ca0bf58d
PS
2007
2008 /* protected by hash lock, if in the hash table */
2009 if (multilist_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
34dc7c2f
BB
2010 uint64_t *cnt = &state->arcs_lsize[type];
2011
b9541d6b
CW
2012 ASSERT(refcount_is_zero(
2013 &buf->b_hdr->b_l1hdr.b_refcnt));
2014 ASSERT(state != arc_anon && state != arc_l2c_only);
34dc7c2f
BB
2015
2016 ASSERT3U(*cnt, >=, size);
2017 atomic_add_64(cnt, -size);
2018 }
36da08ef
PS
2019
2020 (void) refcount_remove_many(&state->arcs_size, size, buf);
34dc7c2f 2021 buf->b_data = NULL;
1eb5bfa3
GW
2022
2023 /*
2024 * If we're destroying a duplicate buffer make sure
2025 * that the appropriate statistics are updated.
2026 */
b9541d6b
CW
2027 if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2028 HDR_ISTYPE_DATA(buf->b_hdr)) {
1eb5bfa3
GW
2029 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2030 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2031 }
b9541d6b
CW
2032 ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2033 buf->b_hdr->b_l1hdr.b_datacnt -= 1;
34dc7c2f
BB
2034 }
2035
2036 /* only remove the buf if requested */
bd089c54 2037 if (!remove)
34dc7c2f
BB
2038 return;
2039
2040 /* remove the buf from the hdr list */
b9541d6b
CW
2041 for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2042 bufp = &(*bufp)->b_next)
34dc7c2f
BB
2043 continue;
2044 *bufp = buf->b_next;
428870ff 2045 buf->b_next = NULL;
34dc7c2f
BB
2046
2047 ASSERT(buf->b_efunc == NULL);
2048
2049 /* clean up the buf */
2050 buf->b_hdr = NULL;
2051 kmem_cache_free(buf_cache, buf);
2052}
2053
d962d5da
PS
2054static void
2055arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2056{
2057 l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2058 l2arc_dev_t *dev = l2hdr->b_dev;
2059
2060 ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2061 ASSERT(HDR_HAS_L2HDR(hdr));
2062
2063 list_remove(&dev->l2ad_buflist, hdr);
2064
d962d5da
PS
2065 /*
2066 * We don't want to leak the b_tmp_cdata buffer that was
2067 * allocated in l2arc_write_buffers()
2068 */
2069 arc_buf_l2_cdata_free(hdr);
2070
2071 /*
2072 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2073 * this header is being processed by l2arc_write_buffers() (i.e.
2074 * it's in the first stage of l2arc_write_buffers()).
2075 * Re-affirming that truth here, just to serve as a reminder. If
2076 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2077 * may not have its HDR_L2_WRITING flag set. (the write may have
2078 * completed, in which case HDR_L2_WRITING will be false and the
2079 * b_daddr field will point to the address of the buffer on disk).
2080 */
2081 IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2082
2083 /*
2084 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2085 * l2arc_write_buffers(). Since we've just removed this header
2086 * from the l2arc buffer list, this header will never reach the
2087 * second stage of l2arc_write_buffers(), which increments the
2088 * accounting stats for this header. Thus, we must be careful
2089 * not to decrement them for this header either.
2090 */
2091 if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2092 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2093 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2094
2095 vdev_space_update(dev->l2ad_vdev,
2096 -l2hdr->b_asize, 0, 0);
2097
2098 (void) refcount_remove_many(&dev->l2ad_alloc,
2099 l2hdr->b_asize, hdr);
2100 }
2101
2102 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2103}
2104
34dc7c2f
BB
2105static void
2106arc_hdr_destroy(arc_buf_hdr_t *hdr)
2107{
b9541d6b
CW
2108 if (HDR_HAS_L1HDR(hdr)) {
2109 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2110 hdr->b_l1hdr.b_datacnt > 0);
2111 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2112 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2113 }
34dc7c2f 2114 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
b9541d6b
CW
2115 ASSERT(!HDR_IN_HASH_TABLE(hdr));
2116
2117 if (HDR_HAS_L2HDR(hdr)) {
d962d5da
PS
2118 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2119 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
428870ff 2120
d962d5da
PS
2121 if (!buflist_held)
2122 mutex_enter(&dev->l2ad_mtx);
b9541d6b 2123
ca0bf58d 2124 /*
d962d5da
PS
2125 * Even though we checked this conditional above, we
2126 * need to check this again now that we have the
2127 * l2ad_mtx. This is because we could be racing with
2128 * another thread calling l2arc_evict() which might have
2129 * destroyed this header's L2 portion as we were waiting
2130 * to acquire the l2ad_mtx. If that happens, we don't
2131 * want to re-destroy the header's L2 portion.
ca0bf58d 2132 */
d962d5da
PS
2133 if (HDR_HAS_L2HDR(hdr))
2134 arc_hdr_l2hdr_destroy(hdr);
428870ff
BB
2135
2136 if (!buflist_held)
d962d5da 2137 mutex_exit(&dev->l2ad_mtx);
34dc7c2f
BB
2138 }
2139
b9541d6b 2140 if (!BUF_EMPTY(hdr))
428870ff 2141 buf_discard_identity(hdr);
b9541d6b 2142
34dc7c2f
BB
2143 if (hdr->b_freeze_cksum != NULL) {
2144 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2145 hdr->b_freeze_cksum = NULL;
2146 }
2147
b9541d6b
CW
2148 if (HDR_HAS_L1HDR(hdr)) {
2149 while (hdr->b_l1hdr.b_buf) {
2150 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2151
2152 if (buf->b_efunc != NULL) {
ca0bf58d 2153 mutex_enter(&arc_user_evicts_lock);
b9541d6b
CW
2154 mutex_enter(&buf->b_evict_lock);
2155 ASSERT(buf->b_hdr != NULL);
ca0bf58d 2156 arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE);
b9541d6b
CW
2157 hdr->b_l1hdr.b_buf = buf->b_next;
2158 buf->b_hdr = &arc_eviction_hdr;
2159 buf->b_next = arc_eviction_list;
2160 arc_eviction_list = buf;
2161 mutex_exit(&buf->b_evict_lock);
ca0bf58d
PS
2162 cv_signal(&arc_user_evicts_cv);
2163 mutex_exit(&arc_user_evicts_lock);
b9541d6b 2164 } else {
ca0bf58d 2165 arc_buf_destroy(hdr->b_l1hdr.b_buf, TRUE);
b9541d6b
CW
2166 }
2167 }
2168 }
2169
34dc7c2f 2170 ASSERT3P(hdr->b_hash_next, ==, NULL);
b9541d6b 2171 if (HDR_HAS_L1HDR(hdr)) {
ca0bf58d 2172 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
b9541d6b
CW
2173 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2174 kmem_cache_free(hdr_full_cache, hdr);
2175 } else {
2176 kmem_cache_free(hdr_l2only_cache, hdr);
2177 }
34dc7c2f
BB
2178}
2179
2180void
2181arc_buf_free(arc_buf_t *buf, void *tag)
2182{
2183 arc_buf_hdr_t *hdr = buf->b_hdr;
b9541d6b 2184 int hashed = hdr->b_l1hdr.b_state != arc_anon;
34dc7c2f
BB
2185
2186 ASSERT(buf->b_efunc == NULL);
2187 ASSERT(buf->b_data != NULL);
2188
2189 if (hashed) {
2190 kmutex_t *hash_lock = HDR_LOCK(hdr);
2191
2192 mutex_enter(hash_lock);
428870ff
BB
2193 hdr = buf->b_hdr;
2194 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2195
34dc7c2f 2196 (void) remove_reference(hdr, hash_lock, tag);
b9541d6b 2197 if (hdr->b_l1hdr.b_datacnt > 1) {
ca0bf58d 2198 arc_buf_destroy(buf, TRUE);
428870ff 2199 } else {
b9541d6b 2200 ASSERT(buf == hdr->b_l1hdr.b_buf);
428870ff 2201 ASSERT(buf->b_efunc == NULL);
2a432414 2202 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
428870ff 2203 }
34dc7c2f
BB
2204 mutex_exit(hash_lock);
2205 } else if (HDR_IO_IN_PROGRESS(hdr)) {
2206 int destroy_hdr;
2207 /*
2208 * We are in the middle of an async write. Don't destroy
2209 * this buffer unless the write completes before we finish
2210 * decrementing the reference count.
2211 */
ca0bf58d 2212 mutex_enter(&arc_user_evicts_lock);
34dc7c2f 2213 (void) remove_reference(hdr, NULL, tag);
b9541d6b 2214 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
34dc7c2f 2215 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
ca0bf58d 2216 mutex_exit(&arc_user_evicts_lock);
34dc7c2f
BB
2217 if (destroy_hdr)
2218 arc_hdr_destroy(hdr);
2219 } else {
428870ff 2220 if (remove_reference(hdr, NULL, tag) > 0)
ca0bf58d 2221 arc_buf_destroy(buf, TRUE);
428870ff 2222 else
34dc7c2f 2223 arc_hdr_destroy(hdr);
34dc7c2f
BB
2224 }
2225}
2226
13fe0198 2227boolean_t
34dc7c2f
BB
2228arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2229{
2230 arc_buf_hdr_t *hdr = buf->b_hdr;
96c080cb 2231 kmutex_t *hash_lock = HDR_LOCK(hdr);
13fe0198 2232 boolean_t no_callback = (buf->b_efunc == NULL);
34dc7c2f 2233
b9541d6b
CW
2234 if (hdr->b_l1hdr.b_state == arc_anon) {
2235 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
34dc7c2f
BB
2236 arc_buf_free(buf, tag);
2237 return (no_callback);
2238 }
2239
2240 mutex_enter(hash_lock);
428870ff 2241 hdr = buf->b_hdr;
b9541d6b 2242 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
428870ff 2243 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
b9541d6b 2244 ASSERT(hdr->b_l1hdr.b_state != arc_anon);
34dc7c2f
BB
2245 ASSERT(buf->b_data != NULL);
2246
2247 (void) remove_reference(hdr, hash_lock, tag);
b9541d6b 2248 if (hdr->b_l1hdr.b_datacnt > 1) {
34dc7c2f 2249 if (no_callback)
ca0bf58d 2250 arc_buf_destroy(buf, TRUE);
34dc7c2f 2251 } else if (no_callback) {
b9541d6b 2252 ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
428870ff 2253 ASSERT(buf->b_efunc == NULL);
2a432414 2254 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
34dc7c2f 2255 }
b9541d6b
CW
2256 ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2257 refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
34dc7c2f
BB
2258 mutex_exit(hash_lock);
2259 return (no_callback);
2260}
2261
5f6d0b6f 2262uint64_t
34dc7c2f
BB
2263arc_buf_size(arc_buf_t *buf)
2264{
2265 return (buf->b_hdr->b_size);
2266}
2267
1eb5bfa3
GW
2268/*
2269 * Called from the DMU to determine if the current buffer should be
2270 * evicted. In order to ensure proper locking, the eviction must be initiated
2271 * from the DMU. Return true if the buffer is associated with user data and
2272 * duplicate buffers still exist.
2273 */
2274boolean_t
2275arc_buf_eviction_needed(arc_buf_t *buf)
2276{
2277 arc_buf_hdr_t *hdr;
2278 boolean_t evict_needed = B_FALSE;
2279
2280 if (zfs_disable_dup_eviction)
2281 return (B_FALSE);
2282
2283 mutex_enter(&buf->b_evict_lock);
2284 hdr = buf->b_hdr;
2285 if (hdr == NULL) {
2286 /*
2287 * We are in arc_do_user_evicts(); let that function
2288 * perform the eviction.
2289 */
2290 ASSERT(buf->b_data == NULL);
2291 mutex_exit(&buf->b_evict_lock);
2292 return (B_FALSE);
2293 } else if (buf->b_data == NULL) {
2294 /*
2295 * We have already been added to the arc eviction list;
2296 * recommend eviction.
2297 */
2298 ASSERT3P(hdr, ==, &arc_eviction_hdr);
2299 mutex_exit(&buf->b_evict_lock);
2300 return (B_TRUE);
2301 }
2302
b9541d6b 2303 if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
1eb5bfa3
GW
2304 evict_needed = B_TRUE;
2305
2306 mutex_exit(&buf->b_evict_lock);
2307 return (evict_needed);
2308}
2309
34dc7c2f 2310/*
ca0bf58d
PS
2311 * Evict the arc_buf_hdr that is provided as a parameter. The resultant
2312 * state of the header is dependent on its state prior to entering this
2313 * function. The following transitions are possible:
34dc7c2f 2314 *
ca0bf58d
PS
2315 * - arc_mru -> arc_mru_ghost
2316 * - arc_mfu -> arc_mfu_ghost
2317 * - arc_mru_ghost -> arc_l2c_only
2318 * - arc_mru_ghost -> deleted
2319 * - arc_mfu_ghost -> arc_l2c_only
2320 * - arc_mfu_ghost -> deleted
34dc7c2f 2321 */
ca0bf58d
PS
2322static int64_t
2323arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
34dc7c2f 2324{
ca0bf58d
PS
2325 arc_state_t *evicted_state, *state;
2326 int64_t bytes_evicted = 0;
34dc7c2f 2327
ca0bf58d
PS
2328 ASSERT(MUTEX_HELD(hash_lock));
2329 ASSERT(HDR_HAS_L1HDR(hdr));
e8b96c60 2330
ca0bf58d
PS
2331 state = hdr->b_l1hdr.b_state;
2332 if (GHOST_STATE(state)) {
2333 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2334 ASSERT(hdr->b_l1hdr.b_buf == NULL);
e8b96c60
MA
2335
2336 /*
ca0bf58d
PS
2337 * l2arc_write_buffers() relies on a header's L1 portion
2338 * (i.e. its b_tmp_cdata field) during its write phase.
2339 * Thus, we cannot push a header onto the arc_l2c_only
2340 * state (removing its L1 piece) until the header is
2341 * done being written to the l2arc.
e8b96c60 2342 */
ca0bf58d
PS
2343 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
2344 ARCSTAT_BUMP(arcstat_evict_l2_skip);
2345 return (bytes_evicted);
e8b96c60
MA
2346 }
2347
ca0bf58d
PS
2348 ARCSTAT_BUMP(arcstat_deleted);
2349 bytes_evicted += hdr->b_size;
428870ff 2350
ca0bf58d 2351 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
428870ff 2352
ca0bf58d
PS
2353 if (HDR_HAS_L2HDR(hdr)) {
2354 /*
2355 * This buffer is cached on the 2nd Level ARC;
2356 * don't destroy the header.
2357 */
2358 arc_change_state(arc_l2c_only, hdr, hash_lock);
2359 /*
2360 * dropping from L1+L2 cached to L2-only,
2361 * realloc to remove the L1 header.
2362 */
2363 hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2364 hdr_l2only_cache);
34dc7c2f 2365 } else {
ca0bf58d
PS
2366 arc_change_state(arc_anon, hdr, hash_lock);
2367 arc_hdr_destroy(hdr);
34dc7c2f 2368 }
ca0bf58d 2369 return (bytes_evicted);
34dc7c2f
BB
2370 }
2371
ca0bf58d
PS
2372 ASSERT(state == arc_mru || state == arc_mfu);
2373 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
34dc7c2f 2374
ca0bf58d
PS
2375 /* prefetch buffers have a minimum lifespan */
2376 if (HDR_IO_IN_PROGRESS(hdr) ||
2377 ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2378 ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2379 arc_min_prefetch_lifespan)) {
2380 ARCSTAT_BUMP(arcstat_evict_skip);
2381 return (bytes_evicted);
da8ccd0e
PS
2382 }
2383
ca0bf58d
PS
2384 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2385 ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2386 while (hdr->b_l1hdr.b_buf) {
2387 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2388 if (!mutex_tryenter(&buf->b_evict_lock)) {
2389 ARCSTAT_BUMP(arcstat_mutex_miss);
2390 break;
2391 }
2392 if (buf->b_data != NULL)
2393 bytes_evicted += hdr->b_size;
2394 if (buf->b_efunc != NULL) {
2395 mutex_enter(&arc_user_evicts_lock);
2396 arc_buf_destroy(buf, FALSE);
2397 hdr->b_l1hdr.b_buf = buf->b_next;
2398 buf->b_hdr = &arc_eviction_hdr;
2399 buf->b_next = arc_eviction_list;
2400 arc_eviction_list = buf;
2401 cv_signal(&arc_user_evicts_cv);
2402 mutex_exit(&arc_user_evicts_lock);
2403 mutex_exit(&buf->b_evict_lock);
2404 } else {
2405 mutex_exit(&buf->b_evict_lock);
2406 arc_buf_destroy(buf, TRUE);
2407 }
2408 }
34dc7c2f 2409
ca0bf58d
PS
2410 if (HDR_HAS_L2HDR(hdr)) {
2411 ARCSTAT_INCR(arcstat_evict_l2_cached, hdr->b_size);
2412 } else {
2413 if (l2arc_write_eligible(hdr->b_spa, hdr))
2414 ARCSTAT_INCR(arcstat_evict_l2_eligible, hdr->b_size);
2415 else
2416 ARCSTAT_INCR(arcstat_evict_l2_ineligible, hdr->b_size);
2417 }
34dc7c2f 2418
ca0bf58d
PS
2419 if (hdr->b_l1hdr.b_datacnt == 0) {
2420 arc_change_state(evicted_state, hdr, hash_lock);
2421 ASSERT(HDR_IN_HASH_TABLE(hdr));
2422 hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2423 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2424 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2425 }
34dc7c2f 2426
ca0bf58d 2427 return (bytes_evicted);
34dc7c2f
BB
2428}
2429
ca0bf58d
PS
2430static uint64_t
2431arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
2432 uint64_t spa, int64_t bytes)
34dc7c2f 2433{
ca0bf58d
PS
2434 multilist_sublist_t *mls;
2435 uint64_t bytes_evicted = 0;
2436 arc_buf_hdr_t *hdr;
34dc7c2f 2437 kmutex_t *hash_lock;
ca0bf58d 2438 int evict_count = 0;
34dc7c2f 2439
ca0bf58d 2440 ASSERT3P(marker, !=, NULL);
96c080cb 2441 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
ca0bf58d
PS
2442
2443 mls = multilist_sublist_lock(ml, idx);
572e2857 2444
ca0bf58d
PS
2445 for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
2446 hdr = multilist_sublist_prev(mls, marker)) {
2447 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
2448 (evict_count >= zfs_arc_evict_batch_limit))
2449 break;
2450
2451 /*
2452 * To keep our iteration location, move the marker
2453 * forward. Since we're not holding hdr's hash lock, we
2454 * must be very careful and not remove 'hdr' from the
2455 * sublist. Otherwise, other consumers might mistake the
2456 * 'hdr' as not being on a sublist when they call the
2457 * multilist_link_active() function (they all rely on
2458 * the hash lock protecting concurrent insertions and
2459 * removals). multilist_sublist_move_forward() was
2460 * specifically implemented to ensure this is the case
2461 * (only 'marker' will be removed and re-inserted).
2462 */
2463 multilist_sublist_move_forward(mls, marker);
2464
2465 /*
2466 * The only case where the b_spa field should ever be
2467 * zero, is the marker headers inserted by
2468 * arc_evict_state(). It's possible for multiple threads
2469 * to be calling arc_evict_state() concurrently (e.g.
2470 * dsl_pool_close() and zio_inject_fault()), so we must
2471 * skip any markers we see from these other threads.
2472 */
2a432414 2473 if (hdr->b_spa == 0)
572e2857
BB
2474 continue;
2475
ca0bf58d
PS
2476 /* we're only interested in evicting buffers of a certain spa */
2477 if (spa != 0 && hdr->b_spa != spa) {
2478 ARCSTAT_BUMP(arcstat_evict_skip);
428870ff 2479 continue;
ca0bf58d
PS
2480 }
2481
2482 hash_lock = HDR_LOCK(hdr);
e8b96c60
MA
2483
2484 /*
ca0bf58d
PS
2485 * We aren't calling this function from any code path
2486 * that would already be holding a hash lock, so we're
2487 * asserting on this assumption to be defensive in case
2488 * this ever changes. Without this check, it would be
2489 * possible to incorrectly increment arcstat_mutex_miss
2490 * below (e.g. if the code changed such that we called
2491 * this function with a hash lock held).
e8b96c60 2492 */
ca0bf58d
PS
2493 ASSERT(!MUTEX_HELD(hash_lock));
2494
34dc7c2f 2495 if (mutex_tryenter(hash_lock)) {
ca0bf58d
PS
2496 uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
2497 mutex_exit(hash_lock);
34dc7c2f 2498
ca0bf58d 2499 bytes_evicted += evicted;
34dc7c2f 2500
572e2857 2501 /*
ca0bf58d
PS
2502 * If evicted is zero, arc_evict_hdr() must have
2503 * decided to skip this header, don't increment
2504 * evict_count in this case.
572e2857 2505 */
ca0bf58d
PS
2506 if (evicted != 0)
2507 evict_count++;
2508
2509 /*
2510 * If arc_size isn't overflowing, signal any
2511 * threads that might happen to be waiting.
2512 *
2513 * For each header evicted, we wake up a single
2514 * thread. If we used cv_broadcast, we could
2515 * wake up "too many" threads causing arc_size
2516 * to significantly overflow arc_c; since
2517 * arc_get_data_buf() doesn't check for overflow
2518 * when it's woken up (it doesn't because it's
2519 * possible for the ARC to be overflowing while
2520 * full of un-evictable buffers, and the
2521 * function should proceed in this case).
2522 *
2523 * If threads are left sleeping, due to not
2524 * using cv_broadcast, they will be woken up
2525 * just before arc_reclaim_thread() sleeps.
2526 */
2527 mutex_enter(&arc_reclaim_lock);
2528 if (!arc_is_overflowing())
2529 cv_signal(&arc_reclaim_waiters_cv);
2530 mutex_exit(&arc_reclaim_lock);
e8b96c60 2531 } else {
ca0bf58d 2532 ARCSTAT_BUMP(arcstat_mutex_miss);
e8b96c60 2533 }
34dc7c2f 2534 }
34dc7c2f 2535
ca0bf58d 2536 multilist_sublist_unlock(mls);
34dc7c2f 2537
ca0bf58d 2538 return (bytes_evicted);
34dc7c2f
BB
2539}
2540
ca0bf58d
PS
2541/*
2542 * Evict buffers from the given arc state, until we've removed the
2543 * specified number of bytes. Move the removed buffers to the
2544 * appropriate evict state.
2545 *
2546 * This function makes a "best effort". It skips over any buffers
2547 * it can't get a hash_lock on, and so, may not catch all candidates.
2548 * It may also return without evicting as much space as requested.
2549 *
2550 * If bytes is specified using the special value ARC_EVICT_ALL, this
2551 * will evict all available (i.e. unlocked and evictable) buffers from
2552 * the given arc state; which is used by arc_flush().
2553 */
2554static uint64_t
2555arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
2556 arc_buf_contents_t type)
34dc7c2f 2557{
ca0bf58d
PS
2558 uint64_t total_evicted = 0;
2559 multilist_t *ml = &state->arcs_list[type];
2560 int num_sublists;
2561 arc_buf_hdr_t **markers;
2562 int i;
2563
96c080cb 2564 IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
ca0bf58d
PS
2565
2566 num_sublists = multilist_get_num_sublists(ml);
d164b209
BB
2567
2568 /*
ca0bf58d
PS
2569 * If we've tried to evict from each sublist, made some
2570 * progress, but still have not hit the target number of bytes
2571 * to evict, we want to keep trying. The markers allow us to
2572 * pick up where we left off for each individual sublist, rather
2573 * than starting from the tail each time.
d164b209 2574 */
ca0bf58d
PS
2575 markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
2576 for (i = 0; i < num_sublists; i++) {
2577 multilist_sublist_t *mls;
34dc7c2f 2578
ca0bf58d
PS
2579 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
2580
2581 /*
2582 * A b_spa of 0 is used to indicate that this header is
2583 * a marker. This fact is used in arc_adjust_type() and
2584 * arc_evict_state_impl().
2585 */
2586 markers[i]->b_spa = 0;
34dc7c2f 2587
ca0bf58d
PS
2588 mls = multilist_sublist_lock(ml, i);
2589 multilist_sublist_insert_tail(mls, markers[i]);
2590 multilist_sublist_unlock(mls);
34dc7c2f
BB
2591 }
2592
d164b209 2593 /*
ca0bf58d
PS
2594 * While we haven't hit our target number of bytes to evict, or
2595 * we're evicting all available buffers.
d164b209 2596 */
ca0bf58d
PS
2597 while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
2598 /*
2599 * Start eviction using a randomly selected sublist,
2600 * this is to try and evenly balance eviction across all
2601 * sublists. Always starting at the same sublist
2602 * (e.g. index 0) would cause evictions to favor certain
2603 * sublists over others.
2604 */
2605 int sublist_idx = multilist_get_random_index(ml);
2606 uint64_t scan_evicted = 0;
34dc7c2f 2607
ca0bf58d
PS
2608 for (i = 0; i < num_sublists; i++) {
2609 uint64_t bytes_remaining;
2610 uint64_t bytes_evicted;
d164b209 2611
ca0bf58d
PS
2612 if (bytes == ARC_EVICT_ALL)
2613 bytes_remaining = ARC_EVICT_ALL;
2614 else if (total_evicted < bytes)
2615 bytes_remaining = bytes - total_evicted;
2616 else
2617 break;
34dc7c2f 2618
ca0bf58d
PS
2619 bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
2620 markers[sublist_idx], spa, bytes_remaining);
2621
2622 scan_evicted += bytes_evicted;
2623 total_evicted += bytes_evicted;
2624
2625 /* we've reached the end, wrap to the beginning */
2626 if (++sublist_idx >= num_sublists)
2627 sublist_idx = 0;
2628 }
2629
2630 /*
2631 * If we didn't evict anything during this scan, we have
2632 * no reason to believe we'll evict more during another
2633 * scan, so break the loop.
2634 */
2635 if (scan_evicted == 0) {
2636 /* This isn't possible, let's make that obvious */
2637 ASSERT3S(bytes, !=, 0);
34dc7c2f 2638
ca0bf58d
PS
2639 /*
2640 * When bytes is ARC_EVICT_ALL, the only way to
2641 * break the loop is when scan_evicted is zero.
2642 * In that case, we actually have evicted enough,
2643 * so we don't want to increment the kstat.
2644 */
2645 if (bytes != ARC_EVICT_ALL) {
2646 ASSERT3S(total_evicted, <, bytes);
2647 ARCSTAT_BUMP(arcstat_evict_not_enough);
2648 }
d164b209 2649
ca0bf58d
PS
2650 break;
2651 }
d164b209 2652 }
34dc7c2f 2653
ca0bf58d
PS
2654 for (i = 0; i < num_sublists; i++) {
2655 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
2656 multilist_sublist_remove(mls, markers[i]);
2657 multilist_sublist_unlock(mls);
34dc7c2f 2658
ca0bf58d 2659 kmem_cache_free(hdr_full_cache, markers[i]);
34dc7c2f 2660 }
ca0bf58d
PS
2661 kmem_free(markers, sizeof (*markers) * num_sublists);
2662
2663 return (total_evicted);
2664}
2665
2666/*
2667 * Flush all "evictable" data of the given type from the arc state
2668 * specified. This will not evict any "active" buffers (i.e. referenced).
2669 *
2670 * When 'retry' is set to FALSE, the function will make a single pass
2671 * over the state and evict any buffers that it can. Since it doesn't
2672 * continually retry the eviction, it might end up leaving some buffers
2673 * in the ARC due to lock misses.
2674 *
2675 * When 'retry' is set to TRUE, the function will continually retry the
2676 * eviction until *all* evictable buffers have been removed from the
2677 * state. As a result, if concurrent insertions into the state are
2678 * allowed (e.g. if the ARC isn't shutting down), this function might
2679 * wind up in an infinite loop, continually trying to evict buffers.
2680 */
2681static uint64_t
2682arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
2683 boolean_t retry)
2684{
2685 uint64_t evicted = 0;
2686
2687 while (state->arcs_lsize[type] != 0) {
2688 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
2689
2690 if (!retry)
2691 break;
2692 }
2693
2694 return (evicted);
34dc7c2f
BB
2695}
2696
ab26409d 2697/*
ef5b2e10
BB
2698 * Helper function for arc_prune_async() it is responsible for safely
2699 * handling the execution of a registered arc_prune_func_t.
ab26409d
BB
2700 */
2701static void
f6046738 2702arc_prune_task(void *ptr)
ab26409d 2703{
f6046738
BB
2704 arc_prune_t *ap = (arc_prune_t *)ptr;
2705 arc_prune_func_t *func = ap->p_pfunc;
ab26409d 2706
f6046738
BB
2707 if (func != NULL)
2708 func(ap->p_adjust, ap->p_private);
ab26409d 2709
4442f60d 2710 refcount_remove(&ap->p_refcnt, func);
f6046738 2711}
ab26409d 2712
f6046738
BB
2713/*
2714 * Notify registered consumers they must drop holds on a portion of the ARC
2715 * buffered they reference. This provides a mechanism to ensure the ARC can
2716 * honor the arc_meta_limit and reclaim otherwise pinned ARC buffers. This
2717 * is analogous to dnlc_reduce_cache() but more generic.
2718 *
ef5b2e10 2719 * This operation is performed asynchronously so it may be safely called
ca67b33a 2720 * in the context of the arc_reclaim_thread(). A reference is taken here
f6046738
BB
2721 * for each registered arc_prune_t and the arc_prune_task() is responsible
2722 * for releasing it once the registered arc_prune_func_t has completed.
2723 */
2724static void
2725arc_prune_async(int64_t adjust)
2726{
2727 arc_prune_t *ap;
ab26409d 2728
f6046738
BB
2729 mutex_enter(&arc_prune_mtx);
2730 for (ap = list_head(&arc_prune_list); ap != NULL;
2731 ap = list_next(&arc_prune_list, ap)) {
ab26409d 2732
f6046738
BB
2733 if (refcount_count(&ap->p_refcnt) >= 2)
2734 continue;
ab26409d 2735
f6046738
BB
2736 refcount_add(&ap->p_refcnt, ap->p_pfunc);
2737 ap->p_adjust = adjust;
2738 taskq_dispatch(arc_prune_taskq, arc_prune_task, ap, TQ_SLEEP);
2739 ARCSTAT_BUMP(arcstat_prune);
ab26409d 2740 }
ab26409d
BB
2741 mutex_exit(&arc_prune_mtx);
2742}
2743
ca0bf58d
PS
2744/*
2745 * Evict the specified number of bytes from the state specified,
2746 * restricting eviction to the spa and type given. This function
2747 * prevents us from trying to evict more from a state's list than
2748 * is "evictable", and to skip evicting altogether when passed a
2749 * negative value for "bytes". In contrast, arc_evict_state() will
2750 * evict everything it can, when passed a negative value for "bytes".
2751 */
2752static uint64_t
2753arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
2754 arc_buf_contents_t type)
2755{
2756 int64_t delta;
2757
2758 if (bytes > 0 && state->arcs_lsize[type] > 0) {
2759 delta = MIN(state->arcs_lsize[type], bytes);
2760 return (arc_evict_state(state, spa, delta, type));
2761 }
2762
2763 return (0);
2764}
2765
2766/*
2767 * The goal of this function is to evict enough meta data buffers from the
2768 * ARC in order to enforce the arc_meta_limit. Achieving this is slightly
2769 * more complicated than it appears because it is common for data buffers
2770 * to have holds on meta data buffers. In addition, dnode meta data buffers
2771 * will be held by the dnodes in the block preventing them from being freed.
2772 * This means we can't simply traverse the ARC and expect to always find
2773 * enough unheld meta data buffer to release.
2774 *
2775 * Therefore, this function has been updated to make alternating passes
2776 * over the ARC releasing data buffers and then newly unheld meta data
2777 * buffers. This ensures forward progress is maintained and arc_meta_used
2778 * will decrease. Normally this is sufficient, but if required the ARC
2779 * will call the registered prune callbacks causing dentry and inodes to
2780 * be dropped from the VFS cache. This will make dnode meta data buffers
2781 * available for reclaim.
2782 */
2783static uint64_t
f6046738 2784arc_adjust_meta_balanced(void)
ca0bf58d
PS
2785{
2786 int64_t adjustmnt, delta, prune = 0;
2787 uint64_t total_evicted = 0;
2788 arc_buf_contents_t type = ARC_BUFC_DATA;
ca67b33a 2789 int restarts = MAX(zfs_arc_meta_adjust_restarts, 0);
ca0bf58d
PS
2790
2791restart:
2792 /*
2793 * This slightly differs than the way we evict from the mru in
2794 * arc_adjust because we don't have a "target" value (i.e. no
2795 * "meta" arc_p). As a result, I think we can completely
2796 * cannibalize the metadata in the MRU before we evict the
2797 * metadata from the MFU. I think we probably need to implement a
2798 * "metadata arc_p" value to do this properly.
2799 */
2800 adjustmnt = arc_meta_used - arc_meta_limit;
2801
2802 if (adjustmnt > 0 && arc_mru->arcs_lsize[type] > 0) {
2803 delta = MIN(arc_mru->arcs_lsize[type], adjustmnt);
2804 total_evicted += arc_adjust_impl(arc_mru, 0, delta, type);
2805 adjustmnt -= delta;
2806 }
2807
2808 /*
2809 * We can't afford to recalculate adjustmnt here. If we do,
2810 * new metadata buffers can sneak into the MRU or ANON lists,
2811 * thus penalize the MFU metadata. Although the fudge factor is
2812 * small, it has been empirically shown to be significant for
2813 * certain workloads (e.g. creating many empty directories). As
2814 * such, we use the original calculation for adjustmnt, and
2815 * simply decrement the amount of data evicted from the MRU.
2816 */
2817
2818 if (adjustmnt > 0 && arc_mfu->arcs_lsize[type] > 0) {
2819 delta = MIN(arc_mfu->arcs_lsize[type], adjustmnt);
2820 total_evicted += arc_adjust_impl(arc_mfu, 0, delta, type);
2821 }
2822
2823 adjustmnt = arc_meta_used - arc_meta_limit;
2824
2825 if (adjustmnt > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
2826 delta = MIN(adjustmnt,
2827 arc_mru_ghost->arcs_lsize[type]);
2828 total_evicted += arc_adjust_impl(arc_mru_ghost, 0, delta, type);
2829 adjustmnt -= delta;
2830 }
2831
2832 if (adjustmnt > 0 && arc_mfu_ghost->arcs_lsize[type] > 0) {
2833 delta = MIN(adjustmnt,
2834 arc_mfu_ghost->arcs_lsize[type]);
2835 total_evicted += arc_adjust_impl(arc_mfu_ghost, 0, delta, type);
2836 }
2837
2838 /*
2839 * If after attempting to make the requested adjustment to the ARC
2840 * the meta limit is still being exceeded then request that the
2841 * higher layers drop some cached objects which have holds on ARC
2842 * meta buffers. Requests to the upper layers will be made with
2843 * increasingly large scan sizes until the ARC is below the limit.
2844 */
2845 if (arc_meta_used > arc_meta_limit) {
2846 if (type == ARC_BUFC_DATA) {
2847 type = ARC_BUFC_METADATA;
2848 } else {
2849 type = ARC_BUFC_DATA;
2850
2851 if (zfs_arc_meta_prune) {
2852 prune += zfs_arc_meta_prune;
f6046738 2853 arc_prune_async(prune);
ca0bf58d
PS
2854 }
2855 }
2856
2857 if (restarts > 0) {
2858 restarts--;
2859 goto restart;
2860 }
2861 }
2862 return (total_evicted);
2863}
2864
f6046738
BB
2865/*
2866 * Evict metadata buffers from the cache, such that arc_meta_used is
2867 * capped by the arc_meta_limit tunable.
2868 */
2869static uint64_t
2870arc_adjust_meta_only(void)
2871{
2872 uint64_t total_evicted = 0;
2873 int64_t target;
2874
2875 /*
2876 * If we're over the meta limit, we want to evict enough
2877 * metadata to get back under the meta limit. We don't want to
2878 * evict so much that we drop the MRU below arc_p, though. If
2879 * we're over the meta limit more than we're over arc_p, we
2880 * evict some from the MRU here, and some from the MFU below.
2881 */
2882 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
36da08ef
PS
2883 (int64_t)(refcount_count(&arc_anon->arcs_size) +
2884 refcount_count(&arc_mru->arcs_size) - arc_p));
f6046738
BB
2885
2886 total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
2887
2888 /*
2889 * Similar to the above, we want to evict enough bytes to get us
2890 * below the meta limit, but not so much as to drop us below the
2891 * space alloted to the MFU (which is defined as arc_c - arc_p).
2892 */
2893 target = MIN((int64_t)(arc_meta_used - arc_meta_limit),
36da08ef 2894 (int64_t)(refcount_count(&arc_mfu->arcs_size) - (arc_c - arc_p)));
f6046738
BB
2895
2896 total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
2897
2898 return (total_evicted);
2899}
2900
2901static uint64_t
2902arc_adjust_meta(void)
2903{
2904 if (zfs_arc_meta_strategy == ARC_STRATEGY_META_ONLY)
2905 return (arc_adjust_meta_only());
2906 else
2907 return (arc_adjust_meta_balanced());
2908}
2909
ca0bf58d
PS
2910/*
2911 * Return the type of the oldest buffer in the given arc state
2912 *
2913 * This function will select a random sublist of type ARC_BUFC_DATA and
2914 * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
2915 * is compared, and the type which contains the "older" buffer will be
2916 * returned.
2917 */
2918static arc_buf_contents_t
2919arc_adjust_type(arc_state_t *state)
2920{
2921 multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
2922 multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
2923 int data_idx = multilist_get_random_index(data_ml);
2924 int meta_idx = multilist_get_random_index(meta_ml);
2925 multilist_sublist_t *data_mls;
2926 multilist_sublist_t *meta_mls;
2927 arc_buf_contents_t type;
2928 arc_buf_hdr_t *data_hdr;
2929 arc_buf_hdr_t *meta_hdr;
2930
2931 /*
2932 * We keep the sublist lock until we're finished, to prevent
2933 * the headers from being destroyed via arc_evict_state().
2934 */
2935 data_mls = multilist_sublist_lock(data_ml, data_idx);
2936 meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
2937
2938 /*
2939 * These two loops are to ensure we skip any markers that
2940 * might be at the tail of the lists due to arc_evict_state().
2941 */
2942
2943 for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
2944 data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
2945 if (data_hdr->b_spa != 0)
2946 break;
2947 }
2948
2949 for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
2950 meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
2951 if (meta_hdr->b_spa != 0)
2952 break;
2953 }
2954
2955 if (data_hdr == NULL && meta_hdr == NULL) {
2956 type = ARC_BUFC_DATA;
2957 } else if (data_hdr == NULL) {
2958 ASSERT3P(meta_hdr, !=, NULL);
2959 type = ARC_BUFC_METADATA;
2960 } else if (meta_hdr == NULL) {
2961 ASSERT3P(data_hdr, !=, NULL);
2962 type = ARC_BUFC_DATA;
2963 } else {
2964 ASSERT3P(data_hdr, !=, NULL);
2965 ASSERT3P(meta_hdr, !=, NULL);
2966
2967 /* The headers can't be on the sublist without an L1 header */
2968 ASSERT(HDR_HAS_L1HDR(data_hdr));
2969 ASSERT(HDR_HAS_L1HDR(meta_hdr));
2970
2971 if (data_hdr->b_l1hdr.b_arc_access <
2972 meta_hdr->b_l1hdr.b_arc_access) {
2973 type = ARC_BUFC_DATA;
2974 } else {
2975 type = ARC_BUFC_METADATA;
2976 }
2977 }
2978
2979 multilist_sublist_unlock(meta_mls);
2980 multilist_sublist_unlock(data_mls);
2981
2982 return (type);
2983}
2984
2985/*
2986 * Evict buffers from the cache, such that arc_size is capped by arc_c.
2987 */
2988static uint64_t
2989arc_adjust(void)
2990{
2991 uint64_t total_evicted = 0;
2992 uint64_t bytes;
2993 int64_t target;
2994
2995 /*
2996 * If we're over arc_meta_limit, we want to correct that before
2997 * potentially evicting data buffers below.
2998 */
2999 total_evicted += arc_adjust_meta();
3000
3001 /*
3002 * Adjust MRU size
3003 *
3004 * If we're over the target cache size, we want to evict enough
3005 * from the list to get back to our target size. We don't want
3006 * to evict too much from the MRU, such that it drops below
3007 * arc_p. So, if we're over our target cache size more than
3008 * the MRU is over arc_p, we'll evict enough to get back to
3009 * arc_p here, and then evict more from the MFU below.
3010 */
3011 target = MIN((int64_t)(arc_size - arc_c),
36da08ef
PS
3012 (int64_t)(refcount_count(&arc_anon->arcs_size) +
3013 refcount_count(&arc_mru->arcs_size) + arc_meta_used - arc_p));
ca0bf58d
PS
3014
3015 /*
3016 * If we're below arc_meta_min, always prefer to evict data.
3017 * Otherwise, try to satisfy the requested number of bytes to
3018 * evict from the type which contains older buffers; in an
3019 * effort to keep newer buffers in the cache regardless of their
3020 * type. If we cannot satisfy the number of bytes from this
3021 * type, spill over into the next type.
3022 */
3023 if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3024 arc_meta_used > arc_meta_min) {
3025 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3026 total_evicted += bytes;
3027
3028 /*
3029 * If we couldn't evict our target number of bytes from
3030 * metadata, we try to get the rest from data.
3031 */
3032 target -= bytes;
3033
3034 total_evicted +=
3035 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3036 } else {
3037 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3038 total_evicted += bytes;
3039
3040 /*
3041 * If we couldn't evict our target number of bytes from
3042 * data, we try to get the rest from metadata.
3043 */
3044 target -= bytes;
3045
3046 total_evicted +=
3047 arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3048 }
3049
3050 /*
3051 * Adjust MFU size
3052 *
3053 * Now that we've tried to evict enough from the MRU to get its
3054 * size back to arc_p, if we're still above the target cache
3055 * size, we evict the rest from the MFU.
3056 */
3057 target = arc_size - arc_c;
3058
a7b10a93 3059 if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
ca0bf58d
PS
3060 arc_meta_used > arc_meta_min) {
3061 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3062 total_evicted += bytes;
3063
3064 /*
3065 * If we couldn't evict our target number of bytes from
3066 * metadata, we try to get the rest from data.
3067 */
3068 target -= bytes;
3069
3070 total_evicted +=
3071 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3072 } else {
3073 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3074 total_evicted += bytes;
3075
3076 /*
3077 * If we couldn't evict our target number of bytes from
3078 * data, we try to get the rest from data.
3079 */
3080 target -= bytes;
3081
3082 total_evicted +=
3083 arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3084 }
3085
3086 /*
3087 * Adjust ghost lists
3088 *
3089 * In addition to the above, the ARC also defines target values
3090 * for the ghost lists. The sum of the mru list and mru ghost
3091 * list should never exceed the target size of the cache, and
3092 * the sum of the mru list, mfu list, mru ghost list, and mfu
3093 * ghost list should never exceed twice the target size of the
3094 * cache. The following logic enforces these limits on the ghost
3095 * caches, and evicts from them as needed.
3096 */
36da08ef
PS
3097 target = refcount_count(&arc_mru->arcs_size) +
3098 refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
ca0bf58d
PS
3099
3100 bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3101 total_evicted += bytes;
3102
3103 target -= bytes;
3104
3105 total_evicted +=
3106 arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3107
3108 /*
3109 * We assume the sum of the mru list and mfu list is less than
3110 * or equal to arc_c (we enforced this above), which means we
3111 * can use the simpler of the two equations below:
3112 *
3113 * mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3114 * mru ghost + mfu ghost <= arc_c
3115 */
36da08ef
PS
3116 target = refcount_count(&arc_mru_ghost->arcs_size) +
3117 refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
ca0bf58d
PS
3118
3119 bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3120 total_evicted += bytes;
3121
3122 target -= bytes;
3123
3124 total_evicted +=
3125 arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3126
3127 return (total_evicted);
3128}
3129
34dc7c2f
BB
3130static void
3131arc_do_user_evicts(void)
3132{
ca0bf58d 3133 mutex_enter(&arc_user_evicts_lock);
34dc7c2f
BB
3134 while (arc_eviction_list != NULL) {
3135 arc_buf_t *buf = arc_eviction_list;
3136 arc_eviction_list = buf->b_next;
428870ff 3137 mutex_enter(&buf->b_evict_lock);
34dc7c2f 3138 buf->b_hdr = NULL;
428870ff 3139 mutex_exit(&buf->b_evict_lock);
ca0bf58d 3140 mutex_exit(&arc_user_evicts_lock);
34dc7c2f
BB
3141
3142 if (buf->b_efunc != NULL)
bd089c54 3143 VERIFY0(buf->b_efunc(buf->b_private));
34dc7c2f
BB
3144
3145 buf->b_efunc = NULL;
3146 buf->b_private = NULL;
3147 kmem_cache_free(buf_cache, buf);
ca0bf58d 3148 mutex_enter(&arc_user_evicts_lock);
34dc7c2f 3149 }
ca0bf58d 3150 mutex_exit(&arc_user_evicts_lock);
34dc7c2f
BB
3151}
3152
ca0bf58d
PS
3153void
3154arc_flush(spa_t *spa, boolean_t retry)
ab26409d 3155{
ca0bf58d 3156 uint64_t guid = 0;
94520ca4 3157
bc888666 3158 /*
ca0bf58d
PS
3159 * If retry is TRUE, a spa must not be specified since we have
3160 * no good way to determine if all of a spa's buffers have been
3161 * evicted from an arc state.
bc888666 3162 */
ca0bf58d 3163 ASSERT(!retry || spa == 0);
d164b209 3164
b9541d6b 3165 if (spa != NULL)
3541dc6d 3166 guid = spa_load_guid(spa);
d164b209 3167
ca0bf58d
PS
3168 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3169 (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3170
3171 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3172 (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3173
3174 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3175 (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
34dc7c2f 3176
ca0bf58d
PS
3177 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3178 (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
34dc7c2f 3179
34dc7c2f 3180 arc_do_user_evicts();
34dc7c2f
BB
3181 ASSERT(spa || arc_eviction_list == NULL);
3182}
3183
34dc7c2f 3184void
ca67b33a 3185arc_shrink(int64_t to_free)
34dc7c2f 3186{
1b8951b3 3187 uint64_t c = arc_c;
34dc7c2f 3188
1b8951b3
TC
3189 if (c > to_free && c - to_free > arc_c_min) {
3190 arc_c = c - to_free;
ca67b33a 3191 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
34dc7c2f
BB
3192 if (arc_c > arc_size)
3193 arc_c = MAX(arc_size, arc_c_min);
3194 if (arc_p > arc_c)
3195 arc_p = (arc_c >> 1);
3196 ASSERT(arc_c >= arc_c_min);
3197 ASSERT((int64_t)arc_p >= 0);
1b8951b3
TC
3198 } else {
3199 arc_c = arc_c_min;
34dc7c2f
BB
3200 }
3201
3202 if (arc_size > arc_c)
ca0bf58d 3203 (void) arc_adjust();
34dc7c2f
BB
3204}
3205
ca67b33a
MA
3206typedef enum free_memory_reason_t {
3207 FMR_UNKNOWN,
3208 FMR_NEEDFREE,
3209 FMR_LOTSFREE,
3210 FMR_SWAPFS_MINFREE,
3211 FMR_PAGES_PP_MAXIMUM,
3212 FMR_HEAP_ARENA,
3213 FMR_ZIO_ARENA,
3214} free_memory_reason_t;
3215
3216int64_t last_free_memory;
3217free_memory_reason_t last_free_reason;
3218
3219#ifdef _KERNEL
ca67b33a
MA
3220/*
3221 * Additional reserve of pages for pp_reserve.
3222 */
3223int64_t arc_pages_pp_reserve = 64;
3224
3225/*
3226 * Additional reserve of pages for swapfs.
3227 */
3228int64_t arc_swapfs_reserve = 64;
ca67b33a
MA
3229#endif /* _KERNEL */
3230
3231/*
3232 * Return the amount of memory that can be consumed before reclaim will be
3233 * needed. Positive if there is sufficient free memory, negative indicates
3234 * the amount of memory that needs to be freed up.
3235 */
3236static int64_t
3237arc_available_memory(void)
3238{
3239 int64_t lowest = INT64_MAX;
3240 free_memory_reason_t r = FMR_UNKNOWN;
ca67b33a 3241#ifdef _KERNEL
ca67b33a 3242 int64_t n;
11f552fa
BB
3243#ifdef __linux__
3244 pgcnt_t needfree = btop(arc_need_free);
3245 pgcnt_t lotsfree = btop(arc_sys_free);
3246 pgcnt_t desfree = 0;
3247#endif
ca67b33a 3248
ca67b33a
MA
3249 if (needfree > 0) {
3250 n = PAGESIZE * (-needfree);
3251 if (n < lowest) {
3252 lowest = n;
3253 r = FMR_NEEDFREE;
3254 }
3255 }
3256
3257 /*
3258 * check that we're out of range of the pageout scanner. It starts to
3259 * schedule paging if freemem is less than lotsfree and needfree.
3260 * lotsfree is the high-water mark for pageout, and needfree is the
3261 * number of needed free pages. We add extra pages here to make sure
3262 * the scanner doesn't start up while we're freeing memory.
3263 */
3264 n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3265 if (n < lowest) {
3266 lowest = n;
3267 r = FMR_LOTSFREE;
3268 }
3269
11f552fa 3270#ifndef __linux__
ca67b33a
MA
3271 /*
3272 * check to make sure that swapfs has enough space so that anon
3273 * reservations can still succeed. anon_resvmem() checks that the
3274 * availrmem is greater than swapfs_minfree, and the number of reserved
3275 * swap pages. We also add a bit of extra here just to prevent
3276 * circumstances from getting really dire.
3277 */
3278 n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3279 desfree - arc_swapfs_reserve);
3280 if (n < lowest) {
3281 lowest = n;
3282 r = FMR_SWAPFS_MINFREE;
3283 }
3284
3285
3286 /*
3287 * Check that we have enough availrmem that memory locking (e.g., via
3288 * mlock(3C) or memcntl(2)) can still succeed. (pages_pp_maximum
3289 * stores the number of pages that cannot be locked; when availrmem
3290 * drops below pages_pp_maximum, page locking mechanisms such as
3291 * page_pp_lock() will fail.)
3292 */
3293 n = PAGESIZE * (availrmem - pages_pp_maximum -
3294 arc_pages_pp_reserve);
3295 if (n < lowest) {
3296 lowest = n;
3297 r = FMR_PAGES_PP_MAXIMUM;
3298 }
11f552fa 3299#endif
ca67b33a
MA
3300
3301#if defined(__i386)
3302 /*
3303 * If we're on an i386 platform, it's possible that we'll exhaust the
3304 * kernel heap space before we ever run out of available physical
3305 * memory. Most checks of the size of the heap_area compare against
3306 * tune.t_minarmem, which is the minimum available real memory that we
3307 * can have in the system. However, this is generally fixed at 25 pages
3308 * which is so low that it's useless. In this comparison, we seek to
3309 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3310 * heap is allocated. (Or, in the calculation, if less than 1/4th is
3311 * free)
3312 */
3313 n = vmem_size(heap_arena, VMEM_FREE) -
3314 (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3315 if (n < lowest) {
3316 lowest = n;
3317 r = FMR_HEAP_ARENA;
3318 }
3319#endif
3320
3321 /*
3322 * If zio data pages are being allocated out of a separate heap segment,
3323 * then enforce that the size of available vmem for this arena remains
3324 * above about 1/16th free.
3325 *
3326 * Note: The 1/16th arena free requirement was put in place
3327 * to aggressively evict memory from the arc in order to avoid
3328 * memory fragmentation issues.
3329 */
3330 if (zio_arena != NULL) {
3331 n = vmem_size(zio_arena, VMEM_FREE) -
3332 (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3333 if (n < lowest) {
3334 lowest = n;
3335 r = FMR_ZIO_ARENA;
3336 }
3337 }
11f552fa 3338#else /* _KERNEL */
ca67b33a
MA
3339 /* Every 100 calls, free a small amount */
3340 if (spa_get_random(100) == 0)
3341 lowest = -1024;
11f552fa 3342#endif /* _KERNEL */
ca67b33a
MA
3343
3344 last_free_memory = lowest;
3345 last_free_reason = r;
3346
3347 return (lowest);
3348}
3349
3350/*
3351 * Determine if the system is under memory pressure and is asking
3352 * to reclaim memory. A return value of TRUE indicates that the system
3353 * is under memory pressure and that the arc should adjust accordingly.
3354 */
3355static boolean_t
3356arc_reclaim_needed(void)
3357{
3358 return (arc_available_memory() < 0);
3359}
3360
34dc7c2f 3361static void
ca67b33a 3362arc_kmem_reap_now(void)
34dc7c2f
BB
3363{
3364 size_t i;
3365 kmem_cache_t *prev_cache = NULL;
3366 kmem_cache_t *prev_data_cache = NULL;
3367 extern kmem_cache_t *zio_buf_cache[];
3368 extern kmem_cache_t *zio_data_buf_cache[];
669dedb3 3369 extern kmem_cache_t *range_seg_cache;
34dc7c2f 3370
f6046738
BB
3371 if ((arc_meta_used >= arc_meta_limit) && zfs_arc_meta_prune) {
3372 /*
3373 * We are exceeding our meta-data cache limit.
3374 * Prune some entries to release holds on meta-data.
3375 */
ef5b2e10 3376 arc_prune_async(zfs_arc_meta_prune);
f6046738
BB
3377 }
3378
34dc7c2f 3379 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
d0c614ec 3380#ifdef _ILP32
3381 /* reach upper limit of cache size on 32-bit */
3382 if (zio_buf_cache[i] == NULL)
3383 break;
3384#endif
34dc7c2f
BB
3385 if (zio_buf_cache[i] != prev_cache) {
3386 prev_cache = zio_buf_cache[i];
3387 kmem_cache_reap_now(zio_buf_cache[i]);
3388 }
3389 if (zio_data_buf_cache[i] != prev_data_cache) {
3390 prev_data_cache = zio_data_buf_cache[i];
3391 kmem_cache_reap_now(zio_data_buf_cache[i]);
3392 }
3393 }
ca0bf58d 3394 kmem_cache_reap_now(buf_cache);
b9541d6b
CW
3395 kmem_cache_reap_now(hdr_full_cache);
3396 kmem_cache_reap_now(hdr_l2only_cache);
669dedb3 3397 kmem_cache_reap_now(range_seg_cache);
ca67b33a
MA
3398
3399 if (zio_arena != NULL) {
3400 /*
3401 * Ask the vmem arena to reclaim unused memory from its
3402 * quantum caches.
3403 */
3404 vmem_qcache_reap(zio_arena);
3405 }
34dc7c2f
BB
3406}
3407
302f753f 3408/*
ca0bf58d
PS
3409 * Threads can block in arc_get_data_buf() waiting for this thread to evict
3410 * enough data and signal them to proceed. When this happens, the threads in
3411 * arc_get_data_buf() are sleeping while holding the hash lock for their
3412 * particular arc header. Thus, we must be careful to never sleep on a
3413 * hash lock in this thread. This is to prevent the following deadlock:
3414 *
3415 * - Thread A sleeps on CV in arc_get_data_buf() holding hash lock "L",
3416 * waiting for the reclaim thread to signal it.
3417 *
3418 * - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
3419 * fails, and goes to sleep forever.
3420 *
3421 * This possible deadlock is avoided by always acquiring a hash lock
3422 * using mutex_tryenter() from arc_reclaim_thread().
302f753f 3423 */
34dc7c2f 3424static void
ca67b33a 3425arc_reclaim_thread(void)
34dc7c2f 3426{
ca67b33a 3427 fstrans_cookie_t cookie = spl_fstrans_mark();
ae6d0c60 3428 hrtime_t growtime = 0;
34dc7c2f
BB
3429 callb_cpr_t cpr;
3430
ca0bf58d 3431 CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
34dc7c2f 3432
ca0bf58d 3433 mutex_enter(&arc_reclaim_lock);
ca67b33a
MA
3434 while (!arc_reclaim_thread_exit) {
3435 int64_t to_free;
3436 int64_t free_memory = arc_available_memory();
3437 uint64_t evicted = 0;
302f753f 3438
ca67b33a 3439 arc_tuning_update();
34dc7c2f 3440
ca67b33a 3441 mutex_exit(&arc_reclaim_lock);
34dc7c2f 3442
ca67b33a 3443 if (free_memory < 0) {
34dc7c2f 3444
ca67b33a 3445 arc_no_grow = B_TRUE;
b128c09f 3446 arc_warm = B_TRUE;
34dc7c2f 3447
ca67b33a
MA
3448 /*
3449 * Wait at least zfs_grow_retry (default 5) seconds
3450 * before considering growing.
3451 */
ae6d0c60 3452 growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
6a8f9b6b 3453
ca67b33a 3454 arc_kmem_reap_now();
34dc7c2f 3455
ca67b33a
MA
3456 /*
3457 * If we are still low on memory, shrink the ARC
3458 * so that we have arc_shrink_min free space.
3459 */
3460 free_memory = arc_available_memory();
34dc7c2f 3461
ca67b33a
MA
3462 to_free = (arc_c >> arc_shrink_shift) - free_memory;
3463 if (to_free > 0) {
3464#ifdef _KERNEL
11f552fa 3465 to_free = MAX(to_free, arc_need_free);
ca67b33a
MA
3466#endif
3467 arc_shrink(to_free);
3468 }
3469 } else if (free_memory < arc_c >> arc_no_grow_shift) {
3470 arc_no_grow = B_TRUE;
ae6d0c60 3471 } else if (gethrtime() >= growtime) {
ca67b33a
MA
3472 arc_no_grow = B_FALSE;
3473 }
bce45ec9 3474
ca67b33a 3475 evicted = arc_adjust();
bce45ec9 3476
ca67b33a 3477 mutex_enter(&arc_reclaim_lock);
bce45ec9 3478
ca67b33a
MA
3479 /*
3480 * If evicted is zero, we couldn't evict anything via
3481 * arc_adjust(). This could be due to hash lock
3482 * collisions, but more likely due to the majority of
3483 * arc buffers being unevictable. Therefore, even if
3484 * arc_size is above arc_c, another pass is unlikely to
3485 * be helpful and could potentially cause us to enter an
3486 * infinite loop.
3487 */
3488 if (arc_size <= arc_c || evicted == 0) {
3489 /*
3490 * We're either no longer overflowing, or we
3491 * can't evict anything more, so we should wake
11f552fa
BB
3492 * up any threads before we go to sleep and clear
3493 * arc_need_free since nothing more can be done.
ca67b33a
MA
3494 */
3495 cv_broadcast(&arc_reclaim_waiters_cv);
11f552fa 3496 arc_need_free = 0;
bce45ec9 3497
ca67b33a
MA
3498 /*
3499 * Block until signaled, or after one second (we
3500 * might need to perform arc_kmem_reap_now()
3501 * even if we aren't being signalled)
3502 */
3503 CALLB_CPR_SAFE_BEGIN(&cpr);
a9bb2b68 3504 (void) cv_timedwait_sig_hires(&arc_reclaim_thread_cv,
ae6d0c60 3505 &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
ca67b33a
MA
3506 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
3507 }
ca0bf58d 3508 }
bce45ec9 3509
ca67b33a 3510 arc_reclaim_thread_exit = FALSE;
ca0bf58d
PS
3511 cv_broadcast(&arc_reclaim_thread_cv);
3512 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_lock */
3513 spl_fstrans_unmark(cookie);
3514 thread_exit();
3515}
3516
3517static void
3518arc_user_evicts_thread(void)
3519{
ca67b33a 3520 fstrans_cookie_t cookie = spl_fstrans_mark();
ca0bf58d 3521 callb_cpr_t cpr;
bce45ec9 3522
ca0bf58d 3523 CALLB_CPR_INIT(&cpr, &arc_user_evicts_lock, callb_generic_cpr, FTAG);
bce45ec9 3524
ca0bf58d
PS
3525 mutex_enter(&arc_user_evicts_lock);
3526 while (!arc_user_evicts_thread_exit) {
3527 mutex_exit(&arc_user_evicts_lock);
3528
3529 arc_do_user_evicts();
3530
3531 /*
3532 * This is necessary in order for the mdb ::arc dcmd to
3533 * show up to date information. Since the ::arc command
3534 * does not call the kstat's update function, without
3535 * this call, the command may show stale stats for the
3536 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3537 * with this change, the data might be up to 1 second
3538 * out of date; but that should suffice. The arc_state_t
3539 * structures can be queried directly if more accurate
3540 * information is needed.
3541 */
3542 if (arc_ksp != NULL)
3543 arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3544
3545 mutex_enter(&arc_user_evicts_lock);
3546
3547 /*
3548 * Block until signaled, or after one second (we need to
3549 * call the arc's kstat update function regularly).
3550 */
3551 CALLB_CPR_SAFE_BEGIN(&cpr);
b64ccd6c 3552 (void) cv_timedwait_sig(&arc_user_evicts_cv,
ca0bf58d
PS
3553 &arc_user_evicts_lock, ddi_get_lbolt() + hz);
3554 CALLB_CPR_SAFE_END(&cpr, &arc_user_evicts_lock);
34dc7c2f
BB
3555 }
3556
ca0bf58d
PS
3557 arc_user_evicts_thread_exit = FALSE;
3558 cv_broadcast(&arc_user_evicts_cv);
3559 CALLB_CPR_EXIT(&cpr); /* drops arc_user_evicts_lock */
40d06e3c 3560 spl_fstrans_unmark(cookie);
34dc7c2f
BB
3561 thread_exit();
3562}
3563
7cb67b45
BB
3564#ifdef _KERNEL
3565/*
302f753f
BB
3566 * Determine the amount of memory eligible for eviction contained in the
3567 * ARC. All clean data reported by the ghost lists can always be safely
3568 * evicted. Due to arc_c_min, the same does not hold for all clean data
3569 * contained by the regular mru and mfu lists.
3570 *
3571 * In the case of the regular mru and mfu lists, we need to report as
3572 * much clean data as possible, such that evicting that same reported
3573 * data will not bring arc_size below arc_c_min. Thus, in certain
3574 * circumstances, the total amount of clean data in the mru and mfu
3575 * lists might not actually be evictable.
3576 *
3577 * The following two distinct cases are accounted for:
3578 *
3579 * 1. The sum of the amount of dirty data contained by both the mru and
3580 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
3581 * is greater than or equal to arc_c_min.
3582 * (i.e. amount of dirty data >= arc_c_min)
3583 *
3584 * This is the easy case; all clean data contained by the mru and mfu
3585 * lists is evictable. Evicting all clean data can only drop arc_size
3586 * to the amount of dirty data, which is greater than arc_c_min.
3587 *
3588 * 2. The sum of the amount of dirty data contained by both the mru and
3589 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
3590 * is less than arc_c_min.
3591 * (i.e. arc_c_min > amount of dirty data)
3592 *
3593 * 2.1. arc_size is greater than or equal arc_c_min.
3594 * (i.e. arc_size >= arc_c_min > amount of dirty data)
3595 *
3596 * In this case, not all clean data from the regular mru and mfu
3597 * lists is actually evictable; we must leave enough clean data
3598 * to keep arc_size above arc_c_min. Thus, the maximum amount of
3599 * evictable data from the two lists combined, is exactly the
3600 * difference between arc_size and arc_c_min.
3601 *
3602 * 2.2. arc_size is less than arc_c_min
3603 * (i.e. arc_c_min > arc_size > amount of dirty data)
3604 *
3605 * In this case, none of the data contained in the mru and mfu
3606 * lists is evictable, even if it's clean. Since arc_size is
3607 * already below arc_c_min, evicting any more would only
3608 * increase this negative difference.
7cb67b45 3609 */
302f753f
BB
3610static uint64_t
3611arc_evictable_memory(void) {
3612 uint64_t arc_clean =
3613 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
3614 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
3615 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
3616 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
3617 uint64_t ghost_clean =
3618 arc_mru_ghost->arcs_lsize[ARC_BUFC_DATA] +
3619 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
3620 arc_mfu_ghost->arcs_lsize[ARC_BUFC_DATA] +
3621 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA];
3622 uint64_t arc_dirty = MAX((int64_t)arc_size - (int64_t)arc_clean, 0);
3623
3624 if (arc_dirty >= arc_c_min)
3625 return (ghost_clean + arc_clean);
3626
3627 return (ghost_clean + MAX((int64_t)arc_size - (int64_t)arc_c_min, 0));
3628}
3629
ed6e9cc2
TC
3630/*
3631 * If sc->nr_to_scan is zero, the caller is requesting a query of the
3632 * number of objects which can potentially be freed. If it is nonzero,
3633 * the request is to free that many objects.
3634 *
3635 * Linux kernels >= 3.12 have the count_objects and scan_objects callbacks
3636 * in struct shrinker and also require the shrinker to return the number
3637 * of objects freed.
3638 *
3639 * Older kernels require the shrinker to return the number of freeable
3640 * objects following the freeing of nr_to_free.
3641 */
3642static spl_shrinker_t
7e7baeca 3643__arc_shrinker_func(struct shrinker *shrink, struct shrink_control *sc)
7cb67b45 3644{
ed6e9cc2 3645 int64_t pages;
7cb67b45 3646
302f753f
BB
3647 /* The arc is considered warm once reclaim has occurred */
3648 if (unlikely(arc_warm == B_FALSE))
3649 arc_warm = B_TRUE;
7cb67b45 3650
302f753f 3651 /* Return the potential number of reclaimable pages */
ed6e9cc2 3652 pages = btop((int64_t)arc_evictable_memory());
302f753f
BB
3653 if (sc->nr_to_scan == 0)
3654 return (pages);
3fd70ee6
BB
3655
3656 /* Not allowed to perform filesystem reclaim */
7e7baeca 3657 if (!(sc->gfp_mask & __GFP_FS))
ed6e9cc2 3658 return (SHRINK_STOP);
3fd70ee6 3659
7cb67b45 3660 /* Reclaim in progress */
ca0bf58d 3661 if (mutex_tryenter(&arc_reclaim_lock) == 0)
ed6e9cc2 3662 return (SHRINK_STOP);
7cb67b45 3663
ca0bf58d
PS
3664 mutex_exit(&arc_reclaim_lock);
3665
302f753f
BB
3666 /*
3667 * Evict the requested number of pages by shrinking arc_c the
3668 * requested amount. If there is nothing left to evict just
3669 * reap whatever we can from the various arc slabs.
3670 */
3671 if (pages > 0) {
ca67b33a
MA
3672 arc_shrink(ptob(sc->nr_to_scan));
3673 arc_kmem_reap_now();
ed6e9cc2
TC
3674#ifdef HAVE_SPLIT_SHRINKER_CALLBACK
3675 pages = MAX(pages - btop(arc_evictable_memory()), 0);
3676#else
1e3cb67b 3677 pages = btop(arc_evictable_memory());
ed6e9cc2 3678#endif
302f753f 3679 } else {
ca67b33a 3680 arc_kmem_reap_now();
ed6e9cc2 3681 pages = SHRINK_STOP;
302f753f
BB
3682 }
3683
ca0bf58d
PS
3684 /*
3685 * We've reaped what we can, wake up threads.
3686 */
3687 cv_broadcast(&arc_reclaim_waiters_cv);
3688
302f753f
BB
3689 /*
3690 * When direct reclaim is observed it usually indicates a rapid
3691 * increase in memory pressure. This occurs because the kswapd
3692 * threads were unable to asynchronously keep enough free memory
3693 * available. In this case set arc_no_grow to briefly pause arc
3694 * growth to avoid compounding the memory pressure.
3695 */
7cb67b45 3696 if (current_is_kswapd()) {
302f753f 3697 ARCSTAT_BUMP(arcstat_memory_indirect_count);
7cb67b45 3698 } else {
302f753f 3699 arc_no_grow = B_TRUE;
11f552fa 3700 arc_need_free = ptob(sc->nr_to_scan);
302f753f 3701 ARCSTAT_BUMP(arcstat_memory_direct_count);
7cb67b45
BB
3702 }
3703
1e3cb67b 3704 return (pages);
7cb67b45 3705}
7e7baeca 3706SPL_SHRINKER_CALLBACK_WRAPPER(arc_shrinker_func);
7cb67b45
BB
3707
3708SPL_SHRINKER_DECLARE(arc_shrinker, arc_shrinker_func, DEFAULT_SEEKS);
3709#endif /* _KERNEL */
3710
34dc7c2f
BB
3711/*
3712 * Adapt arc info given the number of bytes we are trying to add and
3713 * the state that we are comming from. This function is only called
3714 * when we are adding new content to the cache.
3715 */
3716static void
3717arc_adapt(int bytes, arc_state_t *state)
3718{
3719 int mult;
728d6ae9 3720 uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
36da08ef
PS
3721 int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
3722 int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
34dc7c2f
BB
3723
3724 if (state == arc_l2c_only)
3725 return;
3726
3727 ASSERT(bytes > 0);
3728 /*
3729 * Adapt the target size of the MRU list:
3730 * - if we just hit in the MRU ghost list, then increase
3731 * the target size of the MRU list.
3732 * - if we just hit in the MFU ghost list, then increase
3733 * the target size of the MFU list by decreasing the
3734 * target size of the MRU list.
3735 */
3736 if (state == arc_mru_ghost) {
36da08ef 3737 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
62422785
PS
3738 if (!zfs_arc_p_dampener_disable)
3739 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
34dc7c2f 3740
728d6ae9 3741 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
34dc7c2f 3742 } else if (state == arc_mfu_ghost) {
d164b209
BB
3743 uint64_t delta;
3744
36da08ef 3745 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
62422785
PS
3746 if (!zfs_arc_p_dampener_disable)
3747 mult = MIN(mult, 10);
34dc7c2f 3748
d164b209 3749 delta = MIN(bytes * mult, arc_p);
728d6ae9 3750 arc_p = MAX(arc_p_min, arc_p - delta);
34dc7c2f
BB
3751 }
3752 ASSERT((int64_t)arc_p >= 0);
3753
ca67b33a
MA
3754 if (arc_reclaim_needed()) {
3755 cv_signal(&arc_reclaim_thread_cv);
3756 return;
3757 }
3758
34dc7c2f
BB
3759 if (arc_no_grow)
3760 return;
3761
3762 if (arc_c >= arc_c_max)
3763 return;
3764
3765 /*
3766 * If we're within (2 * maxblocksize) bytes of the target
3767 * cache size, increment the target cache size
3768 */
935434ef 3769 ASSERT3U(arc_c, >=, 2ULL << SPA_MAXBLOCKSHIFT);
121b3cae 3770 if (arc_size >= arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
34dc7c2f
BB
3771 atomic_add_64(&arc_c, (int64_t)bytes);
3772 if (arc_c > arc_c_max)
3773 arc_c = arc_c_max;
3774 else if (state == arc_anon)
3775 atomic_add_64(&arc_p, (int64_t)bytes);
3776 if (arc_p > arc_c)
3777 arc_p = arc_c;
3778 }
3779 ASSERT((int64_t)arc_p >= 0);
3780}
3781
3782/*
ca0bf58d
PS
3783 * Check if arc_size has grown past our upper threshold, determined by
3784 * zfs_arc_overflow_shift.
34dc7c2f 3785 */
ca0bf58d
PS
3786static boolean_t
3787arc_is_overflowing(void)
34dc7c2f 3788{
ca0bf58d
PS
3789 /* Always allow at least one block of overflow */
3790 uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
3791 arc_c >> zfs_arc_overflow_shift);
34dc7c2f 3792
ca0bf58d 3793 return (arc_size >= arc_c + overflow);
34dc7c2f
BB
3794}
3795
3796/*
ca0bf58d
PS
3797 * The buffer, supplied as the first argument, needs a data block. If we
3798 * are hitting the hard limit for the cache size, we must sleep, waiting
3799 * for the eviction thread to catch up. If we're past the target size
3800 * but below the hard limit, we'll only signal the reclaim thread and
3801 * continue on.
34dc7c2f
BB
3802 */
3803static void
3804arc_get_data_buf(arc_buf_t *buf)
3805{
b9541d6b 3806 arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
34dc7c2f 3807 uint64_t size = buf->b_hdr->b_size;
b9541d6b 3808 arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
34dc7c2f
BB
3809
3810 arc_adapt(size, state);
3811
3812 /*
ca0bf58d
PS
3813 * If arc_size is currently overflowing, and has grown past our
3814 * upper limit, we must be adding data faster than the evict
3815 * thread can evict. Thus, to ensure we don't compound the
3816 * problem by adding more data and forcing arc_size to grow even
3817 * further past it's target size, we halt and wait for the
3818 * eviction thread to catch up.
3819 *
3820 * It's also possible that the reclaim thread is unable to evict
3821 * enough buffers to get arc_size below the overflow limit (e.g.
3822 * due to buffers being un-evictable, or hash lock collisions).
3823 * In this case, we want to proceed regardless if we're
3824 * overflowing; thus we don't use a while loop here.
34dc7c2f 3825 */
ca0bf58d
PS
3826 if (arc_is_overflowing()) {
3827 mutex_enter(&arc_reclaim_lock);
3828
3829 /*
3830 * Now that we've acquired the lock, we may no longer be
3831 * over the overflow limit, lets check.
3832 *
3833 * We're ignoring the case of spurious wake ups. If that
3834 * were to happen, it'd let this thread consume an ARC
3835 * buffer before it should have (i.e. before we're under
3836 * the overflow limit and were signalled by the reclaim
3837 * thread). As long as that is a rare occurrence, it
3838 * shouldn't cause any harm.
3839 */
3840 if (arc_is_overflowing()) {
3841 cv_signal(&arc_reclaim_thread_cv);
3842 cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
34dc7c2f 3843 }
34dc7c2f 3844
ca0bf58d 3845 mutex_exit(&arc_reclaim_lock);
34dc7c2f 3846 }
ab26409d 3847
da8ccd0e 3848 if (type == ARC_BUFC_METADATA) {
ca0bf58d
PS
3849 buf->b_data = zio_buf_alloc(size);
3850 arc_space_consume(size, ARC_SPACE_META);
3851 } else {
3852 ASSERT(type == ARC_BUFC_DATA);
3853 buf->b_data = zio_data_buf_alloc(size);
3854 arc_space_consume(size, ARC_SPACE_DATA);
da8ccd0e
PS
3855 }
3856
34dc7c2f
BB
3857 /*
3858 * Update the state size. Note that ghost states have a
3859 * "ghost size" and so don't need to be updated.
3860 */
b9541d6b 3861 if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
34dc7c2f 3862 arc_buf_hdr_t *hdr = buf->b_hdr;
36da08ef 3863 arc_state_t *state = hdr->b_l1hdr.b_state;
34dc7c2f 3864
36da08ef 3865 (void) refcount_add_many(&state->arcs_size, size, buf);
ca0bf58d
PS
3866
3867 /*
3868 * If this is reached via arc_read, the link is
3869 * protected by the hash lock. If reached via
3870 * arc_buf_alloc, the header should not be accessed by
3871 * any other thread. And, if reached via arc_read_done,
3872 * the hash lock will protect it if it's found in the
3873 * hash table; otherwise no other thread should be
3874 * trying to [add|remove]_reference it.
3875 */
3876 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
b9541d6b
CW
3877 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3878 atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3879 size);
34dc7c2f
BB
3880 }
3881 /*
3882 * If we are growing the cache, and we are adding anonymous
3883 * data, and we have outgrown arc_p, update arc_p
3884 */
ca0bf58d 3885 if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
36da08ef
PS
3886 (refcount_count(&arc_anon->arcs_size) +
3887 refcount_count(&arc_mru->arcs_size) > arc_p))
34dc7c2f
BB
3888 arc_p = MIN(arc_c, arc_p + size);
3889 }
3890}
3891
3892/*
3893 * This routine is called whenever a buffer is accessed.
3894 * NOTE: the hash lock is dropped in this function.
3895 */
3896static void
2a432414 3897arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
34dc7c2f 3898{
428870ff
BB
3899 clock_t now;
3900
34dc7c2f 3901 ASSERT(MUTEX_HELD(hash_lock));
b9541d6b 3902 ASSERT(HDR_HAS_L1HDR(hdr));
34dc7c2f 3903
b9541d6b 3904 if (hdr->b_l1hdr.b_state == arc_anon) {
34dc7c2f
BB
3905 /*
3906 * This buffer is not in the cache, and does not
3907 * appear in our "ghost" list. Add the new buffer
3908 * to the MRU state.
3909 */
3910
b9541d6b
CW
3911 ASSERT0(hdr->b_l1hdr.b_arc_access);
3912 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
2a432414
GW
3913 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3914 arc_change_state(arc_mru, hdr, hash_lock);
34dc7c2f 3915
b9541d6b 3916 } else if (hdr->b_l1hdr.b_state == arc_mru) {
428870ff
BB
3917 now = ddi_get_lbolt();
3918
34dc7c2f
BB
3919 /*
3920 * If this buffer is here because of a prefetch, then either:
3921 * - clear the flag if this is a "referencing" read
3922 * (any subsequent access will bump this into the MFU state).
3923 * or
3924 * - move the buffer to the head of the list if this is
3925 * another prefetch (to make it less likely to be evicted).
3926 */
b9541d6b
CW
3927 if (HDR_PREFETCH(hdr)) {
3928 if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
ca0bf58d
PS
3929 /* link protected by hash lock */
3930 ASSERT(multilist_link_active(
b9541d6b 3931 &hdr->b_l1hdr.b_arc_node));
34dc7c2f 3932 } else {
2a432414 3933 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
b9541d6b 3934 atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
34dc7c2f
BB
3935 ARCSTAT_BUMP(arcstat_mru_hits);
3936 }
b9541d6b 3937 hdr->b_l1hdr.b_arc_access = now;
34dc7c2f
BB
3938 return;
3939 }
3940
3941 /*
3942 * This buffer has been "accessed" only once so far,
3943 * but it is still in the cache. Move it to the MFU
3944 * state.
3945 */
b9541d6b
CW
3946 if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
3947 ARC_MINTIME)) {
34dc7c2f
BB
3948 /*
3949 * More than 125ms have passed since we
3950 * instantiated this buffer. Move it to the
3951 * most frequently used state.
3952 */
b9541d6b 3953 hdr->b_l1hdr.b_arc_access = now;
2a432414
GW
3954 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3955 arc_change_state(arc_mfu, hdr, hash_lock);
34dc7c2f 3956 }
b9541d6b 3957 atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
34dc7c2f 3958 ARCSTAT_BUMP(arcstat_mru_hits);
b9541d6b 3959 } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
34dc7c2f
BB
3960 arc_state_t *new_state;
3961 /*
3962 * This buffer has been "accessed" recently, but
3963 * was evicted from the cache. Move it to the
3964 * MFU state.
3965 */
3966
b9541d6b 3967 if (HDR_PREFETCH(hdr)) {
34dc7c2f 3968 new_state = arc_mru;
b9541d6b 3969 if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
2a432414
GW
3970 hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3971 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
34dc7c2f
BB
3972 } else {
3973 new_state = arc_mfu;
2a432414 3974 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
34dc7c2f
BB
3975 }
3976
b9541d6b 3977 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
2a432414 3978 arc_change_state(new_state, hdr, hash_lock);
34dc7c2f 3979
b9541d6b 3980 atomic_inc_32(&hdr->b_l1hdr.b_mru_ghost_hits);
34dc7c2f 3981 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
b9541d6b 3982 } else if (hdr->b_l1hdr.b_state == arc_mfu) {
34dc7c2f
BB
3983 /*
3984 * This buffer has been accessed more than once and is
3985 * still in the cache. Keep it in the MFU state.
3986 *
3987 * NOTE: an add_reference() that occurred when we did
3988 * the arc_read() will have kicked this off the list.
3989 * If it was a prefetch, we will explicitly move it to
3990 * the head of the list now.
3991 */
b9541d6b
CW
3992 if ((HDR_PREFETCH(hdr)) != 0) {
3993 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
ca0bf58d
PS
3994 /* link protected by hash_lock */
3995 ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
34dc7c2f 3996 }
b9541d6b 3997 atomic_inc_32(&hdr->b_l1hdr.b_mfu_hits);
34dc7c2f 3998 ARCSTAT_BUMP(arcstat_mfu_hits);
b9541d6b
CW
3999 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4000 } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
34dc7c2f
BB
4001 arc_state_t *new_state = arc_mfu;
4002 /*
4003 * This buffer has been accessed more than once but has
4004 * been evicted from the cache. Move it back to the
4005 * MFU state.
4006 */
4007
b9541d6b 4008 if (HDR_PREFETCH(hdr)) {
34dc7c2f
BB
4009 /*
4010 * This is a prefetch access...
4011 * move this block back to the MRU state.
4012 */
b9541d6b 4013 ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
34dc7c2f
BB
4014 new_state = arc_mru;
4015 }
4016
b9541d6b 4017 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
2a432414
GW
4018 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4019 arc_change_state(new_state, hdr, hash_lock);
34dc7c2f 4020
b9541d6b 4021 atomic_inc_32(&hdr->b_l1hdr.b_mfu_ghost_hits);
34dc7c2f 4022 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
b9541d6b 4023 } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
34dc7c2f
BB
4024 /*
4025 * This buffer is on the 2nd Level ARC.
4026 */
4027
b9541d6b 4028 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
2a432414
GW
4029 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4030 arc_change_state(arc_mfu, hdr, hash_lock);
34dc7c2f 4031 } else {
b9541d6b
CW
4032 cmn_err(CE_PANIC, "invalid arc state 0x%p",
4033 hdr->b_l1hdr.b_state);
34dc7c2f
BB
4034 }
4035}
4036
4037/* a generic arc_done_func_t which you can use */
4038/* ARGSUSED */
4039void
4040arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4041{
428870ff
BB
4042 if (zio == NULL || zio->io_error == 0)
4043 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
13fe0198 4044 VERIFY(arc_buf_remove_ref(buf, arg));
34dc7c2f
BB
4045}
4046
4047/* a generic arc_done_func_t */
4048void
4049arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4050{
4051 arc_buf_t **bufp = arg;
4052 if (zio && zio->io_error) {
13fe0198 4053 VERIFY(arc_buf_remove_ref(buf, arg));
34dc7c2f
BB
4054 *bufp = NULL;
4055 } else {
4056 *bufp = buf;
428870ff 4057 ASSERT(buf->b_data);
34dc7c2f
BB
4058 }
4059}
4060
4061static void
4062arc_read_done(zio_t *zio)
4063{
9b67f605 4064 arc_buf_hdr_t *hdr;
34dc7c2f
BB
4065 arc_buf_t *buf;
4066 arc_buf_t *abuf; /* buffer we're assigning to callback */
9b67f605 4067 kmutex_t *hash_lock = NULL;
34dc7c2f
BB
4068 arc_callback_t *callback_list, *acb;
4069 int freeable = FALSE;
4070
4071 buf = zio->io_private;
4072 hdr = buf->b_hdr;
4073
4074 /*
4075 * The hdr was inserted into hash-table and removed from lists
4076 * prior to starting I/O. We should find this header, since
4077 * it's in the hash table, and it should be legit since it's
4078 * not possible to evict it during the I/O. The only possible
4079 * reason for it not to be found is if we were freed during the
4080 * read.
4081 */
9b67f605
MA
4082 if (HDR_IN_HASH_TABLE(hdr)) {
4083 arc_buf_hdr_t *found;
4084
4085 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4086 ASSERT3U(hdr->b_dva.dva_word[0], ==,
4087 BP_IDENTITY(zio->io_bp)->dva_word[0]);
4088 ASSERT3U(hdr->b_dva.dva_word[1], ==,
4089 BP_IDENTITY(zio->io_bp)->dva_word[1]);
4090
4091 found = buf_hash_find(hdr->b_spa, zio->io_bp,
4092 &hash_lock);
4093
4094 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
4095 hash_lock == NULL) ||
4096 (found == hdr &&
4097 DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4098 (found == hdr && HDR_L2_READING(hdr)));
4099 }
34dc7c2f 4100
2a432414 4101 hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
b9541d6b 4102 if (l2arc_noprefetch && HDR_PREFETCH(hdr))
2a432414 4103 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
34dc7c2f
BB
4104
4105 /* byteswap if necessary */
b9541d6b 4106 callback_list = hdr->b_l1hdr.b_acb;
34dc7c2f 4107 ASSERT(callback_list != NULL);
428870ff 4108 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
9ae529ec
CS
4109 dmu_object_byteswap_t bswap =
4110 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
b01615d5
RY
4111 if (BP_GET_LEVEL(zio->io_bp) > 0)
4112 byteswap_uint64_array(buf->b_data, hdr->b_size);
4113 else
4114 dmu_ot_byteswap[bswap].ob_func(buf->b_data, hdr->b_size);
b128c09f 4115 }
34dc7c2f
BB
4116
4117 arc_cksum_compute(buf, B_FALSE);
498877ba 4118 arc_buf_watch(buf);
34dc7c2f 4119
b9541d6b
CW
4120 if (hash_lock && zio->io_error == 0 &&
4121 hdr->b_l1hdr.b_state == arc_anon) {
428870ff
BB
4122 /*
4123 * Only call arc_access on anonymous buffers. This is because
4124 * if we've issued an I/O for an evicted buffer, we've already
4125 * called arc_access (to prevent any simultaneous readers from
4126 * getting confused).
4127 */
4128 arc_access(hdr, hash_lock);
4129 }
4130
34dc7c2f
BB
4131 /* create copies of the data buffer for the callers */
4132 abuf = buf;
4133 for (acb = callback_list; acb; acb = acb->acb_next) {
4134 if (acb->acb_done) {
1eb5bfa3
GW
4135 if (abuf == NULL) {
4136 ARCSTAT_BUMP(arcstat_duplicate_reads);
34dc7c2f 4137 abuf = arc_buf_clone(buf);
1eb5bfa3 4138 }
34dc7c2f
BB
4139 acb->acb_buf = abuf;
4140 abuf = NULL;
4141 }
4142 }
b9541d6b 4143 hdr->b_l1hdr.b_acb = NULL;
2a432414 4144 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
34dc7c2f 4145 ASSERT(!HDR_BUF_AVAILABLE(hdr));
428870ff
BB
4146 if (abuf == buf) {
4147 ASSERT(buf->b_efunc == NULL);
b9541d6b 4148 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2a432414 4149 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
428870ff 4150 }
34dc7c2f 4151
b9541d6b
CW
4152 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4153 callback_list != NULL);
34dc7c2f
BB
4154
4155 if (zio->io_error != 0) {
2a432414 4156 hdr->b_flags |= ARC_FLAG_IO_ERROR;
b9541d6b 4157 if (hdr->b_l1hdr.b_state != arc_anon)
34dc7c2f
BB
4158 arc_change_state(arc_anon, hdr, hash_lock);
4159 if (HDR_IN_HASH_TABLE(hdr))
4160 buf_hash_remove(hdr);
b9541d6b 4161 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
34dc7c2f
BB
4162 }
4163
4164 /*
4165 * Broadcast before we drop the hash_lock to avoid the possibility
4166 * that the hdr (and hence the cv) might be freed before we get to
4167 * the cv_broadcast().
4168 */
b9541d6b 4169 cv_broadcast(&hdr->b_l1hdr.b_cv);
34dc7c2f 4170
b9541d6b 4171 if (hash_lock != NULL) {
34dc7c2f
BB
4172 mutex_exit(hash_lock);
4173 } else {
4174 /*
4175 * This block was freed while we waited for the read to
4176 * complete. It has been removed from the hash table and
4177 * moved to the anonymous state (so that it won't show up
4178 * in the cache).
4179 */
b9541d6b
CW
4180 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4181 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
34dc7c2f
BB
4182 }
4183
4184 /* execute each callback and free its structure */
4185 while ((acb = callback_list) != NULL) {
4186 if (acb->acb_done)
4187 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4188
4189 if (acb->acb_zio_dummy != NULL) {
4190 acb->acb_zio_dummy->io_error = zio->io_error;
4191 zio_nowait(acb->acb_zio_dummy);
4192 }
4193
4194 callback_list = acb->acb_next;
4195 kmem_free(acb, sizeof (arc_callback_t));
4196 }
4197
4198 if (freeable)
4199 arc_hdr_destroy(hdr);
4200}
4201
4202/*
5c839890 4203 * "Read" the block at the specified DVA (in bp) via the
34dc7c2f
BB
4204 * cache. If the block is found in the cache, invoke the provided
4205 * callback immediately and return. Note that the `zio' parameter
4206 * in the callback will be NULL in this case, since no IO was
4207 * required. If the block is not in the cache pass the read request
4208 * on to the spa with a substitute callback function, so that the
4209 * requested block will be added to the cache.
4210 *
4211 * If a read request arrives for a block that has a read in-progress,
4212 * either wait for the in-progress read to complete (and return the
4213 * results); or, if this is a read with a "done" func, add a record
4214 * to the read to invoke the "done" func when the read completes,
4215 * and return; or just return.
4216 *
4217 * arc_read_done() will invoke all the requested "done" functions
4218 * for readers of this block.
4219 */
4220int
294f6806 4221arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
2a432414
GW
4222 void *private, zio_priority_t priority, int zio_flags,
4223 arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
34dc7c2f 4224{
9b67f605 4225 arc_buf_hdr_t *hdr = NULL;
d4ed6673 4226 arc_buf_t *buf = NULL;
9b67f605 4227 kmutex_t *hash_lock = NULL;
34dc7c2f 4228 zio_t *rzio;
3541dc6d 4229 uint64_t guid = spa_load_guid(spa);
1421c891 4230 int rc = 0;
34dc7c2f 4231
9b67f605
MA
4232 ASSERT(!BP_IS_EMBEDDED(bp) ||
4233 BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4234
34dc7c2f 4235top:
9b67f605
MA
4236 if (!BP_IS_EMBEDDED(bp)) {
4237 /*
4238 * Embedded BP's have no DVA and require no I/O to "read".
4239 * Create an anonymous arc buf to back it.
4240 */
4241 hdr = buf_hash_find(guid, bp, &hash_lock);
4242 }
4243
b9541d6b 4244 if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
34dc7c2f 4245
2a432414 4246 *arc_flags |= ARC_FLAG_CACHED;
34dc7c2f
BB
4247
4248 if (HDR_IO_IN_PROGRESS(hdr)) {
4249
7f60329a
MA
4250 if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4251 priority == ZIO_PRIORITY_SYNC_READ) {
4252 /*
4253 * This sync read must wait for an
4254 * in-progress async read (e.g. a predictive
4255 * prefetch). Async reads are queued
4256 * separately at the vdev_queue layer, so
4257 * this is a form of priority inversion.
4258 * Ideally, we would "inherit" the demand
4259 * i/o's priority by moving the i/o from
4260 * the async queue to the synchronous queue,
4261 * but there is currently no mechanism to do
4262 * so. Track this so that we can evaluate
4263 * the magnitude of this potential performance
4264 * problem.
4265 *
4266 * Note that if the prefetch i/o is already
4267 * active (has been issued to the device),
4268 * the prefetch improved performance, because
4269 * we issued it sooner than we would have
4270 * without the prefetch.
4271 */
4272 DTRACE_PROBE1(arc__sync__wait__for__async,
4273 arc_buf_hdr_t *, hdr);
4274 ARCSTAT_BUMP(arcstat_sync_wait_for_async);
4275 }
4276 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4277 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4278 }
4279
2a432414 4280 if (*arc_flags & ARC_FLAG_WAIT) {
b9541d6b 4281 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
34dc7c2f
BB
4282 mutex_exit(hash_lock);
4283 goto top;
4284 }
2a432414 4285 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
34dc7c2f
BB
4286
4287 if (done) {
7f60329a 4288 arc_callback_t *acb = NULL;
34dc7c2f
BB
4289
4290 acb = kmem_zalloc(sizeof (arc_callback_t),
79c76d5b 4291 KM_SLEEP);
34dc7c2f
BB
4292 acb->acb_done = done;
4293 acb->acb_private = private;
34dc7c2f
BB
4294 if (pio != NULL)
4295 acb->acb_zio_dummy = zio_null(pio,
d164b209 4296 spa, NULL, NULL, NULL, zio_flags);
34dc7c2f
BB
4297
4298 ASSERT(acb->acb_done != NULL);
b9541d6b
CW
4299 acb->acb_next = hdr->b_l1hdr.b_acb;
4300 hdr->b_l1hdr.b_acb = acb;
34dc7c2f
BB
4301 add_reference(hdr, hash_lock, private);
4302 mutex_exit(hash_lock);
1421c891 4303 goto out;
34dc7c2f
BB
4304 }
4305 mutex_exit(hash_lock);
1421c891 4306 goto out;
34dc7c2f
BB
4307 }
4308
b9541d6b
CW
4309 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4310 hdr->b_l1hdr.b_state == arc_mfu);
34dc7c2f
BB
4311
4312 if (done) {
7f60329a
MA
4313 if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
4314 /*
4315 * This is a demand read which does not have to
4316 * wait for i/o because we did a predictive
4317 * prefetch i/o for it, which has completed.
4318 */
4319 DTRACE_PROBE1(
4320 arc__demand__hit__predictive__prefetch,
4321 arc_buf_hdr_t *, hdr);
4322 ARCSTAT_BUMP(
4323 arcstat_demand_hit_predictive_prefetch);
4324 hdr->b_flags &= ~ARC_FLAG_PREDICTIVE_PREFETCH;
4325 }
34dc7c2f
BB
4326 add_reference(hdr, hash_lock, private);
4327 /*
4328 * If this block is already in use, create a new
4329 * copy of the data so that we will be guaranteed
4330 * that arc_release() will always succeed.
4331 */
b9541d6b 4332 buf = hdr->b_l1hdr.b_buf;
34dc7c2f
BB
4333 ASSERT(buf);
4334 ASSERT(buf->b_data);
4335 if (HDR_BUF_AVAILABLE(hdr)) {
4336 ASSERT(buf->b_efunc == NULL);
2a432414 4337 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
34dc7c2f
BB
4338 } else {
4339 buf = arc_buf_clone(buf);
4340 }
428870ff 4341
2a432414 4342 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
b9541d6b 4343 refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
2a432414 4344 hdr->b_flags |= ARC_FLAG_PREFETCH;
34dc7c2f
BB
4345 }
4346 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4347 arc_access(hdr, hash_lock);
2a432414
GW
4348 if (*arc_flags & ARC_FLAG_L2CACHE)
4349 hdr->b_flags |= ARC_FLAG_L2CACHE;
4350 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4351 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
34dc7c2f
BB
4352 mutex_exit(hash_lock);
4353 ARCSTAT_BUMP(arcstat_hits);
b9541d6b
CW
4354 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4355 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
34dc7c2f
BB
4356 data, metadata, hits);
4357
4358 if (done)
4359 done(NULL, buf, private);
4360 } else {
4361 uint64_t size = BP_GET_LSIZE(bp);
9b67f605 4362 arc_callback_t *acb;
b128c09f 4363 vdev_t *vd = NULL;
a117a6d6 4364 uint64_t addr = 0;
d164b209 4365 boolean_t devw = B_FALSE;
0ed212dc 4366 enum zio_compress b_compress = ZIO_COMPRESS_OFF;
b9541d6b 4367 int32_t b_asize = 0;
34dc7c2f 4368
5f6d0b6f
BB
4369 /*
4370 * Gracefully handle a damaged logical block size as a
1cdb86cb 4371 * checksum error.
5f6d0b6f 4372 */
f1512ee6 4373 if (size > spa_maxblocksize(spa)) {
1cdb86cb
BB
4374 ASSERT3P(buf, ==, NULL);
4375 rc = SET_ERROR(ECKSUM);
5f6d0b6f
BB
4376 goto out;
4377 }
4378
34dc7c2f
BB
4379 if (hdr == NULL) {
4380 /* this block is not in the cache */
9b67f605 4381 arc_buf_hdr_t *exists = NULL;
34dc7c2f
BB
4382 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4383 buf = arc_buf_alloc(spa, size, private, type);
4384 hdr = buf->b_hdr;
9b67f605
MA
4385 if (!BP_IS_EMBEDDED(bp)) {
4386 hdr->b_dva = *BP_IDENTITY(bp);
4387 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
9b67f605
MA
4388 exists = buf_hash_insert(hdr, &hash_lock);
4389 }
4390 if (exists != NULL) {
34dc7c2f
BB
4391 /* somebody beat us to the hash insert */
4392 mutex_exit(hash_lock);
428870ff 4393 buf_discard_identity(hdr);
34dc7c2f
BB
4394 (void) arc_buf_remove_ref(buf, private);
4395 goto top; /* restart the IO request */
4396 }
2a432414 4397
7f60329a
MA
4398 /*
4399 * If there is a callback, we pass our reference to
4400 * it; otherwise we remove our reference.
4401 */
4402 if (done == NULL) {
34dc7c2f
BB
4403 (void) remove_reference(hdr, hash_lock,
4404 private);
34dc7c2f 4405 }
7f60329a
MA
4406 if (*arc_flags & ARC_FLAG_PREFETCH)
4407 hdr->b_flags |= ARC_FLAG_PREFETCH;
2a432414
GW
4408 if (*arc_flags & ARC_FLAG_L2CACHE)
4409 hdr->b_flags |= ARC_FLAG_L2CACHE;
4410 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4411 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
34dc7c2f 4412 if (BP_GET_LEVEL(bp) > 0)
2a432414 4413 hdr->b_flags |= ARC_FLAG_INDIRECT;
34dc7c2f 4414 } else {
b9541d6b
CW
4415 /*
4416 * This block is in the ghost cache. If it was L2-only
4417 * (and thus didn't have an L1 hdr), we realloc the
4418 * header to add an L1 hdr.
4419 */
4420 if (!HDR_HAS_L1HDR(hdr)) {
4421 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4422 hdr_full_cache);
4423 }
4424
4425 ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
34dc7c2f 4426 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
b9541d6b 4427 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
ca0bf58d 4428 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
34dc7c2f 4429
7f60329a
MA
4430 /*
4431 * If there is a callback, we pass a reference to it.
4432 */
4433 if (done != NULL)
4434 add_reference(hdr, hash_lock, private);
2a432414
GW
4435 if (*arc_flags & ARC_FLAG_PREFETCH)
4436 hdr->b_flags |= ARC_FLAG_PREFETCH;
2a432414
GW
4437 if (*arc_flags & ARC_FLAG_L2CACHE)
4438 hdr->b_flags |= ARC_FLAG_L2CACHE;
4439 if (*arc_flags & ARC_FLAG_L2COMPRESS)
4440 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
34dc7c2f
BB
4441 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4442 buf->b_hdr = hdr;
4443 buf->b_data = NULL;
4444 buf->b_efunc = NULL;
4445 buf->b_private = NULL;
4446 buf->b_next = NULL;
b9541d6b
CW
4447 hdr->b_l1hdr.b_buf = buf;
4448 ASSERT0(hdr->b_l1hdr.b_datacnt);
4449 hdr->b_l1hdr.b_datacnt = 1;
428870ff
BB
4450 arc_get_data_buf(buf);
4451 arc_access(hdr, hash_lock);
34dc7c2f
BB
4452 }
4453
7f60329a
MA
4454 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
4455 hdr->b_flags |= ARC_FLAG_PREDICTIVE_PREFETCH;
b9541d6b 4456 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
428870ff 4457
79c76d5b 4458 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
34dc7c2f
BB
4459 acb->acb_done = done;
4460 acb->acb_private = private;
34dc7c2f 4461
b9541d6b
CW
4462 ASSERT(hdr->b_l1hdr.b_acb == NULL);
4463 hdr->b_l1hdr.b_acb = acb;
2a432414 4464 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
34dc7c2f 4465
b9541d6b
CW
4466 if (HDR_HAS_L2HDR(hdr) &&
4467 (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4468 devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4469 addr = hdr->b_l2hdr.b_daddr;
4e0f33ff 4470 b_compress = hdr->b_l2hdr.b_compress;
b9541d6b 4471 b_asize = hdr->b_l2hdr.b_asize;
b128c09f
BB
4472 /*
4473 * Lock out device removal.
4474 */
4475 if (vdev_is_dead(vd) ||
4476 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4477 vd = NULL;
4478 }
4479
9b67f605
MA
4480 if (hash_lock != NULL)
4481 mutex_exit(hash_lock);
b128c09f 4482
e49f1e20
WA
4483 /*
4484 * At this point, we have a level 1 cache miss. Try again in
4485 * L2ARC if possible.
4486 */
34dc7c2f 4487 ASSERT3U(hdr->b_size, ==, size);
428870ff 4488 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5dbd68a3 4489 uint64_t, size, zbookmark_phys_t *, zb);
34dc7c2f 4490 ARCSTAT_BUMP(arcstat_misses);
b9541d6b
CW
4491 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4492 demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
34dc7c2f
BB
4493 data, metadata, misses);
4494
7f60329a
MA
4495 if (priority == ZIO_PRIORITY_ASYNC_READ)
4496 hdr->b_flags |= ARC_FLAG_PRIO_ASYNC_READ;
4497 else
4498 hdr->b_flags &= ~ARC_FLAG_PRIO_ASYNC_READ;
4499
d164b209 4500 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
34dc7c2f
BB
4501 /*
4502 * Read from the L2ARC if the following are true:
b128c09f
BB
4503 * 1. The L2ARC vdev was previously cached.
4504 * 2. This buffer still has L2ARC metadata.
4505 * 3. This buffer isn't currently writing to the L2ARC.
4506 * 4. The L2ARC entry wasn't evicted, which may
4507 * also have invalidated the vdev.
d164b209 4508 * 5. This isn't prefetch and l2arc_noprefetch is set.
34dc7c2f 4509 */
b9541d6b 4510 if (HDR_HAS_L2HDR(hdr) &&
d164b209
BB
4511 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4512 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
34dc7c2f
BB
4513 l2arc_read_callback_t *cb;
4514
4515 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4516 ARCSTAT_BUMP(arcstat_l2_hits);
b9541d6b 4517 atomic_inc_32(&hdr->b_l2hdr.b_hits);
34dc7c2f 4518
34dc7c2f 4519 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
79c76d5b 4520 KM_SLEEP);
34dc7c2f
BB
4521 cb->l2rcb_buf = buf;
4522 cb->l2rcb_spa = spa;
4523 cb->l2rcb_bp = *bp;
4524 cb->l2rcb_zb = *zb;
b128c09f 4525 cb->l2rcb_flags = zio_flags;
0ed212dc 4526 cb->l2rcb_compress = b_compress;
34dc7c2f 4527
a117a6d6
GW
4528 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4529 addr + size < vd->vdev_psize -
4530 VDEV_LABEL_END_SIZE);
4531
34dc7c2f 4532 /*
b128c09f
BB
4533 * l2arc read. The SCL_L2ARC lock will be
4534 * released by l2arc_read_done().
3a17a7a9
SK
4535 * Issue a null zio if the underlying buffer
4536 * was squashed to zero size by compression.
34dc7c2f 4537 */
0ed212dc 4538 if (b_compress == ZIO_COMPRESS_EMPTY) {
3a17a7a9
SK
4539 rzio = zio_null(pio, spa, vd,
4540 l2arc_read_done, cb,
4541 zio_flags | ZIO_FLAG_DONT_CACHE |
4542 ZIO_FLAG_CANFAIL |
4543 ZIO_FLAG_DONT_PROPAGATE |
4544 ZIO_FLAG_DONT_RETRY);
4545 } else {
4546 rzio = zio_read_phys(pio, vd, addr,
0ed212dc
BP
4547 b_asize, buf->b_data,
4548 ZIO_CHECKSUM_OFF,
3a17a7a9
SK
4549 l2arc_read_done, cb, priority,
4550 zio_flags | ZIO_FLAG_DONT_CACHE |
4551 ZIO_FLAG_CANFAIL |
4552 ZIO_FLAG_DONT_PROPAGATE |
4553 ZIO_FLAG_DONT_RETRY, B_FALSE);
4554 }
34dc7c2f
BB
4555 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4556 zio_t *, rzio);
0ed212dc 4557 ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
34dc7c2f 4558
2a432414 4559 if (*arc_flags & ARC_FLAG_NOWAIT) {
b128c09f 4560 zio_nowait(rzio);
1421c891 4561 goto out;
b128c09f 4562 }
34dc7c2f 4563
2a432414 4564 ASSERT(*arc_flags & ARC_FLAG_WAIT);
b128c09f 4565 if (zio_wait(rzio) == 0)
1421c891 4566 goto out;
b128c09f
BB
4567
4568 /* l2arc read error; goto zio_read() */
34dc7c2f
BB
4569 } else {
4570 DTRACE_PROBE1(l2arc__miss,
4571 arc_buf_hdr_t *, hdr);
4572 ARCSTAT_BUMP(arcstat_l2_misses);
4573 if (HDR_L2_WRITING(hdr))
4574 ARCSTAT_BUMP(arcstat_l2_rw_clash);
b128c09f 4575 spa_config_exit(spa, SCL_L2ARC, vd);
34dc7c2f 4576 }
d164b209
BB
4577 } else {
4578 if (vd != NULL)
4579 spa_config_exit(spa, SCL_L2ARC, vd);
4580 if (l2arc_ndev != 0) {
4581 DTRACE_PROBE1(l2arc__miss,
4582 arc_buf_hdr_t *, hdr);
4583 ARCSTAT_BUMP(arcstat_l2_misses);
4584 }
34dc7c2f 4585 }
34dc7c2f
BB
4586
4587 rzio = zio_read(pio, spa, bp, buf->b_data, size,
b128c09f 4588 arc_read_done, buf, priority, zio_flags, zb);
34dc7c2f 4589
2a432414 4590 if (*arc_flags & ARC_FLAG_WAIT) {
1421c891
PS
4591 rc = zio_wait(rzio);
4592 goto out;
4593 }
34dc7c2f 4594
2a432414 4595 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
34dc7c2f
BB
4596 zio_nowait(rzio);
4597 }
1421c891
PS
4598
4599out:
4600 spa_read_history_add(spa, zb, *arc_flags);
4601 return (rc);
34dc7c2f
BB
4602}
4603
ab26409d
BB
4604arc_prune_t *
4605arc_add_prune_callback(arc_prune_func_t *func, void *private)
4606{
4607 arc_prune_t *p;
4608
d1d7e268 4609 p = kmem_alloc(sizeof (*p), KM_SLEEP);
ab26409d
BB
4610 p->p_pfunc = func;
4611 p->p_private = private;
4612 list_link_init(&p->p_node);
4613 refcount_create(&p->p_refcnt);
4614
4615 mutex_enter(&arc_prune_mtx);
4616 refcount_add(&p->p_refcnt, &arc_prune_list);
4617 list_insert_head(&arc_prune_list, p);
4618 mutex_exit(&arc_prune_mtx);
4619
4620 return (p);
4621}
4622
4623void
4624arc_remove_prune_callback(arc_prune_t *p)
4625{
4442f60d 4626 boolean_t wait = B_FALSE;
ab26409d
BB
4627 mutex_enter(&arc_prune_mtx);
4628 list_remove(&arc_prune_list, p);
4442f60d
CC
4629 if (refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
4630 wait = B_TRUE;
ab26409d 4631 mutex_exit(&arc_prune_mtx);
4442f60d
CC
4632
4633 /* wait for arc_prune_task to finish */
4634 if (wait)
4635 taskq_wait_outstanding(arc_prune_taskq, 0);
4636 ASSERT0(refcount_count(&p->p_refcnt));
4637 refcount_destroy(&p->p_refcnt);
4638 kmem_free(p, sizeof (*p));
ab26409d
BB
4639}
4640
34dc7c2f
BB
4641void
4642arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4643{
4644 ASSERT(buf->b_hdr != NULL);
b9541d6b
CW
4645 ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4646 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4647 func == NULL);
428870ff
BB
4648 ASSERT(buf->b_efunc == NULL);
4649 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4650
34dc7c2f
BB
4651 buf->b_efunc = func;
4652 buf->b_private = private;
4653}
4654
df4474f9
MA
4655/*
4656 * Notify the arc that a block was freed, and thus will never be used again.
4657 */
4658void
4659arc_freed(spa_t *spa, const blkptr_t *bp)
4660{
4661 arc_buf_hdr_t *hdr;
4662 kmutex_t *hash_lock;
4663 uint64_t guid = spa_load_guid(spa);
4664
9b67f605
MA
4665 ASSERT(!BP_IS_EMBEDDED(bp));
4666
4667 hdr = buf_hash_find(guid, bp, &hash_lock);
df4474f9
MA
4668 if (hdr == NULL)
4669 return;
4670 if (HDR_BUF_AVAILABLE(hdr)) {
b9541d6b 4671 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
df4474f9 4672 add_reference(hdr, hash_lock, FTAG);
2a432414 4673 hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
df4474f9
MA
4674 mutex_exit(hash_lock);
4675
4676 arc_release(buf, FTAG);
4677 (void) arc_buf_remove_ref(buf, FTAG);
4678 } else {
4679 mutex_exit(hash_lock);
4680 }
4681
4682}
4683
34dc7c2f 4684/*
bd089c54
MA
4685 * Clear the user eviction callback set by arc_set_callback(), first calling
4686 * it if it exists. Because the presence of a callback keeps an arc_buf cached
4687 * clearing the callback may result in the arc_buf being destroyed. However,
4688 * it will not result in the *last* arc_buf being destroyed, hence the data
4689 * will remain cached in the ARC. We make a copy of the arc buffer here so
4690 * that we can process the callback without holding any locks.
4691 *
4692 * It's possible that the callback is already in the process of being cleared
4693 * by another thread. In this case we can not clear the callback.
4694 *
4695 * Returns B_TRUE if the callback was successfully called and cleared.
34dc7c2f 4696 */
bd089c54
MA
4697boolean_t
4698arc_clear_callback(arc_buf_t *buf)
34dc7c2f
BB
4699{
4700 arc_buf_hdr_t *hdr;
4701 kmutex_t *hash_lock;
bd089c54
MA
4702 arc_evict_func_t *efunc = buf->b_efunc;
4703 void *private = buf->b_private;
34dc7c2f 4704
428870ff 4705 mutex_enter(&buf->b_evict_lock);
34dc7c2f
BB
4706 hdr = buf->b_hdr;
4707 if (hdr == NULL) {
4708 /*
4709 * We are in arc_do_user_evicts().
4710 */
4711 ASSERT(buf->b_data == NULL);
428870ff 4712 mutex_exit(&buf->b_evict_lock);
bd089c54 4713 return (B_FALSE);
b128c09f 4714 } else if (buf->b_data == NULL) {
34dc7c2f 4715 /*
b128c09f
BB
4716 * We are on the eviction list; process this buffer now
4717 * but let arc_do_user_evicts() do the reaping.
34dc7c2f 4718 */
b128c09f 4719 buf->b_efunc = NULL;
428870ff 4720 mutex_exit(&buf->b_evict_lock);
bd089c54
MA
4721 VERIFY0(efunc(private));
4722 return (B_TRUE);
34dc7c2f 4723 }
b128c09f
BB
4724 hash_lock = HDR_LOCK(hdr);
4725 mutex_enter(hash_lock);
428870ff
BB
4726 hdr = buf->b_hdr;
4727 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 4728
b9541d6b
CW
4729 ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4730 hdr->b_l1hdr.b_datacnt);
4731 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4732 hdr->b_l1hdr.b_state == arc_mfu);
34dc7c2f 4733
bd089c54
MA
4734 buf->b_efunc = NULL;
4735 buf->b_private = NULL;
34dc7c2f 4736
b9541d6b 4737 if (hdr->b_l1hdr.b_datacnt > 1) {
bd089c54 4738 mutex_exit(&buf->b_evict_lock);
ca0bf58d 4739 arc_buf_destroy(buf, TRUE);
bd089c54 4740 } else {
b9541d6b 4741 ASSERT(buf == hdr->b_l1hdr.b_buf);
2a432414 4742 hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
bd089c54 4743 mutex_exit(&buf->b_evict_lock);
34dc7c2f 4744 }
34dc7c2f 4745
bd089c54
MA
4746 mutex_exit(hash_lock);
4747 VERIFY0(efunc(private));
4748 return (B_TRUE);
34dc7c2f
BB
4749}
4750
4751/*
e49f1e20
WA
4752 * Release this buffer from the cache, making it an anonymous buffer. This
4753 * must be done after a read and prior to modifying the buffer contents.
34dc7c2f 4754 * If the buffer has more than one reference, we must make
b128c09f 4755 * a new hdr for the buffer.
34dc7c2f
BB
4756 */
4757void
4758arc_release(arc_buf_t *buf, void *tag)
4759{
b9541d6b
CW
4760 kmutex_t *hash_lock;
4761 arc_state_t *state;
4762 arc_buf_hdr_t *hdr = buf->b_hdr;
34dc7c2f 4763
428870ff 4764 /*
ca0bf58d 4765 * It would be nice to assert that if its DMU metadata (level >
428870ff
BB
4766 * 0 || it's the dnode file), then it must be syncing context.
4767 * But we don't know that information at this level.
4768 */
4769
4770 mutex_enter(&buf->b_evict_lock);
b128c09f 4771
ca0bf58d
PS
4772 ASSERT(HDR_HAS_L1HDR(hdr));
4773
b9541d6b
CW
4774 /*
4775 * We don't grab the hash lock prior to this check, because if
4776 * the buffer's header is in the arc_anon state, it won't be
4777 * linked into the hash table.
4778 */
4779 if (hdr->b_l1hdr.b_state == arc_anon) {
4780 mutex_exit(&buf->b_evict_lock);
4781 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4782 ASSERT(!HDR_IN_HASH_TABLE(hdr));
4783 ASSERT(!HDR_HAS_L2HDR(hdr));
4784 ASSERT(BUF_EMPTY(hdr));
34dc7c2f 4785
b9541d6b
CW
4786 ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4787 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4788 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4789
4790 ASSERT3P(buf->b_efunc, ==, NULL);
4791 ASSERT3P(buf->b_private, ==, NULL);
4792
4793 hdr->b_l1hdr.b_arc_access = 0;
4794 arc_buf_thaw(buf);
4795
4796 return;
34dc7c2f
BB
4797 }
4798
b9541d6b
CW
4799 hash_lock = HDR_LOCK(hdr);
4800 mutex_enter(hash_lock);
4801
4802 /*
4803 * This assignment is only valid as long as the hash_lock is
4804 * held, we must be careful not to reference state or the
4805 * b_state field after dropping the lock.
4806 */
4807 state = hdr->b_l1hdr.b_state;
4808 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4809 ASSERT3P(state, !=, arc_anon);
4810
4811 /* this buffer is not on any list */
4812 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4813
4814 if (HDR_HAS_L2HDR(hdr)) {
b9541d6b 4815 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
ca0bf58d
PS
4816
4817 /*
d962d5da
PS
4818 * We have to recheck this conditional again now that
4819 * we're holding the l2ad_mtx to prevent a race with
4820 * another thread which might be concurrently calling
4821 * l2arc_evict(). In that case, l2arc_evict() might have
4822 * destroyed the header's L2 portion as we were waiting
4823 * to acquire the l2ad_mtx.
ca0bf58d 4824 */
d962d5da
PS
4825 if (HDR_HAS_L2HDR(hdr))
4826 arc_hdr_l2hdr_destroy(hdr);
ca0bf58d 4827
b9541d6b 4828 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
b128c09f
BB
4829 }
4830
34dc7c2f
BB
4831 /*
4832 * Do we have more than one buf?
4833 */
b9541d6b 4834 if (hdr->b_l1hdr.b_datacnt > 1) {
34dc7c2f
BB
4835 arc_buf_hdr_t *nhdr;
4836 arc_buf_t **bufp;
4837 uint64_t blksz = hdr->b_size;
d164b209 4838 uint64_t spa = hdr->b_spa;
b9541d6b 4839 arc_buf_contents_t type = arc_buf_type(hdr);
34dc7c2f
BB
4840 uint32_t flags = hdr->b_flags;
4841
b9541d6b 4842 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
34dc7c2f 4843 /*
428870ff
BB
4844 * Pull the data off of this hdr and attach it to
4845 * a new anonymous hdr.
34dc7c2f
BB
4846 */
4847 (void) remove_reference(hdr, hash_lock, tag);
b9541d6b 4848 bufp = &hdr->b_l1hdr.b_buf;
34dc7c2f
BB
4849 while (*bufp != buf)
4850 bufp = &(*bufp)->b_next;
428870ff 4851 *bufp = buf->b_next;
34dc7c2f
BB
4852 buf->b_next = NULL;
4853
b9541d6b 4854 ASSERT3P(state, !=, arc_l2c_only);
36da08ef
PS
4855
4856 (void) refcount_remove_many(
4857 &state->arcs_size, hdr->b_size, buf);
4858
b9541d6b
CW
4859 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4860 uint64_t *size;
4861
4862 ASSERT3P(state, !=, arc_l2c_only);
4863 size = &state->arcs_lsize[type];
34dc7c2f
BB
4864 ASSERT3U(*size, >=, hdr->b_size);
4865 atomic_add_64(size, -hdr->b_size);
4866 }
1eb5bfa3
GW
4867
4868 /*
4869 * We're releasing a duplicate user data buffer, update
4870 * our statistics accordingly.
4871 */
b9541d6b 4872 if (HDR_ISTYPE_DATA(hdr)) {
1eb5bfa3
GW
4873 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4874 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4875 -hdr->b_size);
4876 }
b9541d6b 4877 hdr->b_l1hdr.b_datacnt -= 1;
34dc7c2f 4878 arc_cksum_verify(buf);
498877ba 4879 arc_buf_unwatch(buf);
34dc7c2f
BB
4880
4881 mutex_exit(hash_lock);
4882
b9541d6b 4883 nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
34dc7c2f
BB
4884 nhdr->b_size = blksz;
4885 nhdr->b_spa = spa;
b9541d6b
CW
4886
4887 nhdr->b_l1hdr.b_mru_hits = 0;
4888 nhdr->b_l1hdr.b_mru_ghost_hits = 0;
4889 nhdr->b_l1hdr.b_mfu_hits = 0;
4890 nhdr->b_l1hdr.b_mfu_ghost_hits = 0;
4891 nhdr->b_l1hdr.b_l2_hits = 0;
2a432414 4892 nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
b9541d6b
CW
4893 nhdr->b_flags |= arc_bufc_to_flags(type);
4894 nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4895
4896 nhdr->b_l1hdr.b_buf = buf;
4897 nhdr->b_l1hdr.b_datacnt = 1;
4898 nhdr->b_l1hdr.b_state = arc_anon;
4899 nhdr->b_l1hdr.b_arc_access = 0;
ca0bf58d 4900 nhdr->b_l1hdr.b_tmp_cdata = NULL;
34dc7c2f 4901 nhdr->b_freeze_cksum = NULL;
b9541d6b
CW
4902
4903 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
34dc7c2f 4904 buf->b_hdr = nhdr;
428870ff 4905 mutex_exit(&buf->b_evict_lock);
36da08ef 4906 (void) refcount_add_many(&arc_anon->arcs_size, blksz, buf);
34dc7c2f 4907 } else {
428870ff 4908 mutex_exit(&buf->b_evict_lock);
b9541d6b 4909 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
ca0bf58d
PS
4910 /* protected by hash lock, or hdr is on arc_anon */
4911 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
34dc7c2f 4912 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
b9541d6b
CW
4913 hdr->b_l1hdr.b_mru_hits = 0;
4914 hdr->b_l1hdr.b_mru_ghost_hits = 0;
4915 hdr->b_l1hdr.b_mfu_hits = 0;
4916 hdr->b_l1hdr.b_mfu_ghost_hits = 0;
4917 hdr->b_l1hdr.b_l2_hits = 0;
4918 arc_change_state(arc_anon, hdr, hash_lock);
4919 hdr->b_l1hdr.b_arc_access = 0;
4920 mutex_exit(hash_lock);
34dc7c2f 4921
428870ff 4922 buf_discard_identity(hdr);
34dc7c2f
BB
4923 arc_buf_thaw(buf);
4924 }
4925 buf->b_efunc = NULL;
4926 buf->b_private = NULL;
34dc7c2f
BB
4927}
4928
4929int
4930arc_released(arc_buf_t *buf)
4931{
b128c09f
BB
4932 int released;
4933
428870ff 4934 mutex_enter(&buf->b_evict_lock);
b9541d6b
CW
4935 released = (buf->b_data != NULL &&
4936 buf->b_hdr->b_l1hdr.b_state == arc_anon);
428870ff 4937 mutex_exit(&buf->b_evict_lock);
b128c09f 4938 return (released);
34dc7c2f
BB
4939}
4940
34dc7c2f
BB
4941#ifdef ZFS_DEBUG
4942int
4943arc_referenced(arc_buf_t *buf)
4944{
b128c09f
BB
4945 int referenced;
4946
428870ff 4947 mutex_enter(&buf->b_evict_lock);
b9541d6b 4948 referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
428870ff 4949 mutex_exit(&buf->b_evict_lock);
b128c09f 4950 return (referenced);
34dc7c2f
BB
4951}
4952#endif
4953
4954static void
4955arc_write_ready(zio_t *zio)
4956{
4957 arc_write_callback_t *callback = zio->io_private;
4958 arc_buf_t *buf = callback->awcb_buf;
4959 arc_buf_hdr_t *hdr = buf->b_hdr;
4960
b9541d6b
CW
4961 ASSERT(HDR_HAS_L1HDR(hdr));
4962 ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4963 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
b128c09f
BB
4964 callback->awcb_ready(zio, buf, callback->awcb_private);
4965
34dc7c2f
BB
4966 /*
4967 * If the IO is already in progress, then this is a re-write
b128c09f
BB
4968 * attempt, so we need to thaw and re-compute the cksum.
4969 * It is the responsibility of the callback to handle the
4970 * accounting for any re-write attempt.
34dc7c2f
BB
4971 */
4972 if (HDR_IO_IN_PROGRESS(hdr)) {
b9541d6b 4973 mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
4974 if (hdr->b_freeze_cksum != NULL) {
4975 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4976 hdr->b_freeze_cksum = NULL;
4977 }
b9541d6b 4978 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
34dc7c2f
BB
4979 }
4980 arc_cksum_compute(buf, B_FALSE);
2a432414 4981 hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
34dc7c2f
BB
4982}
4983
e8b96c60
MA
4984/*
4985 * The SPA calls this callback for each physical write that happens on behalf
4986 * of a logical write. See the comment in dbuf_write_physdone() for details.
4987 */
4988static void
4989arc_write_physdone(zio_t *zio)
4990{
4991 arc_write_callback_t *cb = zio->io_private;
4992 if (cb->awcb_physdone != NULL)
4993 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4994}
4995
34dc7c2f
BB
4996static void
4997arc_write_done(zio_t *zio)
4998{
4999 arc_write_callback_t *callback = zio->io_private;
5000 arc_buf_t *buf = callback->awcb_buf;
5001 arc_buf_hdr_t *hdr = buf->b_hdr;
5002
b9541d6b 5003 ASSERT(hdr->b_l1hdr.b_acb == NULL);
428870ff
BB
5004
5005 if (zio->io_error == 0) {
9b67f605 5006 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
b0bc7a84
MG
5007 buf_discard_identity(hdr);
5008 } else {
5009 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5010 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
b0bc7a84 5011 }
428870ff
BB
5012 } else {
5013 ASSERT(BUF_EMPTY(hdr));
5014 }
34dc7c2f 5015
34dc7c2f 5016 /*
9b67f605
MA
5017 * If the block to be written was all-zero or compressed enough to be
5018 * embedded in the BP, no write was performed so there will be no
5019 * dva/birth/checksum. The buffer must therefore remain anonymous
5020 * (and uncached).
34dc7c2f
BB
5021 */
5022 if (!BUF_EMPTY(hdr)) {
5023 arc_buf_hdr_t *exists;
5024 kmutex_t *hash_lock;
5025
428870ff
BB
5026 ASSERT(zio->io_error == 0);
5027
34dc7c2f
BB
5028 arc_cksum_verify(buf);
5029
5030 exists = buf_hash_insert(hdr, &hash_lock);
b9541d6b 5031 if (exists != NULL) {
34dc7c2f
BB
5032 /*
5033 * This can only happen if we overwrite for
5034 * sync-to-convergence, because we remove
5035 * buffers from the hash table when we arc_free().
5036 */
428870ff
BB
5037 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5038 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5039 panic("bad overwrite, hdr=%p exists=%p",
5040 (void *)hdr, (void *)exists);
b9541d6b
CW
5041 ASSERT(refcount_is_zero(
5042 &exists->b_l1hdr.b_refcnt));
428870ff
BB
5043 arc_change_state(arc_anon, exists, hash_lock);
5044 mutex_exit(hash_lock);
5045 arc_hdr_destroy(exists);
5046 exists = buf_hash_insert(hdr, &hash_lock);
5047 ASSERT3P(exists, ==, NULL);
03c6040b
GW
5048 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5049 /* nopwrite */
5050 ASSERT(zio->io_prop.zp_nopwrite);
5051 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5052 panic("bad nopwrite, hdr=%p exists=%p",
5053 (void *)hdr, (void *)exists);
428870ff
BB
5054 } else {
5055 /* Dedup */
b9541d6b
CW
5056 ASSERT(hdr->b_l1hdr.b_datacnt == 1);
5057 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
428870ff
BB
5058 ASSERT(BP_GET_DEDUP(zio->io_bp));
5059 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5060 }
34dc7c2f 5061 }
2a432414 5062 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
b128c09f 5063 /* if it's not anon, we are doing a scrub */
b9541d6b 5064 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
b128c09f 5065 arc_access(hdr, hash_lock);
34dc7c2f 5066 mutex_exit(hash_lock);
34dc7c2f 5067 } else {
2a432414 5068 hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
34dc7c2f
BB
5069 }
5070
b9541d6b 5071 ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
428870ff 5072 callback->awcb_done(zio, buf, callback->awcb_private);
34dc7c2f
BB
5073
5074 kmem_free(callback, sizeof (arc_write_callback_t));
5075}
5076
5077zio_t *
428870ff 5078arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3a17a7a9 5079 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
e8b96c60
MA
5080 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
5081 arc_done_func_t *done, void *private, zio_priority_t priority,
5dbd68a3 5082 int zio_flags, const zbookmark_phys_t *zb)
34dc7c2f
BB
5083{
5084 arc_buf_hdr_t *hdr = buf->b_hdr;
5085 arc_write_callback_t *callback;
b128c09f 5086 zio_t *zio;
34dc7c2f 5087
b128c09f 5088 ASSERT(ready != NULL);
428870ff 5089 ASSERT(done != NULL);
34dc7c2f 5090 ASSERT(!HDR_IO_ERROR(hdr));
b9541d6b
CW
5091 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5092 ASSERT(hdr->b_l1hdr.b_acb == NULL);
5093 ASSERT(hdr->b_l1hdr.b_datacnt > 0);
b128c09f 5094 if (l2arc)
2a432414 5095 hdr->b_flags |= ARC_FLAG_L2CACHE;
3a17a7a9 5096 if (l2arc_compress)
2a432414 5097 hdr->b_flags |= ARC_FLAG_L2COMPRESS;
79c76d5b 5098 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
34dc7c2f 5099 callback->awcb_ready = ready;
e8b96c60 5100 callback->awcb_physdone = physdone;
34dc7c2f
BB
5101 callback->awcb_done = done;
5102 callback->awcb_private = private;
5103 callback->awcb_buf = buf;
b128c09f 5104
428870ff 5105 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
e8b96c60
MA
5106 arc_write_ready, arc_write_physdone, arc_write_done, callback,
5107 priority, zio_flags, zb);
34dc7c2f
BB
5108
5109 return (zio);
5110}
5111
34dc7c2f 5112static int
e8b96c60 5113arc_memory_throttle(uint64_t reserve, uint64_t txg)
34dc7c2f
BB
5114{
5115#ifdef _KERNEL
7e8bddd0
BB
5116 uint64_t available_memory = ptob(freemem);
5117 static uint64_t page_load = 0;
5118 static uint64_t last_txg = 0;
5119#ifdef __linux__
5120 pgcnt_t minfree = btop(arc_sys_free / 4);
5121#endif
0c5493d4 5122
ca67b33a
MA
5123 if (freemem > physmem * arc_lotsfree_percent / 100)
5124 return (0);
5125
7e8bddd0
BB
5126 if (txg > last_txg) {
5127 last_txg = txg;
5128 page_load = 0;
5129 }
5130
5131 /*
5132 * If we are in pageout, we know that memory is already tight,
5133 * the arc is already going to be evicting, so we just want to
5134 * continue to let page writes occur as quickly as possible.
5135 */
5136 if (current_is_kswapd()) {
5137 if (page_load > MAX(ptob(minfree), available_memory) / 4) {
5138 DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
5139 return (SET_ERROR(ERESTART));
5140 }
5141 /* Note: reserve is inflated, so we deflate */
5142 page_load += reserve / 8;
5143 return (0);
5144 } else if (page_load > 0 && arc_reclaim_needed()) {
ca67b33a 5145 /* memory is low, delay before restarting */
34dc7c2f 5146 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
570827e1 5147 DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
2e528b49 5148 return (SET_ERROR(EAGAIN));
34dc7c2f 5149 }
7e8bddd0 5150 page_load = 0;
34dc7c2f
BB
5151#endif
5152 return (0);
5153}
5154
5155void
5156arc_tempreserve_clear(uint64_t reserve)
5157{
5158 atomic_add_64(&arc_tempreserve, -reserve);
5159 ASSERT((int64_t)arc_tempreserve >= 0);
5160}
5161
5162int
5163arc_tempreserve_space(uint64_t reserve, uint64_t txg)
5164{
5165 int error;
9babb374 5166 uint64_t anon_size;
34dc7c2f 5167
1b8951b3
TC
5168 if (!arc_no_grow &&
5169 reserve > arc_c/4 &&
5170 reserve * 4 > (2ULL << SPA_MAXBLOCKSHIFT))
34dc7c2f 5171 arc_c = MIN(arc_c_max, reserve * 4);
12f9a6a3
BB
5172
5173 /*
5174 * Throttle when the calculated memory footprint for the TXG
5175 * exceeds the target ARC size.
5176 */
570827e1
BB
5177 if (reserve > arc_c) {
5178 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
12f9a6a3 5179 return (SET_ERROR(ERESTART));
570827e1 5180 }
34dc7c2f 5181
9babb374
BB
5182 /*
5183 * Don't count loaned bufs as in flight dirty data to prevent long
5184 * network delays from blocking transactions that are ready to be
5185 * assigned to a txg.
5186 */
36da08ef
PS
5187 anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
5188 arc_loaned_bytes), 0);
9babb374 5189
34dc7c2f
BB
5190 /*
5191 * Writes will, almost always, require additional memory allocations
d3cc8b15 5192 * in order to compress/encrypt/etc the data. We therefore need to
34dc7c2f
BB
5193 * make sure that there is sufficient available memory for this.
5194 */
e8b96c60
MA
5195 error = arc_memory_throttle(reserve, txg);
5196 if (error != 0)
34dc7c2f
BB
5197 return (error);
5198
5199 /*
5200 * Throttle writes when the amount of dirty data in the cache
5201 * gets too large. We try to keep the cache less than half full
5202 * of dirty blocks so that our sync times don't grow too large.
5203 * Note: if two requests come in concurrently, we might let them
5204 * both succeed, when one of them should fail. Not a huge deal.
5205 */
9babb374
BB
5206
5207 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
5208 anon_size > arc_c / 4) {
34dc7c2f
BB
5209 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5210 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5211 arc_tempreserve>>10,
5212 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
5213 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
5214 reserve>>10, arc_c>>10);
570827e1 5215 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
2e528b49 5216 return (SET_ERROR(ERESTART));
34dc7c2f
BB
5217 }
5218 atomic_add_64(&arc_tempreserve, reserve);
5219 return (0);
5220}
5221
13be560d
BB
5222static void
5223arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5224 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5225{
36da08ef 5226 size->value.ui64 = refcount_count(&state->arcs_size);
13be560d
BB
5227 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
5228 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
5229}
5230
5231static int
5232arc_kstat_update(kstat_t *ksp, int rw)
5233{
5234 arc_stats_t *as = ksp->ks_data;
5235
5236 if (rw == KSTAT_WRITE) {
500445c0 5237 return (EACCES);
13be560d
BB
5238 } else {
5239 arc_kstat_update_state(arc_anon,
5240 &as->arcstat_anon_size,
500445c0
PS
5241 &as->arcstat_anon_evictable_data,
5242 &as->arcstat_anon_evictable_metadata);
13be560d
BB
5243 arc_kstat_update_state(arc_mru,
5244 &as->arcstat_mru_size,
500445c0
PS
5245 &as->arcstat_mru_evictable_data,
5246 &as->arcstat_mru_evictable_metadata);
13be560d
BB
5247 arc_kstat_update_state(arc_mru_ghost,
5248 &as->arcstat_mru_ghost_size,
500445c0
PS
5249 &as->arcstat_mru_ghost_evictable_data,
5250 &as->arcstat_mru_ghost_evictable_metadata);
13be560d
BB
5251 arc_kstat_update_state(arc_mfu,
5252 &as->arcstat_mfu_size,
500445c0
PS
5253 &as->arcstat_mfu_evictable_data,
5254 &as->arcstat_mfu_evictable_metadata);
fc41c640 5255 arc_kstat_update_state(arc_mfu_ghost,
13be560d 5256 &as->arcstat_mfu_ghost_size,
500445c0
PS
5257 &as->arcstat_mfu_ghost_evictable_data,
5258 &as->arcstat_mfu_ghost_evictable_metadata);
13be560d
BB
5259 }
5260
5261 return (0);
5262}
5263
ca0bf58d
PS
5264/*
5265 * This function *must* return indices evenly distributed between all
5266 * sublists of the multilist. This is needed due to how the ARC eviction
5267 * code is laid out; arc_evict_state() assumes ARC buffers are evenly
5268 * distributed between all sublists and uses this assumption when
5269 * deciding which sublist to evict from and how much to evict from it.
5270 */
5271unsigned int
5272arc_state_multilist_index_func(multilist_t *ml, void *obj)
5273{
5274 arc_buf_hdr_t *hdr = obj;
5275
5276 /*
5277 * We rely on b_dva to generate evenly distributed index
5278 * numbers using buf_hash below. So, as an added precaution,
5279 * let's make sure we never add empty buffers to the arc lists.
5280 */
5281 ASSERT(!BUF_EMPTY(hdr));
5282
5283 /*
5284 * The assumption here, is the hash value for a given
5285 * arc_buf_hdr_t will remain constant throughout its lifetime
5286 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
5287 * Thus, we don't need to store the header's sublist index
5288 * on insertion, as this index can be recalculated on removal.
5289 *
5290 * Also, the low order bits of the hash value are thought to be
5291 * distributed evenly. Otherwise, in the case that the multilist
5292 * has a power of two number of sublists, each sublists' usage
5293 * would not be evenly distributed.
5294 */
5295 return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
5296 multilist_get_num_sublists(ml));
5297}
5298
ca67b33a
MA
5299/*
5300 * Called during module initialization and periodically thereafter to
5301 * apply reasonable changes to the exposed performance tunings. Non-zero
5302 * zfs_* values which differ from the currently set values will be applied.
5303 */
5304static void
5305arc_tuning_update(void)
5306{
5307 /* Valid range: 64M - <all physical memory> */
5308 if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
5309 (zfs_arc_max > 64 << 20) && (zfs_arc_max < ptob(physmem)) &&
5310 (zfs_arc_max > arc_c_min)) {
5311 arc_c_max = zfs_arc_max;
5312 arc_c = arc_c_max;
5313 arc_p = (arc_c >> 1);
256fa983 5314 arc_meta_limit = MIN(arc_meta_limit, (3 * arc_c_max) / 4);
ca67b33a
MA
5315 }
5316
5317 /* Valid range: 32M - <arc_c_max> */
5318 if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
5319 (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
5320 (zfs_arc_min <= arc_c_max)) {
5321 arc_c_min = zfs_arc_min;
5322 arc_c = MAX(arc_c, arc_c_min);
5323 }
5324
5325 /* Valid range: 16M - <arc_c_max> */
5326 if ((zfs_arc_meta_min) && (zfs_arc_meta_min != arc_meta_min) &&
5327 (zfs_arc_meta_min >= 1ULL << SPA_MAXBLOCKSHIFT) &&
5328 (zfs_arc_meta_min <= arc_c_max)) {
5329 arc_meta_min = zfs_arc_meta_min;
5330 arc_meta_limit = MAX(arc_meta_limit, arc_meta_min);
5331 }
5332
5333 /* Valid range: <arc_meta_min> - <arc_c_max> */
5334 if ((zfs_arc_meta_limit) && (zfs_arc_meta_limit != arc_meta_limit) &&
5335 (zfs_arc_meta_limit >= zfs_arc_meta_min) &&
5336 (zfs_arc_meta_limit <= arc_c_max))
5337 arc_meta_limit = zfs_arc_meta_limit;
5338
5339 /* Valid range: 1 - N */
5340 if (zfs_arc_grow_retry)
5341 arc_grow_retry = zfs_arc_grow_retry;
5342
5343 /* Valid range: 1 - N */
5344 if (zfs_arc_shrink_shift) {
5345 arc_shrink_shift = zfs_arc_shrink_shift;
5346 arc_no_grow_shift = MIN(arc_no_grow_shift, arc_shrink_shift -1);
5347 }
5348
728d6ae9
BB
5349 /* Valid range: 1 - N */
5350 if (zfs_arc_p_min_shift)
5351 arc_p_min_shift = zfs_arc_p_min_shift;
5352
ca67b33a
MA
5353 /* Valid range: 1 - N ticks */
5354 if (zfs_arc_min_prefetch_lifespan)
5355 arc_min_prefetch_lifespan = zfs_arc_min_prefetch_lifespan;
11f552fa 5356
7e8bddd0
BB
5357 /* Valid range: 0 - 100 */
5358 if ((zfs_arc_lotsfree_percent >= 0) &&
5359 (zfs_arc_lotsfree_percent <= 100))
5360 arc_lotsfree_percent = zfs_arc_lotsfree_percent;
5361
11f552fa
BB
5362 /* Valid range: 0 - <all physical memory> */
5363 if ((zfs_arc_sys_free) && (zfs_arc_sys_free != arc_sys_free))
5364 arc_sys_free = MIN(MAX(zfs_arc_sys_free, 0), ptob(physmem));
7e8bddd0 5365
ca67b33a
MA
5366}
5367
34dc7c2f
BB
5368void
5369arc_init(void)
5370{
ca67b33a
MA
5371 /*
5372 * allmem is "all memory that we could possibly use".
5373 */
5374#ifdef _KERNEL
5375 uint64_t allmem = ptob(physmem);
5376#else
5377 uint64_t allmem = (physmem * PAGESIZE) / 2;
5378#endif
5379
ca0bf58d
PS
5380 mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
5381 cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
5382 cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
5383
5384 mutex_init(&arc_user_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
5385 cv_init(&arc_user_evicts_cv, NULL, CV_DEFAULT, NULL);
34dc7c2f
BB
5386
5387 /* Convert seconds to clock ticks */
ca67b33a 5388 arc_min_prefetch_lifespan = 1 * hz;
34dc7c2f
BB
5389
5390 /* Start out with 1/8 of all memory */
ca67b33a 5391 arc_c = allmem / 8;
34dc7c2f
BB
5392
5393#ifdef _KERNEL
5394 /*
5395 * On architectures where the physical memory can be larger
5396 * than the addressable space (intel in 32-bit mode), we may
5397 * need to limit the cache to 1/8 of VM size.
5398 */
5399 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
ca67b33a 5400
7cb67b45
BB
5401 /*
5402 * Register a shrinker to support synchronous (direct) memory
5403 * reclaim from the arc. This is done to prevent kswapd from
5404 * swapping out pages when it is preferable to shrink the arc.
5405 */
5406 spl_register_shrinker(&arc_shrinker);
11f552fa
BB
5407
5408 /* Set to 1/64 of all memory or a minimum of 512K */
5409 arc_sys_free = MAX(ptob(physmem / 64), (512 * 1024));
5410 arc_need_free = 0;
34dc7c2f
BB
5411#endif
5412
0a1f8cd9
TC
5413 /* Set max to 1/2 of all memory */
5414 arc_c_max = allmem / 2;
5415
ab5cbbd1
BB
5416 /*
5417 * In userland, there's only the memory pressure that we artificially
5418 * create (see arc_available_memory()). Don't let arc_c get too
5419 * small, because it can cause transactions to be larger than
5420 * arc_c, causing arc_tempreserve_space() to fail.
5421 */
5422#ifndef _KERNEL
0a1f8cd9 5423 arc_c_min = MAX(arc_c_max / 2, 2ULL << SPA_MAXBLOCKSHIFT);
ab5cbbd1 5424#else
121b3cae 5425 arc_c_min = 2ULL << SPA_MAXBLOCKSHIFT;
ab5cbbd1
BB
5426#endif
5427
34dc7c2f
BB
5428 arc_c = arc_c_max;
5429 arc_p = (arc_c >> 1);
5430
ca67b33a
MA
5431 /* Set min to 1/2 of arc_c_min */
5432 arc_meta_min = 1ULL << SPA_MAXBLOCKSHIFT;
5433 /* Initialize maximum observed usage to zero */
1834f2d8 5434 arc_meta_max = 0;
ca67b33a
MA
5435 /* Set limit to 3/4 of arc_c_max with a floor of arc_meta_min */
5436 arc_meta_limit = MAX((3 * arc_c_max) / 4, arc_meta_min);
34dc7c2f 5437
ca67b33a
MA
5438 /* Apply user specified tunings */
5439 arc_tuning_update();
c52fca13 5440
ca0bf58d 5441 if (zfs_arc_num_sublists_per_state < 1)
ca67b33a 5442 zfs_arc_num_sublists_per_state = MAX(boot_ncpus, 1);
ca0bf58d 5443
34dc7c2f
BB
5444 /* if kmem_flags are set, lets try to use less memory */
5445 if (kmem_debugging())
5446 arc_c = arc_c / 2;
5447 if (arc_c < arc_c_min)
5448 arc_c = arc_c_min;
5449
5450 arc_anon = &ARC_anon;
5451 arc_mru = &ARC_mru;
5452 arc_mru_ghost = &ARC_mru_ghost;
5453 arc_mfu = &ARC_mfu;
5454 arc_mfu_ghost = &ARC_mfu_ghost;
5455 arc_l2c_only = &ARC_l2c_only;
5456 arc_size = 0;
5457
ca0bf58d 5458 multilist_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
b9541d6b 5459 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5460 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5461 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5462 multilist_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
b9541d6b 5463 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5464 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5465 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5466 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
b9541d6b 5467 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5468 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5469 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5470 multilist_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
b9541d6b 5471 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5472 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5473 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5474 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
b9541d6b 5475 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5476 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5477 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5478 multilist_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
b9541d6b 5479 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5480 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5481 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5482 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
b9541d6b 5483 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5484 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5485 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5486 multilist_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
b9541d6b 5487 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5488 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5489 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5490 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
b9541d6b 5491 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5492 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5493 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
5494 multilist_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
b9541d6b 5495 sizeof (arc_buf_hdr_t),
ca0bf58d
PS
5496 offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
5497 zfs_arc_num_sublists_per_state, arc_state_multilist_index_func);
34dc7c2f 5498
e0b0ca98
BB
5499 arc_anon->arcs_state = ARC_STATE_ANON;
5500 arc_mru->arcs_state = ARC_STATE_MRU;
5501 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
5502 arc_mfu->arcs_state = ARC_STATE_MFU;
5503 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
5504 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
5505
36da08ef
PS
5506 refcount_create(&arc_anon->arcs_size);
5507 refcount_create(&arc_mru->arcs_size);
5508 refcount_create(&arc_mru_ghost->arcs_size);
5509 refcount_create(&arc_mfu->arcs_size);
5510 refcount_create(&arc_mfu_ghost->arcs_size);
5511 refcount_create(&arc_l2c_only->arcs_size);
5512
34dc7c2f
BB
5513 buf_init();
5514
ca0bf58d
PS
5515 arc_reclaim_thread_exit = FALSE;
5516 arc_user_evicts_thread_exit = FALSE;
ab26409d
BB
5517 list_create(&arc_prune_list, sizeof (arc_prune_t),
5518 offsetof(arc_prune_t, p_node));
34dc7c2f 5519 arc_eviction_list = NULL;
ab26409d 5520 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
5521 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
5522
1229323d 5523 arc_prune_taskq = taskq_create("arc_prune", max_ncpus, defclsyspri,
aa9af22c 5524 max_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
f6046738 5525
34dc7c2f
BB
5526 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
5527 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
5528
5529 if (arc_ksp != NULL) {
5530 arc_ksp->ks_data = &arc_stats;
13be560d 5531 arc_ksp->ks_update = arc_kstat_update;
34dc7c2f
BB
5532 kstat_install(arc_ksp);
5533 }
5534
ca67b33a 5535 (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
1229323d 5536 TS_RUN, defclsyspri);
34dc7c2f 5537
ca0bf58d 5538 (void) thread_create(NULL, 0, arc_user_evicts_thread, NULL, 0, &p0,
1229323d 5539 TS_RUN, defclsyspri);
ca0bf58d 5540
34dc7c2f 5541 arc_dead = FALSE;
b128c09f 5542 arc_warm = B_FALSE;
34dc7c2f 5543
e8b96c60
MA
5544 /*
5545 * Calculate maximum amount of dirty data per pool.
5546 *
5547 * If it has been set by a module parameter, take that.
5548 * Otherwise, use a percentage of physical memory defined by
5549 * zfs_dirty_data_max_percent (default 10%) with a cap at
5550 * zfs_dirty_data_max_max (default 25% of physical memory).
5551 */
5552 if (zfs_dirty_data_max_max == 0)
43518d92 5553 zfs_dirty_data_max_max = (uint64_t)physmem * PAGESIZE *
e8b96c60
MA
5554 zfs_dirty_data_max_max_percent / 100;
5555
5556 if (zfs_dirty_data_max == 0) {
43518d92 5557 zfs_dirty_data_max = (uint64_t)physmem * PAGESIZE *
e8b96c60
MA
5558 zfs_dirty_data_max_percent / 100;
5559 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5560 zfs_dirty_data_max_max);
5561 }
34dc7c2f
BB
5562}
5563
5564void
5565arc_fini(void)
5566{
ab26409d
BB
5567 arc_prune_t *p;
5568
7cb67b45
BB
5569#ifdef _KERNEL
5570 spl_unregister_shrinker(&arc_shrinker);
5571#endif /* _KERNEL */
5572
ca0bf58d
PS
5573 mutex_enter(&arc_reclaim_lock);
5574 arc_reclaim_thread_exit = TRUE;
5575 /*
5576 * The reclaim thread will set arc_reclaim_thread_exit back to
5577 * FALSE when it is finished exiting; we're waiting for that.
5578 */
5579 while (arc_reclaim_thread_exit) {
5580 cv_signal(&arc_reclaim_thread_cv);
5581 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
5582 }
5583 mutex_exit(&arc_reclaim_lock);
5584
5585 mutex_enter(&arc_user_evicts_lock);
5586 arc_user_evicts_thread_exit = TRUE;
5587 /*
5588 * The user evicts thread will set arc_user_evicts_thread_exit
5589 * to FALSE when it is finished exiting; we're waiting for that.
5590 */
5591 while (arc_user_evicts_thread_exit) {
5592 cv_signal(&arc_user_evicts_cv);
5593 cv_wait(&arc_user_evicts_cv, &arc_user_evicts_lock);
5594 }
5595 mutex_exit(&arc_user_evicts_lock);
34dc7c2f 5596
ca0bf58d
PS
5597 /* Use TRUE to ensure *all* buffers are evicted */
5598 arc_flush(NULL, TRUE);
34dc7c2f
BB
5599
5600 arc_dead = TRUE;
5601
5602 if (arc_ksp != NULL) {
5603 kstat_delete(arc_ksp);
5604 arc_ksp = NULL;
5605 }
5606
f6046738
BB
5607 taskq_wait(arc_prune_taskq);
5608 taskq_destroy(arc_prune_taskq);
5609
ab26409d
BB
5610 mutex_enter(&arc_prune_mtx);
5611 while ((p = list_head(&arc_prune_list)) != NULL) {
5612 list_remove(&arc_prune_list, p);
5613 refcount_remove(&p->p_refcnt, &arc_prune_list);
5614 refcount_destroy(&p->p_refcnt);
5615 kmem_free(p, sizeof (*p));
5616 }
5617 mutex_exit(&arc_prune_mtx);
5618
5619 list_destroy(&arc_prune_list);
5620 mutex_destroy(&arc_prune_mtx);
ca0bf58d
PS
5621 mutex_destroy(&arc_reclaim_lock);
5622 cv_destroy(&arc_reclaim_thread_cv);
5623 cv_destroy(&arc_reclaim_waiters_cv);
5624
5625 mutex_destroy(&arc_user_evicts_lock);
5626 cv_destroy(&arc_user_evicts_cv);
5627
36da08ef
PS
5628 refcount_destroy(&arc_anon->arcs_size);
5629 refcount_destroy(&arc_mru->arcs_size);
5630 refcount_destroy(&arc_mru_ghost->arcs_size);
5631 refcount_destroy(&arc_mfu->arcs_size);
5632 refcount_destroy(&arc_mfu_ghost->arcs_size);
5633 refcount_destroy(&arc_l2c_only->arcs_size);
5634
ca0bf58d
PS
5635 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
5636 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
5637 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
5638 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
5639 multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
5640 multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
5641 multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
5642 multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
5643 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
5644 multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
34dc7c2f
BB
5645
5646 buf_fini();
9babb374 5647
b9541d6b 5648 ASSERT0(arc_loaned_bytes);
34dc7c2f
BB
5649}
5650
5651/*
5652 * Level 2 ARC
5653 *
5654 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5655 * It uses dedicated storage devices to hold cached data, which are populated
5656 * using large infrequent writes. The main role of this cache is to boost
5657 * the performance of random read workloads. The intended L2ARC devices
5658 * include short-stroked disks, solid state disks, and other media with
5659 * substantially faster read latency than disk.
5660 *
5661 * +-----------------------+
5662 * | ARC |
5663 * +-----------------------+
5664 * | ^ ^
5665 * | | |
5666 * l2arc_feed_thread() arc_read()
5667 * | | |
5668 * | l2arc read |
5669 * V | |
5670 * +---------------+ |
5671 * | L2ARC | |
5672 * +---------------+ |
5673 * | ^ |
5674 * l2arc_write() | |
5675 * | | |
5676 * V | |
5677 * +-------+ +-------+
5678 * | vdev | | vdev |
5679 * | cache | | cache |
5680 * +-------+ +-------+
5681 * +=========+ .-----.
5682 * : L2ARC : |-_____-|
5683 * : devices : | Disks |
5684 * +=========+ `-_____-'
5685 *
5686 * Read requests are satisfied from the following sources, in order:
5687 *
5688 * 1) ARC
5689 * 2) vdev cache of L2ARC devices
5690 * 3) L2ARC devices
5691 * 4) vdev cache of disks
5692 * 5) disks
5693 *
5694 * Some L2ARC device types exhibit extremely slow write performance.
5695 * To accommodate for this there are some significant differences between
5696 * the L2ARC and traditional cache design:
5697 *
5698 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
5699 * the ARC behave as usual, freeing buffers and placing headers on ghost
5700 * lists. The ARC does not send buffers to the L2ARC during eviction as
5701 * this would add inflated write latencies for all ARC memory pressure.
5702 *
5703 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5704 * It does this by periodically scanning buffers from the eviction-end of
5705 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3a17a7a9
SK
5706 * not already there. It scans until a headroom of buffers is satisfied,
5707 * which itself is a buffer for ARC eviction. If a compressible buffer is
5708 * found during scanning and selected for writing to an L2ARC device, we
5709 * temporarily boost scanning headroom during the next scan cycle to make
5710 * sure we adapt to compression effects (which might significantly reduce
5711 * the data volume we write to L2ARC). The thread that does this is
34dc7c2f
BB
5712 * l2arc_feed_thread(), illustrated below; example sizes are included to
5713 * provide a better sense of ratio than this diagram:
5714 *
5715 * head --> tail
5716 * +---------------------+----------+
5717 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
5718 * +---------------------+----------+ | o L2ARC eligible
5719 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
5720 * +---------------------+----------+ |
5721 * 15.9 Gbytes ^ 32 Mbytes |
5722 * headroom |
5723 * l2arc_feed_thread()
5724 * |
5725 * l2arc write hand <--[oooo]--'
5726 * | 8 Mbyte
5727 * | write max
5728 * V
5729 * +==============================+
5730 * L2ARC dev |####|#|###|###| |####| ... |
5731 * +==============================+
5732 * 32 Gbytes
5733 *
5734 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5735 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5736 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
5737 * safe to say that this is an uncommon case, since buffers at the end of
5738 * the ARC lists have moved there due to inactivity.
5739 *
5740 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5741 * then the L2ARC simply misses copying some buffers. This serves as a
5742 * pressure valve to prevent heavy read workloads from both stalling the ARC
5743 * with waits and clogging the L2ARC with writes. This also helps prevent
5744 * the potential for the L2ARC to churn if it attempts to cache content too
5745 * quickly, such as during backups of the entire pool.
5746 *
b128c09f
BB
5747 * 5. After system boot and before the ARC has filled main memory, there are
5748 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5749 * lists can remain mostly static. Instead of searching from tail of these
5750 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5751 * for eligible buffers, greatly increasing its chance of finding them.
5752 *
5753 * The L2ARC device write speed is also boosted during this time so that
5754 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
5755 * there are no L2ARC reads, and no fear of degrading read performance
5756 * through increased writes.
5757 *
5758 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
34dc7c2f
BB
5759 * the vdev queue can aggregate them into larger and fewer writes. Each
5760 * device is written to in a rotor fashion, sweeping writes through
5761 * available space then repeating.
5762 *
b128c09f 5763 * 7. The L2ARC does not store dirty content. It never needs to flush
34dc7c2f
BB
5764 * write buffers back to disk based storage.
5765 *
b128c09f 5766 * 8. If an ARC buffer is written (and dirtied) which also exists in the
34dc7c2f
BB
5767 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5768 *
5769 * The performance of the L2ARC can be tweaked by a number of tunables, which
5770 * may be necessary for different workloads:
5771 *
5772 * l2arc_write_max max write bytes per interval
b128c09f 5773 * l2arc_write_boost extra write bytes during device warmup
34dc7c2f 5774 * l2arc_noprefetch skip caching prefetched buffers
3a17a7a9 5775 * l2arc_nocompress skip compressing buffers
34dc7c2f 5776 * l2arc_headroom number of max device writes to precache
3a17a7a9
SK
5777 * l2arc_headroom_boost when we find compressed buffers during ARC
5778 * scanning, we multiply headroom by this
5779 * percentage factor for the next scan cycle,
5780 * since more compressed buffers are likely to
5781 * be present
34dc7c2f
BB
5782 * l2arc_feed_secs seconds between L2ARC writing
5783 *
5784 * Tunables may be removed or added as future performance improvements are
5785 * integrated, and also may become zpool properties.
d164b209
BB
5786 *
5787 * There are three key functions that control how the L2ARC warms up:
5788 *
5789 * l2arc_write_eligible() check if a buffer is eligible to cache
5790 * l2arc_write_size() calculate how much to write
5791 * l2arc_write_interval() calculate sleep delay between writes
5792 *
5793 * These three functions determine what to write, how much, and how quickly
5794 * to send writes.
34dc7c2f
BB
5795 */
5796
d164b209 5797static boolean_t
2a432414 5798l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
d164b209
BB
5799{
5800 /*
5801 * A buffer is *not* eligible for the L2ARC if it:
5802 * 1. belongs to a different spa.
428870ff
BB
5803 * 2. is already cached on the L2ARC.
5804 * 3. has an I/O in progress (it may be an incomplete read).
5805 * 4. is flagged not eligible (zfs property).
d164b209 5806 */
b9541d6b 5807 if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
2a432414 5808 HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
d164b209
BB
5809 return (B_FALSE);
5810
5811 return (B_TRUE);
5812}
5813
5814static uint64_t
3a17a7a9 5815l2arc_write_size(void)
d164b209
BB
5816{
5817 uint64_t size;
5818
3a17a7a9
SK
5819 /*
5820 * Make sure our globals have meaningful values in case the user
5821 * altered them.
5822 */
5823 size = l2arc_write_max;
5824 if (size == 0) {
5825 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5826 "be greater than zero, resetting it to the default (%d)",
5827 L2ARC_WRITE_SIZE);
5828 size = l2arc_write_max = L2ARC_WRITE_SIZE;
5829 }
d164b209
BB
5830
5831 if (arc_warm == B_FALSE)
3a17a7a9 5832 size += l2arc_write_boost;
d164b209
BB
5833
5834 return (size);
5835
5836}
5837
5838static clock_t
5839l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5840{
428870ff 5841 clock_t interval, next, now;
d164b209
BB
5842
5843 /*
5844 * If the ARC lists are busy, increase our write rate; if the
5845 * lists are stale, idle back. This is achieved by checking
5846 * how much we previously wrote - if it was more than half of
5847 * what we wanted, schedule the next write much sooner.
5848 */
5849 if (l2arc_feed_again && wrote > (wanted / 2))
5850 interval = (hz * l2arc_feed_min_ms) / 1000;
5851 else
5852 interval = hz * l2arc_feed_secs;
5853
428870ff
BB
5854 now = ddi_get_lbolt();
5855 next = MAX(now, MIN(now + interval, began + interval));
d164b209
BB
5856
5857 return (next);
5858}
5859
34dc7c2f
BB
5860/*
5861 * Cycle through L2ARC devices. This is how L2ARC load balances.
b128c09f 5862 * If a device is returned, this also returns holding the spa config lock.
34dc7c2f
BB
5863 */
5864static l2arc_dev_t *
5865l2arc_dev_get_next(void)
5866{
b128c09f 5867 l2arc_dev_t *first, *next = NULL;
34dc7c2f 5868
b128c09f
BB
5869 /*
5870 * Lock out the removal of spas (spa_namespace_lock), then removal
5871 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
5872 * both locks will be dropped and a spa config lock held instead.
5873 */
5874 mutex_enter(&spa_namespace_lock);
5875 mutex_enter(&l2arc_dev_mtx);
5876
5877 /* if there are no vdevs, there is nothing to do */
5878 if (l2arc_ndev == 0)
5879 goto out;
5880
5881 first = NULL;
5882 next = l2arc_dev_last;
5883 do {
5884 /* loop around the list looking for a non-faulted vdev */
5885 if (next == NULL) {
34dc7c2f 5886 next = list_head(l2arc_dev_list);
b128c09f
BB
5887 } else {
5888 next = list_next(l2arc_dev_list, next);
5889 if (next == NULL)
5890 next = list_head(l2arc_dev_list);
5891 }
5892
5893 /* if we have come back to the start, bail out */
5894 if (first == NULL)
5895 first = next;
5896 else if (next == first)
5897 break;
5898
5899 } while (vdev_is_dead(next->l2ad_vdev));
5900
5901 /* if we were unable to find any usable vdevs, return NULL */
5902 if (vdev_is_dead(next->l2ad_vdev))
5903 next = NULL;
34dc7c2f
BB
5904
5905 l2arc_dev_last = next;
5906
b128c09f
BB
5907out:
5908 mutex_exit(&l2arc_dev_mtx);
5909
5910 /*
5911 * Grab the config lock to prevent the 'next' device from being
5912 * removed while we are writing to it.
5913 */
5914 if (next != NULL)
5915 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5916 mutex_exit(&spa_namespace_lock);
5917
34dc7c2f
BB
5918 return (next);
5919}
5920
b128c09f
BB
5921/*
5922 * Free buffers that were tagged for destruction.
5923 */
5924static void
0bc8fd78 5925l2arc_do_free_on_write(void)
b128c09f
BB
5926{
5927 list_t *buflist;
5928 l2arc_data_free_t *df, *df_prev;
5929
5930 mutex_enter(&l2arc_free_on_write_mtx);
5931 buflist = l2arc_free_on_write;
5932
5933 for (df = list_tail(buflist); df; df = df_prev) {
5934 df_prev = list_prev(buflist, df);
5935 ASSERT(df->l2df_data != NULL);
5936 ASSERT(df->l2df_func != NULL);
5937 df->l2df_func(df->l2df_data, df->l2df_size);
5938 list_remove(buflist, df);
5939 kmem_free(df, sizeof (l2arc_data_free_t));
5940 }
5941
5942 mutex_exit(&l2arc_free_on_write_mtx);
5943}
5944
34dc7c2f
BB
5945/*
5946 * A write to a cache device has completed. Update all headers to allow
5947 * reads from these buffers to begin.
5948 */
5949static void
5950l2arc_write_done(zio_t *zio)
5951{
5952 l2arc_write_callback_t *cb;
5953 l2arc_dev_t *dev;
5954 list_t *buflist;
2a432414 5955 arc_buf_hdr_t *head, *hdr, *hdr_prev;
34dc7c2f 5956 kmutex_t *hash_lock;
3bec585e 5957 int64_t bytes_dropped = 0;
34dc7c2f
BB
5958
5959 cb = zio->io_private;
5960 ASSERT(cb != NULL);
5961 dev = cb->l2wcb_dev;
5962 ASSERT(dev != NULL);
5963 head = cb->l2wcb_head;
5964 ASSERT(head != NULL);
b9541d6b 5965 buflist = &dev->l2ad_buflist;
34dc7c2f
BB
5966 ASSERT(buflist != NULL);
5967 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5968 l2arc_write_callback_t *, cb);
5969
5970 if (zio->io_error != 0)
5971 ARCSTAT_BUMP(arcstat_l2_writes_error);
5972
34dc7c2f
BB
5973 /*
5974 * All writes completed, or an error was hit.
5975 */
ca0bf58d
PS
5976top:
5977 mutex_enter(&dev->l2ad_mtx);
2a432414
GW
5978 for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5979 hdr_prev = list_prev(buflist, hdr);
34dc7c2f 5980
2a432414 5981 hash_lock = HDR_LOCK(hdr);
ca0bf58d
PS
5982
5983 /*
5984 * We cannot use mutex_enter or else we can deadlock
5985 * with l2arc_write_buffers (due to swapping the order
5986 * the hash lock and l2ad_mtx are taken).
5987 */
34dc7c2f
BB
5988 if (!mutex_tryenter(hash_lock)) {
5989 /*
ca0bf58d
PS
5990 * Missed the hash lock. We must retry so we
5991 * don't leave the ARC_FLAG_L2_WRITING bit set.
34dc7c2f 5992 */
ca0bf58d
PS
5993 ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
5994
5995 /*
5996 * We don't want to rescan the headers we've
5997 * already marked as having been written out, so
5998 * we reinsert the head node so we can pick up
5999 * where we left off.
6000 */
6001 list_remove(buflist, head);
6002 list_insert_after(buflist, hdr, head);
6003
6004 mutex_exit(&dev->l2ad_mtx);
6005
6006 /*
6007 * We wait for the hash lock to become available
6008 * to try and prevent busy waiting, and increase
6009 * the chance we'll be able to acquire the lock
6010 * the next time around.
6011 */
6012 mutex_enter(hash_lock);
6013 mutex_exit(hash_lock);
6014 goto top;
34dc7c2f
BB
6015 }
6016
b9541d6b 6017 /*
ca0bf58d
PS
6018 * We could not have been moved into the arc_l2c_only
6019 * state while in-flight due to our ARC_FLAG_L2_WRITING
6020 * bit being set. Let's just ensure that's being enforced.
6021 */
6022 ASSERT(HDR_HAS_L1HDR(hdr));
6023
6024 /*
6025 * We may have allocated a buffer for L2ARC compression,
6026 * we must release it to avoid leaking this data.
b9541d6b 6027 */
ca0bf58d 6028 l2arc_release_cdata_buf(hdr);
b9541d6b 6029
8a09d5fd
BB
6030 /*
6031 * Skipped - drop L2ARC entry and mark the header as no
6032 * longer L2 eligibile.
6033 */
6034 if (hdr->b_l2hdr.b_daddr == L2ARC_ADDR_UNSET) {
6035 list_remove(buflist, hdr);
6036 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
6037 hdr->b_flags &= ~ARC_FLAG_L2CACHE;
6038
6039 ARCSTAT_BUMP(arcstat_l2_writes_skip_toobig);
6040
6041 (void) refcount_remove_many(&dev->l2ad_alloc,
6042 hdr->b_l2hdr.b_asize, hdr);
6043 } else if (zio->io_error != 0) {
34dc7c2f 6044 /*
b128c09f 6045 * Error - drop L2ARC entry.
34dc7c2f 6046 */
2a432414 6047 list_remove(buflist, hdr);
b9541d6b
CW
6048 hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
6049
6050 ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
2a432414 6051 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
d962d5da
PS
6052
6053 bytes_dropped += hdr->b_l2hdr.b_asize;
6054 (void) refcount_remove_many(&dev->l2ad_alloc,
6055 hdr->b_l2hdr.b_asize, hdr);
34dc7c2f
BB
6056 }
6057
6058 /*
ca0bf58d
PS
6059 * Allow ARC to begin reads and ghost list evictions to
6060 * this L2ARC entry.
34dc7c2f 6061 */
2a432414 6062 hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
34dc7c2f
BB
6063
6064 mutex_exit(hash_lock);
6065 }
6066
6067 atomic_inc_64(&l2arc_writes_done);
6068 list_remove(buflist, head);
b9541d6b
CW
6069 ASSERT(!HDR_HAS_L1HDR(head));
6070 kmem_cache_free(hdr_l2only_cache, head);
6071 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 6072
3bec585e
SK
6073 vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6074
b128c09f 6075 l2arc_do_free_on_write();
34dc7c2f
BB
6076
6077 kmem_free(cb, sizeof (l2arc_write_callback_t));
6078}
6079
6080/*
6081 * A read to a cache device completed. Validate buffer contents before
6082 * handing over to the regular ARC routines.
6083 */
6084static void
6085l2arc_read_done(zio_t *zio)
6086{
6087 l2arc_read_callback_t *cb;
6088 arc_buf_hdr_t *hdr;
6089 arc_buf_t *buf;
34dc7c2f 6090 kmutex_t *hash_lock;
b128c09f
BB
6091 int equal;
6092
6093 ASSERT(zio->io_vd != NULL);
6094 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6095
6096 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
34dc7c2f
BB
6097
6098 cb = zio->io_private;
6099 ASSERT(cb != NULL);
6100 buf = cb->l2rcb_buf;
6101 ASSERT(buf != NULL);
34dc7c2f 6102
428870ff 6103 hash_lock = HDR_LOCK(buf->b_hdr);
34dc7c2f 6104 mutex_enter(hash_lock);
428870ff
BB
6105 hdr = buf->b_hdr;
6106 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
34dc7c2f 6107
3a17a7a9
SK
6108 /*
6109 * If the buffer was compressed, decompress it first.
6110 */
6111 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
6112 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
6113 ASSERT(zio->io_data != NULL);
4e0f33ff
AJ
6114 ASSERT3U(zio->io_size, ==, hdr->b_size);
6115 ASSERT3U(BP_GET_LSIZE(&cb->l2rcb_bp), ==, hdr->b_size);
3a17a7a9 6116
34dc7c2f
BB
6117 /*
6118 * Check this survived the L2ARC journey.
6119 */
6120 equal = arc_cksum_equal(buf);
6121 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6122 mutex_exit(hash_lock);
6123 zio->io_private = buf;
b128c09f
BB
6124 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
6125 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
34dc7c2f
BB
6126 arc_read_done(zio);
6127 } else {
6128 mutex_exit(hash_lock);
6129 /*
6130 * Buffer didn't survive caching. Increment stats and
6131 * reissue to the original storage device.
6132 */
b128c09f 6133 if (zio->io_error != 0) {
34dc7c2f 6134 ARCSTAT_BUMP(arcstat_l2_io_error);
b128c09f 6135 } else {
2e528b49 6136 zio->io_error = SET_ERROR(EIO);
b128c09f 6137 }
34dc7c2f
BB
6138 if (!equal)
6139 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6140
34dc7c2f 6141 /*
b128c09f
BB
6142 * If there's no waiter, issue an async i/o to the primary
6143 * storage now. If there *is* a waiter, the caller must
6144 * issue the i/o in a context where it's OK to block.
34dc7c2f 6145 */
d164b209
BB
6146 if (zio->io_waiter == NULL) {
6147 zio_t *pio = zio_unique_parent(zio);
6148
6149 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6150
6151 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4e0f33ff 6152 buf->b_data, hdr->b_size, arc_read_done, buf,
b128c09f 6153 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
d164b209 6154 }
34dc7c2f
BB
6155 }
6156
6157 kmem_free(cb, sizeof (l2arc_read_callback_t));
6158}
6159
6160/*
6161 * This is the list priority from which the L2ARC will search for pages to
6162 * cache. This is used within loops (0..3) to cycle through lists in the
6163 * desired order. This order can have a significant effect on cache
6164 * performance.
6165 *
6166 * Currently the metadata lists are hit first, MFU then MRU, followed by
6167 * the data lists. This function returns a locked list, and also returns
6168 * the lock pointer.
6169 */
ca0bf58d
PS
6170static multilist_sublist_t *
6171l2arc_sublist_lock(int list_num)
34dc7c2f 6172{
ca0bf58d
PS
6173 multilist_t *ml = NULL;
6174 unsigned int idx;
34dc7c2f
BB
6175
6176 ASSERT(list_num >= 0 && list_num <= 3);
6177
6178 switch (list_num) {
6179 case 0:
ca0bf58d 6180 ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
34dc7c2f
BB
6181 break;
6182 case 1:
ca0bf58d 6183 ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
34dc7c2f
BB
6184 break;
6185 case 2:
ca0bf58d 6186 ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
34dc7c2f
BB
6187 break;
6188 case 3:
ca0bf58d 6189 ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
34dc7c2f
BB
6190 break;
6191 }
6192
ca0bf58d
PS
6193 /*
6194 * Return a randomly-selected sublist. This is acceptable
6195 * because the caller feeds only a little bit of data for each
6196 * call (8MB). Subsequent calls will result in different
6197 * sublists being selected.
6198 */
6199 idx = multilist_get_random_index(ml);
6200 return (multilist_sublist_lock(ml, idx));
34dc7c2f
BB
6201}
6202
6203/*
6204 * Evict buffers from the device write hand to the distance specified in
6205 * bytes. This distance may span populated buffers, it may span nothing.
6206 * This is clearing a region on the L2ARC device ready for writing.
6207 * If the 'all' boolean is set, every buffer is evicted.
6208 */
6209static void
6210l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6211{
6212 list_t *buflist;
2a432414 6213 arc_buf_hdr_t *hdr, *hdr_prev;
34dc7c2f
BB
6214 kmutex_t *hash_lock;
6215 uint64_t taddr;
6216
b9541d6b 6217 buflist = &dev->l2ad_buflist;
34dc7c2f
BB
6218
6219 if (!all && dev->l2ad_first) {
6220 /*
6221 * This is the first sweep through the device. There is
6222 * nothing to evict.
6223 */
6224 return;
6225 }
6226
b128c09f 6227 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
34dc7c2f
BB
6228 /*
6229 * When nearing the end of the device, evict to the end
6230 * before the device write hand jumps to the start.
6231 */
6232 taddr = dev->l2ad_end;
6233 } else {
6234 taddr = dev->l2ad_hand + distance;
6235 }
6236 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6237 uint64_t, taddr, boolean_t, all);
6238
6239top:
b9541d6b 6240 mutex_enter(&dev->l2ad_mtx);
2a432414
GW
6241 for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6242 hdr_prev = list_prev(buflist, hdr);
34dc7c2f 6243
2a432414 6244 hash_lock = HDR_LOCK(hdr);
ca0bf58d
PS
6245
6246 /*
6247 * We cannot use mutex_enter or else we can deadlock
6248 * with l2arc_write_buffers (due to swapping the order
6249 * the hash lock and l2ad_mtx are taken).
6250 */
34dc7c2f
BB
6251 if (!mutex_tryenter(hash_lock)) {
6252 /*
6253 * Missed the hash lock. Retry.
6254 */
6255 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
b9541d6b 6256 mutex_exit(&dev->l2ad_mtx);
34dc7c2f
BB
6257 mutex_enter(hash_lock);
6258 mutex_exit(hash_lock);
6259 goto top;
6260 }
6261
2a432414 6262 if (HDR_L2_WRITE_HEAD(hdr)) {
34dc7c2f
BB
6263 /*
6264 * We hit a write head node. Leave it for
6265 * l2arc_write_done().
6266 */
2a432414 6267 list_remove(buflist, hdr);
34dc7c2f
BB
6268 mutex_exit(hash_lock);
6269 continue;
6270 }
6271
b9541d6b
CW
6272 if (!all && HDR_HAS_L2HDR(hdr) &&
6273 (hdr->b_l2hdr.b_daddr > taddr ||
6274 hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
34dc7c2f
BB
6275 /*
6276 * We've evicted to the target address,
6277 * or the end of the device.
6278 */
6279 mutex_exit(hash_lock);
6280 break;
6281 }
6282
b9541d6b
CW
6283 ASSERT(HDR_HAS_L2HDR(hdr));
6284 if (!HDR_HAS_L1HDR(hdr)) {
2a432414 6285 ASSERT(!HDR_L2_READING(hdr));
34dc7c2f
BB
6286 /*
6287 * This doesn't exist in the ARC. Destroy.
6288 * arc_hdr_destroy() will call list_remove()
6289 * and decrement arcstat_l2_size.
6290 */
2a432414
GW
6291 arc_change_state(arc_anon, hdr, hash_lock);
6292 arc_hdr_destroy(hdr);
34dc7c2f 6293 } else {
b9541d6b
CW
6294 ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6295 ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
b128c09f
BB
6296 /*
6297 * Invalidate issued or about to be issued
6298 * reads, since we may be about to write
6299 * over this location.
6300 */
2a432414 6301 if (HDR_L2_READING(hdr)) {
b128c09f 6302 ARCSTAT_BUMP(arcstat_l2_evict_reading);
2a432414 6303 hdr->b_flags |= ARC_FLAG_L2_EVICTED;
b128c09f
BB
6304 }
6305
ca0bf58d
PS
6306 /* Ensure this header has finished being written */
6307 ASSERT(!HDR_L2_WRITING(hdr));
6308 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
d962d5da
PS
6309
6310 arc_hdr_l2hdr_destroy(hdr);
34dc7c2f
BB
6311 }
6312 mutex_exit(hash_lock);
6313 }
b9541d6b 6314 mutex_exit(&dev->l2ad_mtx);
34dc7c2f
BB
6315}
6316
6317/*
6318 * Find and write ARC buffers to the L2ARC device.
6319 *
2a432414 6320 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
34dc7c2f 6321 * for reading until they have completed writing.
3a17a7a9
SK
6322 * The headroom_boost is an in-out parameter used to maintain headroom boost
6323 * state between calls to this function.
6324 *
6325 * Returns the number of bytes actually written (which may be smaller than
6326 * the delta by which the device hand has changed due to alignment).
34dc7c2f 6327 */
d164b209 6328static uint64_t
3a17a7a9
SK
6329l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
6330 boolean_t *headroom_boost)
34dc7c2f 6331{
2a432414 6332 arc_buf_hdr_t *hdr, *hdr_prev, *head;
ef56b078
AG
6333 uint64_t write_asize, write_sz, headroom, buf_compress_minsz,
6334 stats_size;
34dc7c2f 6335 void *buf_data;
3a17a7a9 6336 boolean_t full;
34dc7c2f
BB
6337 l2arc_write_callback_t *cb;
6338 zio_t *pio, *wzio;
3541dc6d 6339 uint64_t guid = spa_load_guid(spa);
d6320ddb 6340 int try;
3a17a7a9 6341 const boolean_t do_headroom_boost = *headroom_boost;
34dc7c2f 6342
34dc7c2f
BB
6343 ASSERT(dev->l2ad_vdev != NULL);
6344
3a17a7a9
SK
6345 /* Lower the flag now, we might want to raise it again later. */
6346 *headroom_boost = B_FALSE;
6347
34dc7c2f 6348 pio = NULL;
ef56b078 6349 write_sz = write_asize = 0;
34dc7c2f 6350 full = B_FALSE;
b9541d6b 6351 head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
2a432414 6352 head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
b9541d6b 6353 head->b_flags |= ARC_FLAG_HAS_L2HDR;
34dc7c2f 6354
3a17a7a9
SK
6355 /*
6356 * We will want to try to compress buffers that are at least 2x the
6357 * device sector size.
6358 */
6359 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
6360
34dc7c2f
BB
6361 /*
6362 * Copy buffers for L2ARC writing.
6363 */
d6320ddb 6364 for (try = 0; try <= 3; try++) {
ca0bf58d 6365 multilist_sublist_t *mls = l2arc_sublist_lock(try);
3a17a7a9
SK
6366 uint64_t passed_sz = 0;
6367
b128c09f
BB
6368 /*
6369 * L2ARC fast warmup.
6370 *
6371 * Until the ARC is warm and starts to evict, read from the
6372 * head of the ARC lists rather than the tail.
6373 */
b128c09f 6374 if (arc_warm == B_FALSE)
ca0bf58d 6375 hdr = multilist_sublist_head(mls);
b128c09f 6376 else
ca0bf58d 6377 hdr = multilist_sublist_tail(mls);
b128c09f 6378
3a17a7a9
SK
6379 headroom = target_sz * l2arc_headroom;
6380 if (do_headroom_boost)
6381 headroom = (headroom * l2arc_headroom_boost) / 100;
6382
2a432414 6383 for (; hdr; hdr = hdr_prev) {
3a17a7a9
SK
6384 kmutex_t *hash_lock;
6385 uint64_t buf_sz;
ef56b078 6386 uint64_t buf_a_sz;
3a17a7a9 6387
b128c09f 6388 if (arc_warm == B_FALSE)
ca0bf58d 6389 hdr_prev = multilist_sublist_next(mls, hdr);
b128c09f 6390 else
ca0bf58d 6391 hdr_prev = multilist_sublist_prev(mls, hdr);
34dc7c2f 6392
2a432414 6393 hash_lock = HDR_LOCK(hdr);
3a17a7a9 6394 if (!mutex_tryenter(hash_lock)) {
34dc7c2f
BB
6395 /*
6396 * Skip this buffer rather than waiting.
6397 */
6398 continue;
6399 }
6400
2a432414 6401 passed_sz += hdr->b_size;
34dc7c2f
BB
6402 if (passed_sz > headroom) {
6403 /*
6404 * Searched too far.
6405 */
6406 mutex_exit(hash_lock);
6407 break;
6408 }
6409
2a432414 6410 if (!l2arc_write_eligible(guid, hdr)) {
34dc7c2f
BB
6411 mutex_exit(hash_lock);
6412 continue;
6413 }
6414
ef56b078
AG
6415 /*
6416 * Assume that the buffer is not going to be compressed
6417 * and could take more space on disk because of a larger
6418 * disk block size.
6419 */
6420 buf_sz = hdr->b_size;
6421 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6422
6423 if ((write_asize + buf_a_sz) > target_sz) {
34dc7c2f
BB
6424 full = B_TRUE;
6425 mutex_exit(hash_lock);
6426 break;
6427 }
6428
34dc7c2f
BB
6429 if (pio == NULL) {
6430 /*
6431 * Insert a dummy header on the buflist so
6432 * l2arc_write_done() can find where the
6433 * write buffers begin without searching.
6434 */
ca0bf58d 6435 mutex_enter(&dev->l2ad_mtx);
b9541d6b 6436 list_insert_head(&dev->l2ad_buflist, head);
ca0bf58d 6437 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 6438
96c080cb
BB
6439 cb = kmem_alloc(
6440 sizeof (l2arc_write_callback_t), KM_SLEEP);
34dc7c2f
BB
6441 cb->l2wcb_dev = dev;
6442 cb->l2wcb_head = head;
6443 pio = zio_root(spa, l2arc_write_done, cb,
6444 ZIO_FLAG_CANFAIL);
6445 }
6446
6447 /*
6448 * Create and add a new L2ARC header.
6449 */
b9541d6b 6450 hdr->b_l2hdr.b_dev = dev;
2a432414 6451 hdr->b_flags |= ARC_FLAG_L2_WRITING;
3a17a7a9
SK
6452 /*
6453 * Temporarily stash the data buffer in b_tmp_cdata.
6454 * The subsequent write step will pick it up from
b9541d6b 6455 * there. This is because can't access b_l1hdr.b_buf
3a17a7a9
SK
6456 * without holding the hash_lock, which we in turn
6457 * can't access without holding the ARC list locks
6458 * (which we want to avoid during compression/writing)
6459 */
4e0f33ff 6460 hdr->b_l2hdr.b_compress = ZIO_COMPRESS_OFF;
b9541d6b
CW
6461 hdr->b_l2hdr.b_asize = hdr->b_size;
6462 hdr->b_l2hdr.b_hits = 0;
6463 hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
3a17a7a9 6464
d962d5da
PS
6465 /*
6466 * Explicitly set the b_daddr field to a known
6467 * value which means "invalid address". This
6468 * enables us to differentiate which stage of
6469 * l2arc_write_buffers() the particular header
6470 * is in (e.g. this loop, or the one below).
6471 * ARC_FLAG_L2_WRITING is not enough to make
6472 * this distinction, and we need to know in
6473 * order to do proper l2arc vdev accounting in
6474 * arc_release() and arc_hdr_destroy().
6475 *
6476 * Note, we can't use a new flag to distinguish
6477 * the two stages because we don't hold the
6478 * header's hash_lock below, in the second stage
6479 * of this function. Thus, we can't simply
6480 * change the b_flags field to denote that the
6481 * IO has been sent. We can change the b_daddr
6482 * field of the L2 portion, though, since we'll
6483 * be holding the l2ad_mtx; which is why we're
6484 * using it to denote the header's state change.
6485 */
6486 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
b9541d6b 6487 hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
3a17a7a9 6488
ca0bf58d 6489 mutex_enter(&dev->l2ad_mtx);
b9541d6b 6490 list_insert_head(&dev->l2ad_buflist, hdr);
ca0bf58d 6491 mutex_exit(&dev->l2ad_mtx);
34dc7c2f
BB
6492
6493 /*
6494 * Compute and store the buffer cksum before
6495 * writing. On debug the cksum is verified first.
6496 */
b9541d6b
CW
6497 arc_cksum_verify(hdr->b_l1hdr.b_buf);
6498 arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
34dc7c2f
BB
6499
6500 mutex_exit(hash_lock);
6501
3a17a7a9 6502 write_sz += buf_sz;
ef56b078 6503 write_asize += buf_a_sz;
3a17a7a9
SK
6504 }
6505
ca0bf58d 6506 multilist_sublist_unlock(mls);
3a17a7a9
SK
6507
6508 if (full == B_TRUE)
6509 break;
6510 }
6511
6512 /* No buffers selected for writing? */
6513 if (pio == NULL) {
6514 ASSERT0(write_sz);
b9541d6b
CW
6515 ASSERT(!HDR_HAS_L1HDR(head));
6516 kmem_cache_free(hdr_l2only_cache, head);
3a17a7a9
SK
6517 return (0);
6518 }
6519
ca0bf58d
PS
6520 mutex_enter(&dev->l2ad_mtx);
6521
ef56b078
AG
6522 /*
6523 * Note that elsewhere in this file arcstat_l2_asize
6524 * and the used space on l2ad_vdev are updated using b_asize,
6525 * which is not necessarily rounded up to the device block size.
6526 * Too keep accounting consistent we do the same here as well:
6527 * stats_size accumulates the sum of b_asize of the written buffers,
6528 * while write_asize accumulates the sum of b_asize rounded up
6529 * to the device block size.
6530 * The latter sum is used only to validate the corectness of the code.
6531 */
6532 stats_size = 0;
6533 write_asize = 0;
6534
3a17a7a9
SK
6535 /*
6536 * Now start writing the buffers. We're starting at the write head
6537 * and work backwards, retracing the course of the buffer selector
6538 * loop above.
6539 */
b9541d6b
CW
6540 for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
6541 hdr = list_prev(&dev->l2ad_buflist, hdr)) {
3a17a7a9
SK
6542 uint64_t buf_sz;
6543
ca0bf58d
PS
6544 /*
6545 * We rely on the L1 portion of the header below, so
6546 * it's invalid for this header to have been evicted out
6547 * of the ghost cache, prior to being written out. The
6548 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
6549 */
6550 ASSERT(HDR_HAS_L1HDR(hdr));
6551
3a17a7a9
SK
6552 /*
6553 * We shouldn't need to lock the buffer here, since we flagged
2a432414
GW
6554 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
6555 * take care to only access its L2 cache parameters. In
b9541d6b 6556 * particular, hdr->l1hdr.b_buf may be invalid by now due to
2a432414 6557 * ARC eviction.
3a17a7a9 6558 */
b9541d6b 6559 hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
3a17a7a9 6560
b9541d6b
CW
6561 if ((!l2arc_nocompress && HDR_L2COMPRESS(hdr)) &&
6562 hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
6563 if (l2arc_compress_buf(hdr)) {
3a17a7a9
SK
6564 /*
6565 * If compression succeeded, enable headroom
6566 * boost on the next scan cycle.
6567 */
6568 *headroom_boost = B_TRUE;
6569 }
6570 }
6571
6572 /*
6573 * Pick up the buffer data we had previously stashed away
6574 * (and now potentially also compressed).
6575 */
b9541d6b
CW
6576 buf_data = hdr->b_l1hdr.b_tmp_cdata;
6577 buf_sz = hdr->b_l2hdr.b_asize;
3a17a7a9 6578
d962d5da
PS
6579 /*
6580 * We need to do this regardless if buf_sz is zero or
6581 * not, otherwise, when this l2hdr is evicted we'll
6582 * remove a reference that was never added.
6583 */
6584 (void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
6585
3a17a7a9
SK
6586 /* Compression may have squashed the buffer to zero length. */
6587 if (buf_sz != 0) {
ef56b078 6588 uint64_t buf_a_sz;
3a17a7a9 6589
8a09d5fd
BB
6590 /*
6591 * Buffers which are larger than l2arc_max_block_size
6592 * after compression are skipped and removed from L2
6593 * eligibility.
6594 */
6595 if (buf_sz > l2arc_max_block_size) {
6596 hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
6597 continue;
6598 }
6599
34dc7c2f
BB
6600 wzio = zio_write_phys(pio, dev->l2ad_vdev,
6601 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6602 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6603 ZIO_FLAG_CANFAIL, B_FALSE);
6604
6605 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6606 zio_t *, wzio);
6607 (void) zio_nowait(wzio);
6608
ef56b078 6609 stats_size += buf_sz;
d962d5da 6610
b128c09f
BB
6611 /*
6612 * Keep the clock hand suitably device-aligned.
6613 */
ef56b078
AG
6614 buf_a_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6615 write_asize += buf_a_sz;
6616 dev->l2ad_hand += buf_a_sz;
34dc7c2f 6617 }
34dc7c2f 6618 }
34dc7c2f 6619
b9541d6b 6620 mutex_exit(&dev->l2ad_mtx);
34dc7c2f 6621
3a17a7a9 6622 ASSERT3U(write_asize, <=, target_sz);
34dc7c2f 6623 ARCSTAT_BUMP(arcstat_l2_writes_sent);
3a17a7a9 6624 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
34dc7c2f 6625 ARCSTAT_INCR(arcstat_l2_size, write_sz);
ef56b078
AG
6626 ARCSTAT_INCR(arcstat_l2_asize, stats_size);
6627 vdev_space_update(dev->l2ad_vdev, stats_size, 0, 0);
34dc7c2f
BB
6628
6629 /*
6630 * Bump device hand to the device start if it is approaching the end.
6631 * l2arc_evict() will already have evicted ahead for this case.
6632 */
b128c09f 6633 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
34dc7c2f 6634 dev->l2ad_hand = dev->l2ad_start;
34dc7c2f
BB
6635 dev->l2ad_first = B_FALSE;
6636 }
6637
d164b209 6638 dev->l2ad_writing = B_TRUE;
34dc7c2f 6639 (void) zio_wait(pio);
d164b209
BB
6640 dev->l2ad_writing = B_FALSE;
6641
3a17a7a9
SK
6642 return (write_asize);
6643}
6644
6645/*
6646 * Compresses an L2ARC buffer.
b9541d6b 6647 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
3a17a7a9
SK
6648 * size in l2hdr->b_asize. This routine tries to compress the data and
6649 * depending on the compression result there are three possible outcomes:
6650 * *) The buffer was incompressible. The original l2hdr contents were left
6651 * untouched and are ready for writing to an L2 device.
6652 * *) The buffer was all-zeros, so there is no need to write it to an L2
6653 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6654 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6655 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6656 * data buffer which holds the compressed data to be written, and b_asize
6657 * tells us how much data there is. b_compress is set to the appropriate
6658 * compression algorithm. Once writing is done, invoke
6659 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6660 *
6661 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6662 * buffer was incompressible).
6663 */
6664static boolean_t
b9541d6b 6665l2arc_compress_buf(arc_buf_hdr_t *hdr)
3a17a7a9
SK
6666{
6667 void *cdata;
9b67f605 6668 size_t csize, len, rounded;
b9541d6b 6669 l2arc_buf_hdr_t *l2hdr;
3a17a7a9 6670
b9541d6b
CW
6671 ASSERT(HDR_HAS_L2HDR(hdr));
6672
6673 l2hdr = &hdr->b_l2hdr;
6674
6675 ASSERT(HDR_HAS_L1HDR(hdr));
4e0f33ff 6676 ASSERT3U(l2hdr->b_compress, ==, ZIO_COMPRESS_OFF);
b9541d6b 6677 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
3a17a7a9
SK
6678
6679 len = l2hdr->b_asize;
6680 cdata = zio_data_buf_alloc(len);
b9541d6b
CW
6681 ASSERT3P(cdata, !=, NULL);
6682 csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
3a17a7a9
SK
6683 cdata, l2hdr->b_asize);
6684
9b67f605
MA
6685 rounded = P2ROUNDUP(csize, (size_t)SPA_MINBLOCKSIZE);
6686 if (rounded > csize) {
6687 bzero((char *)cdata + csize, rounded - csize);
6688 csize = rounded;
6689 }
6690
3a17a7a9
SK
6691 if (csize == 0) {
6692 /* zero block, indicate that there's nothing to write */
6693 zio_data_buf_free(cdata, len);
4e0f33ff 6694 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
3a17a7a9 6695 l2hdr->b_asize = 0;
b9541d6b 6696 hdr->b_l1hdr.b_tmp_cdata = NULL;
3a17a7a9
SK
6697 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6698 return (B_TRUE);
6699 } else if (csize > 0 && csize < len) {
6700 /*
6701 * Compression succeeded, we'll keep the cdata around for
6702 * writing and release it afterwards.
6703 */
4e0f33ff 6704 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
3a17a7a9 6705 l2hdr->b_asize = csize;
b9541d6b 6706 hdr->b_l1hdr.b_tmp_cdata = cdata;
3a17a7a9
SK
6707 ARCSTAT_BUMP(arcstat_l2_compress_successes);
6708 return (B_TRUE);
6709 } else {
6710 /*
6711 * Compression failed, release the compressed buffer.
6712 * l2hdr will be left unmodified.
6713 */
6714 zio_data_buf_free(cdata, len);
6715 ARCSTAT_BUMP(arcstat_l2_compress_failures);
6716 return (B_FALSE);
6717 }
6718}
6719
6720/*
6721 * Decompresses a zio read back from an l2arc device. On success, the
6722 * underlying zio's io_data buffer is overwritten by the uncompressed
6723 * version. On decompression error (corrupt compressed stream), the
6724 * zio->io_error value is set to signal an I/O error.
6725 *
6726 * Please note that the compressed data stream is not checksummed, so
6727 * if the underlying device is experiencing data corruption, we may feed
6728 * corrupt data to the decompressor, so the decompressor needs to be
6729 * able to handle this situation (LZ4 does).
6730 */
6731static void
6732l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6733{
6734 uint64_t csize;
6735 void *cdata;
6736
6737 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6738
6739 if (zio->io_error != 0) {
6740 /*
6741 * An io error has occured, just restore the original io
6742 * size in preparation for a main pool read.
6743 */
6744 zio->io_orig_size = zio->io_size = hdr->b_size;
6745 return;
6746 }
6747
6748 if (c == ZIO_COMPRESS_EMPTY) {
6749 /*
6750 * An empty buffer results in a null zio, which means we
6751 * need to fill its io_data after we're done restoring the
6752 * buffer's contents.
6753 */
b9541d6b
CW
6754 ASSERT(hdr->b_l1hdr.b_buf != NULL);
6755 bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6756 zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
3a17a7a9
SK
6757 } else {
6758 ASSERT(zio->io_data != NULL);
6759 /*
6760 * We copy the compressed data from the start of the arc buffer
6761 * (the zio_read will have pulled in only what we need, the
6762 * rest is garbage which we will overwrite at decompression)
6763 * and then decompress back to the ARC data buffer. This way we
6764 * can minimize copying by simply decompressing back over the
6765 * original compressed data (rather than decompressing to an
6766 * aux buffer and then copying back the uncompressed buffer,
6767 * which is likely to be much larger).
6768 */
6769 csize = zio->io_size;
6770 cdata = zio_data_buf_alloc(csize);
6771 bcopy(zio->io_data, cdata, csize);
6772 if (zio_decompress_data(c, cdata, zio->io_data, csize,
6773 hdr->b_size) != 0)
96c080cb 6774 zio->io_error = EIO;
3a17a7a9
SK
6775 zio_data_buf_free(cdata, csize);
6776 }
6777
6778 /* Restore the expected uncompressed IO size. */
6779 zio->io_orig_size = zio->io_size = hdr->b_size;
6780}
6781
6782/*
6783 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6784 * This buffer serves as a temporary holder of compressed data while
6785 * the buffer entry is being written to an l2arc device. Once that is
6786 * done, we can dispose of it.
6787 */
6788static void
2a432414 6789l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
3a17a7a9 6790{
4e0f33ff 6791 enum zio_compress comp;
ca0bf58d 6792
b9541d6b 6793 ASSERT(HDR_HAS_L1HDR(hdr));
4e0f33ff
AJ
6794 ASSERT(HDR_HAS_L2HDR(hdr));
6795 comp = hdr->b_l2hdr.b_compress;
ca0bf58d
PS
6796 ASSERT(comp == ZIO_COMPRESS_OFF || L2ARC_IS_VALID_COMPRESS(comp));
6797
6798 if (comp == ZIO_COMPRESS_OFF) {
6799 /*
6800 * In this case, b_tmp_cdata points to the same buffer
6801 * as the arc_buf_t's b_data field. We don't want to
6802 * free it, since the arc_buf_t will handle that.
6803 */
6804 hdr->b_l1hdr.b_tmp_cdata = NULL;
6805 } else if (comp == ZIO_COMPRESS_EMPTY) {
6806 /*
6807 * In this case, b_tmp_cdata was compressed to an empty
6808 * buffer, thus there's nothing to free and b_tmp_cdata
6809 * should have been set to NULL in l2arc_write_buffers().
6810 */
6811 ASSERT3P(hdr->b_l1hdr.b_tmp_cdata, ==, NULL);
6812 } else {
3a17a7a9
SK
6813 /*
6814 * If the data was compressed, then we've allocated a
6815 * temporary buffer for it, so now we need to release it.
6816 */
b9541d6b
CW
6817 ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6818 zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6819 hdr->b_size);
ca0bf58d 6820 hdr->b_l1hdr.b_tmp_cdata = NULL;
3a17a7a9 6821 }
ca0bf58d 6822
34dc7c2f
BB
6823}
6824
6825/*
6826 * This thread feeds the L2ARC at regular intervals. This is the beating
6827 * heart of the L2ARC.
6828 */
6829static void
6830l2arc_feed_thread(void)
6831{
6832 callb_cpr_t cpr;
6833 l2arc_dev_t *dev;
6834 spa_t *spa;
d164b209 6835 uint64_t size, wrote;
428870ff 6836 clock_t begin, next = ddi_get_lbolt();
3a17a7a9 6837 boolean_t headroom_boost = B_FALSE;
40d06e3c 6838 fstrans_cookie_t cookie;
34dc7c2f
BB
6839
6840 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6841
6842 mutex_enter(&l2arc_feed_thr_lock);
6843
40d06e3c 6844 cookie = spl_fstrans_mark();
34dc7c2f 6845 while (l2arc_thread_exit == 0) {
34dc7c2f 6846 CALLB_CPR_SAFE_BEGIN(&cpr);
b64ccd6c 6847 (void) cv_timedwait_sig(&l2arc_feed_thr_cv,
5b63b3eb 6848 &l2arc_feed_thr_lock, next);
34dc7c2f 6849 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
428870ff 6850 next = ddi_get_lbolt() + hz;
34dc7c2f
BB
6851
6852 /*
b128c09f 6853 * Quick check for L2ARC devices.
34dc7c2f
BB
6854 */
6855 mutex_enter(&l2arc_dev_mtx);
6856 if (l2arc_ndev == 0) {
6857 mutex_exit(&l2arc_dev_mtx);
6858 continue;
6859 }
b128c09f 6860 mutex_exit(&l2arc_dev_mtx);
428870ff 6861 begin = ddi_get_lbolt();
34dc7c2f
BB
6862
6863 /*
b128c09f
BB
6864 * This selects the next l2arc device to write to, and in
6865 * doing so the next spa to feed from: dev->l2ad_spa. This
6866 * will return NULL if there are now no l2arc devices or if
6867 * they are all faulted.
6868 *
6869 * If a device is returned, its spa's config lock is also
6870 * held to prevent device removal. l2arc_dev_get_next()
6871 * will grab and release l2arc_dev_mtx.
34dc7c2f 6872 */
b128c09f 6873 if ((dev = l2arc_dev_get_next()) == NULL)
34dc7c2f 6874 continue;
b128c09f
BB
6875
6876 spa = dev->l2ad_spa;
6877 ASSERT(spa != NULL);
34dc7c2f 6878
572e2857
BB
6879 /*
6880 * If the pool is read-only then force the feed thread to
6881 * sleep a little longer.
6882 */
6883 if (!spa_writeable(spa)) {
6884 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6885 spa_config_exit(spa, SCL_L2ARC, dev);
6886 continue;
6887 }
6888
34dc7c2f 6889 /*
b128c09f 6890 * Avoid contributing to memory pressure.
34dc7c2f 6891 */
ca67b33a 6892 if (arc_reclaim_needed()) {
b128c09f
BB
6893 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6894 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f
BB
6895 continue;
6896 }
b128c09f 6897
34dc7c2f
BB
6898 ARCSTAT_BUMP(arcstat_l2_feeds);
6899
3a17a7a9 6900 size = l2arc_write_size();
b128c09f 6901
34dc7c2f
BB
6902 /*
6903 * Evict L2ARC buffers that will be overwritten.
6904 */
b128c09f 6905 l2arc_evict(dev, size, B_FALSE);
34dc7c2f
BB
6906
6907 /*
6908 * Write ARC buffers.
6909 */
3a17a7a9 6910 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
d164b209
BB
6911
6912 /*
6913 * Calculate interval between writes.
6914 */
6915 next = l2arc_write_interval(begin, size, wrote);
b128c09f 6916 spa_config_exit(spa, SCL_L2ARC, dev);
34dc7c2f 6917 }
40d06e3c 6918 spl_fstrans_unmark(cookie);
34dc7c2f
BB
6919
6920 l2arc_thread_exit = 0;
6921 cv_broadcast(&l2arc_feed_thr_cv);
6922 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
6923 thread_exit();
6924}
6925
b128c09f
BB
6926boolean_t
6927l2arc_vdev_present(vdev_t *vd)
6928{
6929 l2arc_dev_t *dev;
6930
6931 mutex_enter(&l2arc_dev_mtx);
6932 for (dev = list_head(l2arc_dev_list); dev != NULL;
6933 dev = list_next(l2arc_dev_list, dev)) {
6934 if (dev->l2ad_vdev == vd)
6935 break;
6936 }
6937 mutex_exit(&l2arc_dev_mtx);
6938
6939 return (dev != NULL);
6940}
6941
34dc7c2f
BB
6942/*
6943 * Add a vdev for use by the L2ARC. By this point the spa has already
6944 * validated the vdev and opened it.
6945 */
6946void
9babb374 6947l2arc_add_vdev(spa_t *spa, vdev_t *vd)
34dc7c2f
BB
6948{
6949 l2arc_dev_t *adddev;
6950
b128c09f
BB
6951 ASSERT(!l2arc_vdev_present(vd));
6952
34dc7c2f
BB
6953 /*
6954 * Create a new l2arc device entry.
6955 */
6956 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6957 adddev->l2ad_spa = spa;
6958 adddev->l2ad_vdev = vd;
9babb374
BB
6959 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6960 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
34dc7c2f 6961 adddev->l2ad_hand = adddev->l2ad_start;
34dc7c2f 6962 adddev->l2ad_first = B_TRUE;
d164b209 6963 adddev->l2ad_writing = B_FALSE;
98f72a53 6964 list_link_init(&adddev->l2ad_node);
34dc7c2f 6965
b9541d6b 6966 mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
6967 /*
6968 * This is a list of all ARC buffers that are still valid on the
6969 * device.
6970 */
b9541d6b
CW
6971 list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6972 offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
34dc7c2f 6973
428870ff 6974 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
d962d5da 6975 refcount_create(&adddev->l2ad_alloc);
34dc7c2f
BB
6976
6977 /*
6978 * Add device to global list
6979 */
6980 mutex_enter(&l2arc_dev_mtx);
6981 list_insert_head(l2arc_dev_list, adddev);
6982 atomic_inc_64(&l2arc_ndev);
6983 mutex_exit(&l2arc_dev_mtx);
6984}
6985
6986/*
6987 * Remove a vdev from the L2ARC.
6988 */
6989void
6990l2arc_remove_vdev(vdev_t *vd)
6991{
6992 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6993
34dc7c2f
BB
6994 /*
6995 * Find the device by vdev
6996 */
6997 mutex_enter(&l2arc_dev_mtx);
6998 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6999 nextdev = list_next(l2arc_dev_list, dev);
7000 if (vd == dev->l2ad_vdev) {
7001 remdev = dev;
7002 break;
7003 }
7004 }
7005 ASSERT(remdev != NULL);
7006
7007 /*
7008 * Remove device from global list
7009 */
7010 list_remove(l2arc_dev_list, remdev);
7011 l2arc_dev_last = NULL; /* may have been invalidated */
b128c09f
BB
7012 atomic_dec_64(&l2arc_ndev);
7013 mutex_exit(&l2arc_dev_mtx);
34dc7c2f
BB
7014
7015 /*
7016 * Clear all buflists and ARC references. L2ARC device flush.
7017 */
7018 l2arc_evict(remdev, 0, B_TRUE);
b9541d6b
CW
7019 list_destroy(&remdev->l2ad_buflist);
7020 mutex_destroy(&remdev->l2ad_mtx);
d962d5da 7021 refcount_destroy(&remdev->l2ad_alloc);
34dc7c2f 7022 kmem_free(remdev, sizeof (l2arc_dev_t));
34dc7c2f
BB
7023}
7024
7025void
b128c09f 7026l2arc_init(void)
34dc7c2f
BB
7027{
7028 l2arc_thread_exit = 0;
7029 l2arc_ndev = 0;
7030 l2arc_writes_sent = 0;
7031 l2arc_writes_done = 0;
7032
7033 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7034 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7035 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
34dc7c2f
BB
7036 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7037
7038 l2arc_dev_list = &L2ARC_dev_list;
7039 l2arc_free_on_write = &L2ARC_free_on_write;
7040 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7041 offsetof(l2arc_dev_t, l2ad_node));
7042 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7043 offsetof(l2arc_data_free_t, l2df_list_node));
34dc7c2f
BB
7044}
7045
7046void
b128c09f 7047l2arc_fini(void)
34dc7c2f 7048{
b128c09f
BB
7049 /*
7050 * This is called from dmu_fini(), which is called from spa_fini();
7051 * Because of this, we can assume that all l2arc devices have
7052 * already been removed when the pools themselves were removed.
7053 */
7054
7055 l2arc_do_free_on_write();
34dc7c2f
BB
7056
7057 mutex_destroy(&l2arc_feed_thr_lock);
7058 cv_destroy(&l2arc_feed_thr_cv);
7059 mutex_destroy(&l2arc_dev_mtx);
34dc7c2f
BB
7060 mutex_destroy(&l2arc_free_on_write_mtx);
7061
7062 list_destroy(l2arc_dev_list);
7063 list_destroy(l2arc_free_on_write);
7064}
b128c09f
BB
7065
7066void
7067l2arc_start(void)
7068{
fb5f0bc8 7069 if (!(spa_mode_global & FWRITE))
b128c09f
BB
7070 return;
7071
7072 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
1229323d 7073 TS_RUN, defclsyspri);
b128c09f
BB
7074}
7075
7076void
7077l2arc_stop(void)
7078{
fb5f0bc8 7079 if (!(spa_mode_global & FWRITE))
b128c09f
BB
7080 return;
7081
7082 mutex_enter(&l2arc_feed_thr_lock);
7083 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
7084 l2arc_thread_exit = 1;
7085 while (l2arc_thread_exit != 0)
7086 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7087 mutex_exit(&l2arc_feed_thr_lock);
7088}
c28b2279
BB
7089
7090#if defined(_KERNEL) && defined(HAVE_SPL)
0f699108
AZ
7091EXPORT_SYMBOL(arc_buf_size);
7092EXPORT_SYMBOL(arc_write);
c28b2279
BB
7093EXPORT_SYMBOL(arc_read);
7094EXPORT_SYMBOL(arc_buf_remove_ref);
e0b0ca98 7095EXPORT_SYMBOL(arc_buf_info);
c28b2279 7096EXPORT_SYMBOL(arc_getbuf_func);
ab26409d
BB
7097EXPORT_SYMBOL(arc_add_prune_callback);
7098EXPORT_SYMBOL(arc_remove_prune_callback);
c28b2279 7099
bce45ec9 7100module_param(zfs_arc_min, ulong, 0644);
c409e464 7101MODULE_PARM_DESC(zfs_arc_min, "Min arc size");
c28b2279 7102
bce45ec9 7103module_param(zfs_arc_max, ulong, 0644);
c409e464 7104MODULE_PARM_DESC(zfs_arc_max, "Max arc size");
c28b2279 7105
bce45ec9 7106module_param(zfs_arc_meta_limit, ulong, 0644);
c28b2279 7107MODULE_PARM_DESC(zfs_arc_meta_limit, "Meta limit for arc size");
6a8f9b6b 7108
ca0bf58d
PS
7109module_param(zfs_arc_meta_min, ulong, 0644);
7110MODULE_PARM_DESC(zfs_arc_meta_min, "Min arc metadata");
7111
bce45ec9 7112module_param(zfs_arc_meta_prune, int, 0644);
2cbb06b5 7113MODULE_PARM_DESC(zfs_arc_meta_prune, "Meta objects to scan for prune");
c409e464 7114
ca67b33a 7115module_param(zfs_arc_meta_adjust_restarts, int, 0644);
bc888666
BB
7116MODULE_PARM_DESC(zfs_arc_meta_adjust_restarts,
7117 "Limit number of restarts in arc_adjust_meta");
7118
f6046738
BB
7119module_param(zfs_arc_meta_strategy, int, 0644);
7120MODULE_PARM_DESC(zfs_arc_meta_strategy, "Meta reclaim strategy");
7121
bce45ec9 7122module_param(zfs_arc_grow_retry, int, 0644);
c409e464
BB
7123MODULE_PARM_DESC(zfs_arc_grow_retry, "Seconds before growing arc size");
7124
89c8cac4
PS
7125module_param(zfs_arc_p_aggressive_disable, int, 0644);
7126MODULE_PARM_DESC(zfs_arc_p_aggressive_disable, "disable aggressive arc_p grow");
7127
62422785
PS
7128module_param(zfs_arc_p_dampener_disable, int, 0644);
7129MODULE_PARM_DESC(zfs_arc_p_dampener_disable, "disable arc_p adapt dampener");
7130
bce45ec9 7131module_param(zfs_arc_shrink_shift, int, 0644);
c409e464
BB
7132MODULE_PARM_DESC(zfs_arc_shrink_shift, "log2(fraction of arc to reclaim)");
7133
728d6ae9
BB
7134module_param(zfs_arc_p_min_shift, int, 0644);
7135MODULE_PARM_DESC(zfs_arc_p_min_shift, "arc_c shift to calc min/max arc_p");
7136
1f7c30df
BB
7137module_param(zfs_disable_dup_eviction, int, 0644);
7138MODULE_PARM_DESC(zfs_disable_dup_eviction, "disable duplicate buffer eviction");
7139
49ddb315
MA
7140module_param(zfs_arc_average_blocksize, int, 0444);
7141MODULE_PARM_DESC(zfs_arc_average_blocksize, "Target average block size");
7142
bce45ec9
BB
7143module_param(zfs_arc_min_prefetch_lifespan, int, 0644);
7144MODULE_PARM_DESC(zfs_arc_min_prefetch_lifespan, "Min life of prefetch block");
7145
ca0bf58d
PS
7146module_param(zfs_arc_num_sublists_per_state, int, 0644);
7147MODULE_PARM_DESC(zfs_arc_num_sublists_per_state,
7148 "Number of sublists used in each of the ARC state lists");
7149
bce45ec9 7150module_param(l2arc_write_max, ulong, 0644);
abd8610c
BB
7151MODULE_PARM_DESC(l2arc_write_max, "Max write bytes per interval");
7152
bce45ec9 7153module_param(l2arc_write_boost, ulong, 0644);
abd8610c
BB
7154MODULE_PARM_DESC(l2arc_write_boost, "Extra write bytes during device warmup");
7155
bce45ec9 7156module_param(l2arc_headroom, ulong, 0644);
abd8610c
BB
7157MODULE_PARM_DESC(l2arc_headroom, "Number of max device writes to precache");
7158
3a17a7a9
SK
7159module_param(l2arc_headroom_boost, ulong, 0644);
7160MODULE_PARM_DESC(l2arc_headroom_boost, "Compressed l2arc_headroom multiplier");
7161
8a09d5fd
BB
7162module_param(l2arc_max_block_size, ulong, 0644);
7163MODULE_PARM_DESC(l2arc_max_block_size, "Skip L2ARC buffers larger than N");
7164
bce45ec9 7165module_param(l2arc_feed_secs, ulong, 0644);
abd8610c
BB
7166MODULE_PARM_DESC(l2arc_feed_secs, "Seconds between L2ARC writing");
7167
bce45ec9 7168module_param(l2arc_feed_min_ms, ulong, 0644);
abd8610c
BB
7169MODULE_PARM_DESC(l2arc_feed_min_ms, "Min feed interval in milliseconds");
7170
bce45ec9 7171module_param(l2arc_noprefetch, int, 0644);
abd8610c
BB
7172MODULE_PARM_DESC(l2arc_noprefetch, "Skip caching prefetched buffers");
7173
3a17a7a9
SK
7174module_param(l2arc_nocompress, int, 0644);
7175MODULE_PARM_DESC(l2arc_nocompress, "Skip compressing L2ARC buffers");
7176
bce45ec9 7177module_param(l2arc_feed_again, int, 0644);
abd8610c
BB
7178MODULE_PARM_DESC(l2arc_feed_again, "Turbo L2ARC warmup");
7179
bce45ec9 7180module_param(l2arc_norw, int, 0644);
abd8610c
BB
7181MODULE_PARM_DESC(l2arc_norw, "No reads during writes");
7182
7e8bddd0
BB
7183module_param(zfs_arc_lotsfree_percent, int, 0644);
7184MODULE_PARM_DESC(zfs_arc_lotsfree_percent,
7185 "System free memory I/O throttle in bytes");
7186
11f552fa
BB
7187module_param(zfs_arc_sys_free, ulong, 0644);
7188MODULE_PARM_DESC(zfs_arc_sys_free, "System free memory target size in bytes");
7189
c28b2279 7190#endif