xref: /freebsd/sys/contrib/openzfs/module/zfs/arc.c (revision 29fc4075e69fd27de0cded313ac6000165d99f8b)
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 https://opensource.org/licenses/CDDL-1.0.
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 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2018, Joyent, Inc.
24  * Copyright (c) 2011, 2020, Delphix. All rights reserved.
25  * Copyright (c) 2014, Saso Kiselkov. All rights reserved.
26  * Copyright (c) 2017, Nexenta Systems, Inc.  All rights reserved.
27  * Copyright (c) 2019, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
28  * Copyright (c) 2020, George Amanakis. All rights reserved.
29  * Copyright (c) 2019, Klara Inc.
30  * Copyright (c) 2019, Allan Jude
31  * Copyright (c) 2020, The FreeBSD Foundation [1]
32  *
33  * [1] Portions of this software were developed by Allan Jude
34  *     under sponsorship from the FreeBSD Foundation.
35  */
36 
37 /*
38  * DVA-based Adjustable Replacement Cache
39  *
40  * While much of the theory of operation used here is
41  * based on the self-tuning, low overhead replacement cache
42  * presented by Megiddo and Modha at FAST 2003, there are some
43  * significant differences:
44  *
45  * 1. The Megiddo and Modha model assumes any page is evictable.
46  * Pages in its cache cannot be "locked" into memory.  This makes
47  * the eviction algorithm simple: evict the last page in the list.
48  * This also make the performance characteristics easy to reason
49  * about.  Our cache is not so simple.  At any given moment, some
50  * subset of the blocks in the cache are un-evictable because we
51  * have handed out a reference to them.  Blocks are only evictable
52  * when there are no external references active.  This makes
53  * eviction far more problematic:  we choose to evict the evictable
54  * blocks that are the "lowest" in the list.
55  *
56  * There are times when it is not possible to evict the requested
57  * space.  In these circumstances we are unable to adjust the cache
58  * size.  To prevent the cache growing unbounded at these times we
59  * implement a "cache throttle" that slows the flow of new data
60  * into the cache until we can make space available.
61  *
62  * 2. The Megiddo and Modha model assumes a fixed cache size.
63  * Pages are evicted when the cache is full and there is a cache
64  * miss.  Our model has a variable sized cache.  It grows with
65  * high use, but also tries to react to memory pressure from the
66  * operating system: decreasing its size when system memory is
67  * tight.
68  *
69  * 3. The Megiddo and Modha model assumes a fixed page size. All
70  * elements of the cache are therefore exactly the same size.  So
71  * when adjusting the cache size following a cache miss, its simply
72  * a matter of choosing a single page to evict.  In our model, we
73  * have variable sized cache blocks (ranging from 512 bytes to
74  * 128K bytes).  We therefore choose a set of blocks to evict to make
75  * space for a cache miss that approximates as closely as possible
76  * the space used by the new block.
77  *
78  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
79  * by N. Megiddo & D. Modha, FAST 2003
80  */
81 
82 /*
83  * The locking model:
84  *
85  * A new reference to a cache buffer can be obtained in two
86  * ways: 1) via a hash table lookup using the DVA as a key,
87  * or 2) via one of the ARC lists.  The arc_read() interface
88  * uses method 1, while the internal ARC algorithms for
89  * adjusting the cache use method 2.  We therefore provide two
90  * types of locks: 1) the hash table lock array, and 2) the
91  * ARC list locks.
92  *
93  * Buffers do not have their own mutexes, rather they rely on the
94  * hash table mutexes for the bulk of their protection (i.e. most
95  * fields in the arc_buf_hdr_t are protected by these mutexes).
96  *
97  * buf_hash_find() returns the appropriate mutex (held) when it
98  * locates the requested buffer in the hash table.  It returns
99  * NULL for the mutex if the buffer was not in the table.
100  *
101  * buf_hash_remove() expects the appropriate hash mutex to be
102  * already held before it is invoked.
103  *
104  * Each ARC state also has a mutex which is used to protect the
105  * buffer list associated with the state.  When attempting to
106  * obtain a hash table lock while holding an ARC list lock you
107  * must use: mutex_tryenter() to avoid deadlock.  Also note that
108  * the active state mutex must be held before the ghost state mutex.
109  *
110  * It as also possible to register a callback which is run when the
111  * arc_meta_limit is reached and no buffers can be safely evicted.  In
112  * this case the arc user should drop a reference on some arc buffers so
113  * they can be reclaimed and the arc_meta_limit honored.  For example,
114  * when using the ZPL each dentry holds a references on a znode.  These
115  * dentries must be pruned before the arc buffer holding the znode can
116  * be safely evicted.
117  *
118  * Note that the majority of the performance stats are manipulated
119  * with atomic operations.
120  *
121  * The L2ARC uses the l2ad_mtx on each vdev for the following:
122  *
123  *	- L2ARC buflist creation
124  *	- L2ARC buflist eviction
125  *	- L2ARC write completion, which walks L2ARC buflists
126  *	- ARC header destruction, as it removes from L2ARC buflists
127  *	- ARC header release, as it removes from L2ARC buflists
128  */
129 
130 /*
131  * ARC operation:
132  *
133  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
134  * This structure can point either to a block that is still in the cache or to
135  * one that is only accessible in an L2 ARC device, or it can provide
136  * information about a block that was recently evicted. If a block is
137  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
138  * information to retrieve it from the L2ARC device. This information is
139  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
140  * that is in this state cannot access the data directly.
141  *
142  * Blocks that are actively being referenced or have not been evicted
143  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
144  * the arc_buf_hdr_t that will point to the data block in memory. A block can
145  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
146  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
147  * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
148  *
149  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
150  * ability to store the physical data (b_pabd) associated with the DVA of the
151  * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
152  * it will match its on-disk compression characteristics. This behavior can be
153  * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
154  * compressed ARC functionality is disabled, the b_pabd will point to an
155  * uncompressed version of the on-disk data.
156  *
157  * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
158  * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
159  * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
160  * consumer. The ARC will provide references to this data and will keep it
161  * cached until it is no longer in use. The ARC caches only the L1ARC's physical
162  * data block and will evict any arc_buf_t that is no longer referenced. The
163  * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
164  * "overhead_size" kstat.
165  *
166  * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
167  * compressed form. The typical case is that consumers will want uncompressed
168  * data, and when that happens a new data buffer is allocated where the data is
169  * decompressed for them to use. Currently the only consumer who wants
170  * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
171  * exists on disk. When this happens, the arc_buf_t's data buffer is shared
172  * with the arc_buf_hdr_t.
173  *
174  * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
175  * first one is owned by a compressed send consumer (and therefore references
176  * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
177  * used by any other consumer (and has its own uncompressed copy of the data
178  * buffer).
179  *
180  *   arc_buf_hdr_t
181  *   +-----------+
182  *   | fields    |
183  *   | common to |
184  *   | L1- and   |
185  *   | L2ARC     |
186  *   +-----------+
187  *   | l2arc_buf_hdr_t
188  *   |           |
189  *   +-----------+
190  *   | l1arc_buf_hdr_t
191  *   |           |              arc_buf_t
192  *   | b_buf     +------------>+-----------+      arc_buf_t
193  *   | b_pabd    +-+           |b_next     +---->+-----------+
194  *   +-----------+ |           |-----------|     |b_next     +-->NULL
195  *                 |           |b_comp = T |     +-----------+
196  *                 |           |b_data     +-+   |b_comp = F |
197  *                 |           +-----------+ |   |b_data     +-+
198  *                 +->+------+               |   +-----------+ |
199  *        compressed  |      |               |                 |
200  *           data     |      |<--------------+                 | uncompressed
201  *                    +------+          compressed,            |     data
202  *                                        shared               +-->+------+
203  *                                         data                    |      |
204  *                                                                 |      |
205  *                                                                 +------+
206  *
207  * When a consumer reads a block, the ARC must first look to see if the
208  * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
209  * arc_buf_t and either copies uncompressed data into a new data buffer from an
210  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
211  * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
212  * hdr is compressed and the desired compression characteristics of the
213  * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
214  * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
215  * the last buffer in the hdr's b_buf list, however a shared compressed buf can
216  * be anywhere in the hdr's list.
217  *
218  * The diagram below shows an example of an uncompressed ARC hdr that is
219  * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
220  * the last element in the buf list):
221  *
222  *                arc_buf_hdr_t
223  *                +-----------+
224  *                |           |
225  *                |           |
226  *                |           |
227  *                +-----------+
228  * l2arc_buf_hdr_t|           |
229  *                |           |
230  *                +-----------+
231  * l1arc_buf_hdr_t|           |
232  *                |           |                 arc_buf_t    (shared)
233  *                |    b_buf  +------------>+---------+      arc_buf_t
234  *                |           |             |b_next   +---->+---------+
235  *                |  b_pabd   +-+           |---------|     |b_next   +-->NULL
236  *                +-----------+ |           |         |     +---------+
237  *                              |           |b_data   +-+   |         |
238  *                              |           +---------+ |   |b_data   +-+
239  *                              +->+------+             |   +---------+ |
240  *                                 |      |             |               |
241  *                   uncompressed  |      |             |               |
242  *                        data     +------+             |               |
243  *                                    ^                 +->+------+     |
244  *                                    |       uncompressed |      |     |
245  *                                    |           data     |      |     |
246  *                                    |                    +------+     |
247  *                                    +---------------------------------+
248  *
249  * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
250  * since the physical block is about to be rewritten. The new data contents
251  * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
252  * it may compress the data before writing it to disk. The ARC will be called
253  * with the transformed data and will memcpy the transformed on-disk block into
254  * a newly allocated b_pabd. Writes are always done into buffers which have
255  * either been loaned (and hence are new and don't have other readers) or
256  * buffers which have been released (and hence have their own hdr, if there
257  * were originally other readers of the buf's original hdr). This ensures that
258  * the ARC only needs to update a single buf and its hdr after a write occurs.
259  *
260  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
261  * L2ARC will always write the contents of b_pabd to the L2ARC. This means
262  * that when compressed ARC is enabled that the L2ARC blocks are identical
263  * to the on-disk block in the main data pool. This provides a significant
264  * advantage since the ARC can leverage the bp's checksum when reading from the
265  * L2ARC to determine if the contents are valid. However, if the compressed
266  * ARC is disabled, then the L2ARC's block must be transformed to look
267  * like the physical block in the main data pool before comparing the
268  * checksum and determining its validity.
269  *
270  * The L1ARC has a slightly different system for storing encrypted data.
271  * Raw (encrypted + possibly compressed) data has a few subtle differences from
272  * data that is just compressed. The biggest difference is that it is not
273  * possible to decrypt encrypted data (or vice-versa) if the keys aren't loaded.
274  * The other difference is that encryption cannot be treated as a suggestion.
275  * If a caller would prefer compressed data, but they actually wind up with
276  * uncompressed data the worst thing that could happen is there might be a
277  * performance hit. If the caller requests encrypted data, however, we must be
278  * sure they actually get it or else secret information could be leaked. Raw
279  * data is stored in hdr->b_crypt_hdr.b_rabd. An encrypted header, therefore,
280  * may have both an encrypted version and a decrypted version of its data at
281  * once. When a caller needs a raw arc_buf_t, it is allocated and the data is
282  * copied out of this header. To avoid complications with b_pabd, raw buffers
283  * cannot be shared.
284  */
285 
286 #include <sys/spa.h>
287 #include <sys/zio.h>
288 #include <sys/spa_impl.h>
289 #include <sys/zio_compress.h>
290 #include <sys/zio_checksum.h>
291 #include <sys/zfs_context.h>
292 #include <sys/arc.h>
293 #include <sys/zfs_refcount.h>
294 #include <sys/vdev.h>
295 #include <sys/vdev_impl.h>
296 #include <sys/dsl_pool.h>
297 #include <sys/multilist.h>
298 #include <sys/abd.h>
299 #include <sys/zil.h>
300 #include <sys/fm/fs/zfs.h>
301 #include <sys/callb.h>
302 #include <sys/kstat.h>
303 #include <sys/zthr.h>
304 #include <zfs_fletcher.h>
305 #include <sys/arc_impl.h>
306 #include <sys/trace_zfs.h>
307 #include <sys/aggsum.h>
308 #include <sys/wmsum.h>
309 #include <cityhash.h>
310 #include <sys/vdev_trim.h>
311 #include <sys/zfs_racct.h>
312 #include <sys/zstd/zstd.h>
313 
314 #ifndef _KERNEL
315 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
316 boolean_t arc_watch = B_FALSE;
317 #endif
318 
319 /*
320  * This thread's job is to keep enough free memory in the system, by
321  * calling arc_kmem_reap_soon() plus arc_reduce_target_size(), which improves
322  * arc_available_memory().
323  */
324 static zthr_t *arc_reap_zthr;
325 
326 /*
327  * This thread's job is to keep arc_size under arc_c, by calling
328  * arc_evict(), which improves arc_is_overflowing().
329  */
330 static zthr_t *arc_evict_zthr;
331 static arc_buf_hdr_t **arc_state_evict_markers;
332 static int arc_state_evict_marker_count;
333 
334 static kmutex_t arc_evict_lock;
335 static boolean_t arc_evict_needed = B_FALSE;
336 
337 /*
338  * Count of bytes evicted since boot.
339  */
340 static uint64_t arc_evict_count;
341 
342 /*
343  * List of arc_evict_waiter_t's, representing threads waiting for the
344  * arc_evict_count to reach specific values.
345  */
346 static list_t arc_evict_waiters;
347 
348 /*
349  * When arc_is_overflowing(), arc_get_data_impl() waits for this percent of
350  * the requested amount of data to be evicted.  For example, by default for
351  * every 2KB that's evicted, 1KB of it may be "reused" by a new allocation.
352  * Since this is above 100%, it ensures that progress is made towards getting
353  * arc_size under arc_c.  Since this is finite, it ensures that allocations
354  * can still happen, even during the potentially long time that arc_size is
355  * more than arc_c.
356  */
357 static int zfs_arc_eviction_pct = 200;
358 
359 /*
360  * The number of headers to evict in arc_evict_state_impl() before
361  * dropping the sublist lock and evicting from another sublist. A lower
362  * value means we're more likely to evict the "correct" header (i.e. the
363  * oldest header in the arc state), but comes with higher overhead
364  * (i.e. more invocations of arc_evict_state_impl()).
365  */
366 static int zfs_arc_evict_batch_limit = 10;
367 
368 /* number of seconds before growing cache again */
369 int arc_grow_retry = 5;
370 
371 /*
372  * Minimum time between calls to arc_kmem_reap_soon().
373  */
374 static const int arc_kmem_cache_reap_retry_ms = 1000;
375 
376 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
377 static int zfs_arc_overflow_shift = 8;
378 
379 /* shift of arc_c for calculating both min and max arc_p */
380 static int arc_p_min_shift = 4;
381 
382 /* log2(fraction of arc to reclaim) */
383 int arc_shrink_shift = 7;
384 
385 /* percent of pagecache to reclaim arc to */
386 #ifdef _KERNEL
387 uint_t zfs_arc_pc_percent = 0;
388 #endif
389 
390 /*
391  * log2(fraction of ARC which must be free to allow growing).
392  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
393  * when reading a new block into the ARC, we will evict an equal-sized block
394  * from the ARC.
395  *
396  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
397  * we will still not allow it to grow.
398  */
399 int			arc_no_grow_shift = 5;
400 
401 
402 /*
403  * minimum lifespan of a prefetch block in clock ticks
404  * (initialized in arc_init())
405  */
406 static int		arc_min_prefetch_ms;
407 static int		arc_min_prescient_prefetch_ms;
408 
409 /*
410  * If this percent of memory is free, don't throttle.
411  */
412 int arc_lotsfree_percent = 10;
413 
414 /*
415  * The arc has filled available memory and has now warmed up.
416  */
417 boolean_t arc_warm;
418 
419 /*
420  * These tunables are for performance analysis.
421  */
422 unsigned long zfs_arc_max = 0;
423 unsigned long zfs_arc_min = 0;
424 unsigned long zfs_arc_meta_limit = 0;
425 unsigned long zfs_arc_meta_min = 0;
426 static unsigned long zfs_arc_dnode_limit = 0;
427 static unsigned long zfs_arc_dnode_reduce_percent = 10;
428 static int zfs_arc_grow_retry = 0;
429 static int zfs_arc_shrink_shift = 0;
430 static int zfs_arc_p_min_shift = 0;
431 int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
432 
433 /*
434  * ARC dirty data constraints for arc_tempreserve_space() throttle:
435  * * total dirty data limit
436  * * anon block dirty limit
437  * * each pool's anon allowance
438  */
439 static const unsigned long zfs_arc_dirty_limit_percent = 50;
440 static const unsigned long zfs_arc_anon_limit_percent = 25;
441 static const unsigned long zfs_arc_pool_dirty_percent = 20;
442 
443 /*
444  * Enable or disable compressed arc buffers.
445  */
446 int zfs_compressed_arc_enabled = B_TRUE;
447 
448 /*
449  * ARC will evict meta buffers that exceed arc_meta_limit. This
450  * tunable make arc_meta_limit adjustable for different workloads.
451  */
452 static unsigned long zfs_arc_meta_limit_percent = 75;
453 
454 /*
455  * Percentage that can be consumed by dnodes of ARC meta buffers.
456  */
457 static unsigned long zfs_arc_dnode_limit_percent = 10;
458 
459 /*
460  * These tunables are Linux-specific
461  */
462 static unsigned long zfs_arc_sys_free = 0;
463 static int zfs_arc_min_prefetch_ms = 0;
464 static int zfs_arc_min_prescient_prefetch_ms = 0;
465 static int zfs_arc_p_dampener_disable = 1;
466 static int zfs_arc_meta_prune = 10000;
467 static int zfs_arc_meta_strategy = ARC_STRATEGY_META_BALANCED;
468 static int zfs_arc_meta_adjust_restarts = 4096;
469 static int zfs_arc_lotsfree_percent = 10;
470 
471 /*
472  * Number of arc_prune threads
473  */
474 static int zfs_arc_prune_task_threads = 1;
475 
476 /* The 6 states: */
477 arc_state_t ARC_anon;
478 arc_state_t ARC_mru;
479 arc_state_t ARC_mru_ghost;
480 arc_state_t ARC_mfu;
481 arc_state_t ARC_mfu_ghost;
482 arc_state_t ARC_l2c_only;
483 
484 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 },
500 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
501 	{ "access_skip",		KSTAT_DATA_UINT64 },
502 	{ "evict_skip",			KSTAT_DATA_UINT64 },
503 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
504 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
505 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
506 	{ "evict_l2_eligible_mfu",	KSTAT_DATA_UINT64 },
507 	{ "evict_l2_eligible_mru",	KSTAT_DATA_UINT64 },
508 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
509 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
510 	{ "hash_elements",		KSTAT_DATA_UINT64 },
511 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
512 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
513 	{ "hash_chains",		KSTAT_DATA_UINT64 },
514 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
515 	{ "p",				KSTAT_DATA_UINT64 },
516 	{ "c",				KSTAT_DATA_UINT64 },
517 	{ "c_min",			KSTAT_DATA_UINT64 },
518 	{ "c_max",			KSTAT_DATA_UINT64 },
519 	{ "size",			KSTAT_DATA_UINT64 },
520 	{ "compressed_size",		KSTAT_DATA_UINT64 },
521 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
522 	{ "overhead_size",		KSTAT_DATA_UINT64 },
523 	{ "hdr_size",			KSTAT_DATA_UINT64 },
524 	{ "data_size",			KSTAT_DATA_UINT64 },
525 	{ "metadata_size",		KSTAT_DATA_UINT64 },
526 	{ "dbuf_size",			KSTAT_DATA_UINT64 },
527 	{ "dnode_size",			KSTAT_DATA_UINT64 },
528 	{ "bonus_size",			KSTAT_DATA_UINT64 },
529 #if defined(COMPAT_FREEBSD11)
530 	{ "other_size",			KSTAT_DATA_UINT64 },
531 #endif
532 	{ "anon_size",			KSTAT_DATA_UINT64 },
533 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
534 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
535 	{ "mru_size",			KSTAT_DATA_UINT64 },
536 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
537 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
538 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
539 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
540 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
541 	{ "mfu_size",			KSTAT_DATA_UINT64 },
542 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
543 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
544 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
545 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
546 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
547 	{ "l2_hits",			KSTAT_DATA_UINT64 },
548 	{ "l2_misses",			KSTAT_DATA_UINT64 },
549 	{ "l2_prefetch_asize",		KSTAT_DATA_UINT64 },
550 	{ "l2_mru_asize",		KSTAT_DATA_UINT64 },
551 	{ "l2_mfu_asize",		KSTAT_DATA_UINT64 },
552 	{ "l2_bufc_data_asize",		KSTAT_DATA_UINT64 },
553 	{ "l2_bufc_metadata_asize",	KSTAT_DATA_UINT64 },
554 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
555 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
556 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
557 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
558 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
559 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
560 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
561 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
562 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
563 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
564 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
565 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
566 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
567 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
568 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
569 	{ "l2_size",			KSTAT_DATA_UINT64 },
570 	{ "l2_asize",			KSTAT_DATA_UINT64 },
571 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
572 	{ "l2_log_blk_writes",		KSTAT_DATA_UINT64 },
573 	{ "l2_log_blk_avg_asize",	KSTAT_DATA_UINT64 },
574 	{ "l2_log_blk_asize",		KSTAT_DATA_UINT64 },
575 	{ "l2_log_blk_count",		KSTAT_DATA_UINT64 },
576 	{ "l2_data_to_meta_ratio",	KSTAT_DATA_UINT64 },
577 	{ "l2_rebuild_success",		KSTAT_DATA_UINT64 },
578 	{ "l2_rebuild_unsupported",	KSTAT_DATA_UINT64 },
579 	{ "l2_rebuild_io_errors",	KSTAT_DATA_UINT64 },
580 	{ "l2_rebuild_dh_errors",	KSTAT_DATA_UINT64 },
581 	{ "l2_rebuild_cksum_lb_errors",	KSTAT_DATA_UINT64 },
582 	{ "l2_rebuild_lowmem",		KSTAT_DATA_UINT64 },
583 	{ "l2_rebuild_size",		KSTAT_DATA_UINT64 },
584 	{ "l2_rebuild_asize",		KSTAT_DATA_UINT64 },
585 	{ "l2_rebuild_bufs",		KSTAT_DATA_UINT64 },
586 	{ "l2_rebuild_bufs_precached",	KSTAT_DATA_UINT64 },
587 	{ "l2_rebuild_log_blks",	KSTAT_DATA_UINT64 },
588 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
589 	{ "memory_direct_count",	KSTAT_DATA_UINT64 },
590 	{ "memory_indirect_count",	KSTAT_DATA_UINT64 },
591 	{ "memory_all_bytes",		KSTAT_DATA_UINT64 },
592 	{ "memory_free_bytes",		KSTAT_DATA_UINT64 },
593 	{ "memory_available_bytes",	KSTAT_DATA_INT64 },
594 	{ "arc_no_grow",		KSTAT_DATA_UINT64 },
595 	{ "arc_tempreserve",		KSTAT_DATA_UINT64 },
596 	{ "arc_loaned_bytes",		KSTAT_DATA_UINT64 },
597 	{ "arc_prune",			KSTAT_DATA_UINT64 },
598 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
599 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
600 	{ "arc_dnode_limit",		KSTAT_DATA_UINT64 },
601 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
602 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
603 	{ "async_upgrade_sync",		KSTAT_DATA_UINT64 },
604 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
605 	{ "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
606 	{ "arc_need_free",		KSTAT_DATA_UINT64 },
607 	{ "arc_sys_free",		KSTAT_DATA_UINT64 },
608 	{ "arc_raw_size",		KSTAT_DATA_UINT64 },
609 	{ "cached_only_in_progress",	KSTAT_DATA_UINT64 },
610 	{ "abd_chunk_waste_size",	KSTAT_DATA_UINT64 },
611 };
612 
613 arc_sums_t arc_sums;
614 
615 #define	ARCSTAT_MAX(stat, val) {					\
616 	uint64_t m;							\
617 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
618 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
619 		continue;						\
620 }
621 
622 /*
623  * We define a macro to allow ARC hits/misses to be easily broken down by
624  * two separate conditions, giving a total of four different subtypes for
625  * each of hits and misses (so eight statistics total).
626  */
627 #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
628 	if (cond1) {							\
629 		if (cond2) {						\
630 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
631 		} else {						\
632 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
633 		}							\
634 	} else {							\
635 		if (cond2) {						\
636 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
637 		} else {						\
638 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
639 		}							\
640 	}
641 
642 /*
643  * This macro allows us to use kstats as floating averages. Each time we
644  * update this kstat, we first factor it and the update value by
645  * ARCSTAT_AVG_FACTOR to shrink the new value's contribution to the overall
646  * average. This macro assumes that integer loads and stores are atomic, but
647  * is not safe for multiple writers updating the kstat in parallel (only the
648  * last writer's update will remain).
649  */
650 #define	ARCSTAT_F_AVG_FACTOR	3
651 #define	ARCSTAT_F_AVG(stat, value) \
652 	do { \
653 		uint64_t x = ARCSTAT(stat); \
654 		x = x - x / ARCSTAT_F_AVG_FACTOR + \
655 		    (value) / ARCSTAT_F_AVG_FACTOR; \
656 		ARCSTAT(stat) = x; \
657 	} while (0)
658 
659 static kstat_t			*arc_ksp;
660 
661 /*
662  * There are several ARC variables that are critical to export as kstats --
663  * but we don't want to have to grovel around in the kstat whenever we wish to
664  * manipulate them.  For these variables, we therefore define them to be in
665  * terms of the statistic variable.  This assures that we are not introducing
666  * the possibility of inconsistency by having shadow copies of the variables,
667  * while still allowing the code to be readable.
668  */
669 #define	arc_tempreserve	ARCSTAT(arcstat_tempreserve)
670 #define	arc_loaned_bytes	ARCSTAT(arcstat_loaned_bytes)
671 #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
672 /* max size for dnodes */
673 #define	arc_dnode_size_limit	ARCSTAT(arcstat_dnode_limit)
674 #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
675 #define	arc_need_free	ARCSTAT(arcstat_need_free) /* waiting to be evicted */
676 
677 hrtime_t arc_growtime;
678 list_t arc_prune_list;
679 kmutex_t arc_prune_mtx;
680 taskq_t *arc_prune_taskq;
681 
682 #define	GHOST_STATE(state)	\
683 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
684 	(state) == arc_l2c_only)
685 
686 #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
687 #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
688 #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
689 #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
690 #define	HDR_PRESCIENT_PREFETCH(hdr)	\
691 	((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
692 #define	HDR_COMPRESSION_ENABLED(hdr)	\
693 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
694 
695 #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
696 #define	HDR_L2_READING(hdr)	\
697 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
698 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
699 #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
700 #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
701 #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
702 #define	HDR_PROTECTED(hdr)	((hdr)->b_flags & ARC_FLAG_PROTECTED)
703 #define	HDR_NOAUTH(hdr)		((hdr)->b_flags & ARC_FLAG_NOAUTH)
704 #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
705 
706 #define	HDR_ISTYPE_METADATA(hdr)	\
707 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
708 #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
709 
710 #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
711 #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
712 #define	HDR_HAS_RABD(hdr)	\
713 	(HDR_HAS_L1HDR(hdr) && HDR_PROTECTED(hdr) &&	\
714 	(hdr)->b_crypt_hdr.b_rabd != NULL)
715 #define	HDR_ENCRYPTED(hdr)	\
716 	(HDR_PROTECTED(hdr) && DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
717 #define	HDR_AUTHENTICATED(hdr)	\
718 	(HDR_PROTECTED(hdr) && !DMU_OT_IS_ENCRYPTED((hdr)->b_crypt_hdr.b_ot))
719 
720 /* For storing compression mode in b_flags */
721 #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
722 
723 #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
724 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
725 #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
726 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
727 
728 #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
729 #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
730 #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
731 #define	ARC_BUF_ENCRYPTED(buf)	((buf)->b_flags & ARC_BUF_FLAG_ENCRYPTED)
732 
733 /*
734  * Other sizes
735  */
736 
737 #define	HDR_FULL_CRYPT_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
738 #define	HDR_FULL_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_crypt_hdr))
739 #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
740 
741 /*
742  * Hash table routines
743  */
744 
745 #define	BUF_LOCKS 2048
746 typedef struct buf_hash_table {
747 	uint64_t ht_mask;
748 	arc_buf_hdr_t **ht_table;
749 	kmutex_t ht_locks[BUF_LOCKS] ____cacheline_aligned;
750 } buf_hash_table_t;
751 
752 static buf_hash_table_t buf_hash_table;
753 
754 #define	BUF_HASH_INDEX(spa, dva, birth) \
755 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
756 #define	BUF_HASH_LOCK(idx)	(&buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
757 #define	HDR_LOCK(hdr) \
758 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
759 
760 uint64_t zfs_crc64_table[256];
761 
762 /*
763  * Level 2 ARC
764  */
765 
766 #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
767 #define	L2ARC_HEADROOM		2			/* num of writes */
768 
769 /*
770  * If we discover during ARC scan any buffers to be compressed, we boost
771  * our headroom for the next scanning cycle by this percentage multiple.
772  */
773 #define	L2ARC_HEADROOM_BOOST	200
774 #define	L2ARC_FEED_SECS		1		/* caching interval secs */
775 #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
776 
777 /*
778  * We can feed L2ARC from two states of ARC buffers, mru and mfu,
779  * and each of the state has two types: data and metadata.
780  */
781 #define	L2ARC_FEED_TYPES	4
782 
783 /* L2ARC Performance Tunables */
784 unsigned long l2arc_write_max = L2ARC_WRITE_SIZE;	/* def max write size */
785 unsigned long l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra warmup write */
786 unsigned long l2arc_headroom = L2ARC_HEADROOM;		/* # of dev writes */
787 unsigned long l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
788 unsigned long l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
789 unsigned long l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval msecs */
790 int l2arc_noprefetch = B_TRUE;			/* don't cache prefetch bufs */
791 int l2arc_feed_again = B_TRUE;			/* turbo warmup */
792 int l2arc_norw = B_FALSE;			/* no reads during writes */
793 static int l2arc_meta_percent = 33;		/* limit on headers size */
794 
795 /*
796  * L2ARC Internals
797  */
798 static list_t L2ARC_dev_list;			/* device list */
799 static list_t *l2arc_dev_list;			/* device list pointer */
800 static kmutex_t l2arc_dev_mtx;			/* device list mutex */
801 static l2arc_dev_t *l2arc_dev_last;		/* last device used */
802 static list_t L2ARC_free_on_write;		/* free after write buf list */
803 static list_t *l2arc_free_on_write;		/* free after write list ptr */
804 static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
805 static uint64_t l2arc_ndev;			/* number of devices */
806 
807 typedef struct l2arc_read_callback {
808 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
809 	blkptr_t		l2rcb_bp;		/* original blkptr */
810 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
811 	int			l2rcb_flags;		/* original flags */
812 	abd_t			*l2rcb_abd;		/* temporary buffer */
813 } l2arc_read_callback_t;
814 
815 typedef struct l2arc_data_free {
816 	/* protected by l2arc_free_on_write_mtx */
817 	abd_t		*l2df_abd;
818 	size_t		l2df_size;
819 	arc_buf_contents_t l2df_type;
820 	list_node_t	l2df_list_node;
821 } l2arc_data_free_t;
822 
823 typedef enum arc_fill_flags {
824 	ARC_FILL_LOCKED		= 1 << 0, /* hdr lock is held */
825 	ARC_FILL_COMPRESSED	= 1 << 1, /* fill with compressed data */
826 	ARC_FILL_ENCRYPTED	= 1 << 2, /* fill with encrypted data */
827 	ARC_FILL_NOAUTH		= 1 << 3, /* don't attempt to authenticate */
828 	ARC_FILL_IN_PLACE	= 1 << 4  /* fill in place (special case) */
829 } arc_fill_flags_t;
830 
831 typedef enum arc_ovf_level {
832 	ARC_OVF_NONE,			/* ARC within target size. */
833 	ARC_OVF_SOME,			/* ARC is slightly overflowed. */
834 	ARC_OVF_SEVERE			/* ARC is severely overflowed. */
835 } arc_ovf_level_t;
836 
837 static kmutex_t l2arc_feed_thr_lock;
838 static kcondvar_t l2arc_feed_thr_cv;
839 static uint8_t l2arc_thread_exit;
840 
841 static kmutex_t l2arc_rebuild_thr_lock;
842 static kcondvar_t l2arc_rebuild_thr_cv;
843 
844 enum arc_hdr_alloc_flags {
845 	ARC_HDR_ALLOC_RDATA = 0x1,
846 	ARC_HDR_DO_ADAPT = 0x2,
847 	ARC_HDR_USE_RESERVE = 0x4,
848 };
849 
850 
851 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, const void *, int);
852 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, const void *);
853 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, const void *, int);
854 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, const void *);
855 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, const void *);
856 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size,
857     const void *tag);
858 static void arc_hdr_free_abd(arc_buf_hdr_t *, boolean_t);
859 static void arc_hdr_alloc_abd(arc_buf_hdr_t *, int);
860 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
861 static void arc_buf_watch(arc_buf_t *);
862 
863 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
864 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
865 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
866 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
867 
868 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
869 static void l2arc_read_done(zio_t *);
870 static void l2arc_do_free_on_write(void);
871 static void l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
872     boolean_t state_only);
873 
874 #define	l2arc_hdr_arcstats_increment(hdr) \
875 	l2arc_hdr_arcstats_update((hdr), B_TRUE, B_FALSE)
876 #define	l2arc_hdr_arcstats_decrement(hdr) \
877 	l2arc_hdr_arcstats_update((hdr), B_FALSE, B_FALSE)
878 #define	l2arc_hdr_arcstats_increment_state(hdr) \
879 	l2arc_hdr_arcstats_update((hdr), B_TRUE, B_TRUE)
880 #define	l2arc_hdr_arcstats_decrement_state(hdr) \
881 	l2arc_hdr_arcstats_update((hdr), B_FALSE, B_TRUE)
882 
883 /*
884  * l2arc_exclude_special : A zfs module parameter that controls whether buffers
885  * 		present on special vdevs are eligibile for caching in L2ARC. If
886  * 		set to 1, exclude dbufs on special vdevs from being cached to
887  * 		L2ARC.
888  */
889 int l2arc_exclude_special = 0;
890 
891 /*
892  * l2arc_mfuonly : A ZFS module parameter that controls whether only MFU
893  * 		metadata and data are cached from ARC into L2ARC.
894  */
895 static int l2arc_mfuonly = 0;
896 
897 /*
898  * L2ARC TRIM
899  * l2arc_trim_ahead : A ZFS module parameter that controls how much ahead of
900  * 		the current write size (l2arc_write_max) we should TRIM if we
901  * 		have filled the device. It is defined as a percentage of the
902  * 		write size. If set to 100 we trim twice the space required to
903  * 		accommodate upcoming writes. A minimum of 64MB will be trimmed.
904  * 		It also enables TRIM of the whole L2ARC device upon creation or
905  * 		addition to an existing pool or if the header of the device is
906  * 		invalid upon importing a pool or onlining a cache device. The
907  * 		default is 0, which disables TRIM on L2ARC altogether as it can
908  * 		put significant stress on the underlying storage devices. This
909  * 		will vary depending of how well the specific device handles
910  * 		these commands.
911  */
912 static unsigned long l2arc_trim_ahead = 0;
913 
914 /*
915  * Performance tuning of L2ARC persistence:
916  *
917  * l2arc_rebuild_enabled : A ZFS module parameter that controls whether adding
918  * 		an L2ARC device (either at pool import or later) will attempt
919  * 		to rebuild L2ARC buffer contents.
920  * l2arc_rebuild_blocks_min_l2size : A ZFS module parameter that controls
921  * 		whether log blocks are written to the L2ARC device. If the L2ARC
922  * 		device is less than 1GB, the amount of data l2arc_evict()
923  * 		evicts is significant compared to the amount of restored L2ARC
924  * 		data. In this case do not write log blocks in L2ARC in order
925  * 		not to waste space.
926  */
927 static int l2arc_rebuild_enabled = B_TRUE;
928 static unsigned long l2arc_rebuild_blocks_min_l2size = 1024 * 1024 * 1024;
929 
930 /* L2ARC persistence rebuild control routines. */
931 void l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen);
932 static __attribute__((noreturn)) void l2arc_dev_rebuild_thread(void *arg);
933 static int l2arc_rebuild(l2arc_dev_t *dev);
934 
935 /* L2ARC persistence read I/O routines. */
936 static int l2arc_dev_hdr_read(l2arc_dev_t *dev);
937 static int l2arc_log_blk_read(l2arc_dev_t *dev,
938     const l2arc_log_blkptr_t *this_lp, const l2arc_log_blkptr_t *next_lp,
939     l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
940     zio_t *this_io, zio_t **next_io);
941 static zio_t *l2arc_log_blk_fetch(vdev_t *vd,
942     const l2arc_log_blkptr_t *lp, l2arc_log_blk_phys_t *lb);
943 static void l2arc_log_blk_fetch_abort(zio_t *zio);
944 
945 /* L2ARC persistence block restoration routines. */
946 static void l2arc_log_blk_restore(l2arc_dev_t *dev,
947     const l2arc_log_blk_phys_t *lb, uint64_t lb_asize);
948 static void l2arc_hdr_restore(const l2arc_log_ent_phys_t *le,
949     l2arc_dev_t *dev);
950 
951 /* L2ARC persistence write I/O routines. */
952 static void l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio,
953     l2arc_write_callback_t *cb);
954 
955 /* L2ARC persistence auxiliary routines. */
956 boolean_t l2arc_log_blkptr_valid(l2arc_dev_t *dev,
957     const l2arc_log_blkptr_t *lbp);
958 static boolean_t l2arc_log_blk_insert(l2arc_dev_t *dev,
959     const arc_buf_hdr_t *ab);
960 boolean_t l2arc_range_check_overlap(uint64_t bottom,
961     uint64_t top, uint64_t check);
962 static void l2arc_blk_fetch_done(zio_t *zio);
963 static inline uint64_t
964     l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev);
965 
966 /*
967  * We use Cityhash for this. It's fast, and has good hash properties without
968  * requiring any large static buffers.
969  */
970 static uint64_t
971 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
972 {
973 	return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
974 }
975 
976 #define	HDR_EMPTY(hdr)						\
977 	((hdr)->b_dva.dva_word[0] == 0 &&			\
978 	(hdr)->b_dva.dva_word[1] == 0)
979 
980 #define	HDR_EMPTY_OR_LOCKED(hdr)				\
981 	(HDR_EMPTY(hdr) || MUTEX_HELD(HDR_LOCK(hdr)))
982 
983 #define	HDR_EQUAL(spa, dva, birth, hdr)				\
984 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
985 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
986 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
987 
988 static void
989 buf_discard_identity(arc_buf_hdr_t *hdr)
990 {
991 	hdr->b_dva.dva_word[0] = 0;
992 	hdr->b_dva.dva_word[1] = 0;
993 	hdr->b_birth = 0;
994 }
995 
996 static arc_buf_hdr_t *
997 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
998 {
999 	const dva_t *dva = BP_IDENTITY(bp);
1000 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1001 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1002 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1003 	arc_buf_hdr_t *hdr;
1004 
1005 	mutex_enter(hash_lock);
1006 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1007 	    hdr = hdr->b_hash_next) {
1008 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1009 			*lockp = hash_lock;
1010 			return (hdr);
1011 		}
1012 	}
1013 	mutex_exit(hash_lock);
1014 	*lockp = NULL;
1015 	return (NULL);
1016 }
1017 
1018 /*
1019  * Insert an entry into the hash table.  If there is already an element
1020  * equal to elem in the hash table, then the already existing element
1021  * will be returned and the new element will not be inserted.
1022  * Otherwise returns NULL.
1023  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1024  */
1025 static arc_buf_hdr_t *
1026 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1027 {
1028 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1029 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1030 	arc_buf_hdr_t *fhdr;
1031 	uint32_t i;
1032 
1033 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1034 	ASSERT(hdr->b_birth != 0);
1035 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
1036 
1037 	if (lockp != NULL) {
1038 		*lockp = hash_lock;
1039 		mutex_enter(hash_lock);
1040 	} else {
1041 		ASSERT(MUTEX_HELD(hash_lock));
1042 	}
1043 
1044 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1045 	    fhdr = fhdr->b_hash_next, i++) {
1046 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1047 			return (fhdr);
1048 	}
1049 
1050 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
1051 	buf_hash_table.ht_table[idx] = hdr;
1052 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1053 
1054 	/* collect some hash table performance data */
1055 	if (i > 0) {
1056 		ARCSTAT_BUMP(arcstat_hash_collisions);
1057 		if (i == 1)
1058 			ARCSTAT_BUMP(arcstat_hash_chains);
1059 
1060 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1061 	}
1062 	uint64_t he = atomic_inc_64_nv(
1063 	    &arc_stats.arcstat_hash_elements.value.ui64);
1064 	ARCSTAT_MAX(arcstat_hash_elements_max, he);
1065 
1066 	return (NULL);
1067 }
1068 
1069 static void
1070 buf_hash_remove(arc_buf_hdr_t *hdr)
1071 {
1072 	arc_buf_hdr_t *fhdr, **hdrp;
1073 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1074 
1075 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1076 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1077 
1078 	hdrp = &buf_hash_table.ht_table[idx];
1079 	while ((fhdr = *hdrp) != hdr) {
1080 		ASSERT3P(fhdr, !=, NULL);
1081 		hdrp = &fhdr->b_hash_next;
1082 	}
1083 	*hdrp = hdr->b_hash_next;
1084 	hdr->b_hash_next = NULL;
1085 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1086 
1087 	/* collect some hash table performance data */
1088 	atomic_dec_64(&arc_stats.arcstat_hash_elements.value.ui64);
1089 
1090 	if (buf_hash_table.ht_table[idx] &&
1091 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1092 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1093 }
1094 
1095 /*
1096  * Global data structures and functions for the buf kmem cache.
1097  */
1098 
1099 static kmem_cache_t *hdr_full_cache;
1100 static kmem_cache_t *hdr_full_crypt_cache;
1101 static kmem_cache_t *hdr_l2only_cache;
1102 static kmem_cache_t *buf_cache;
1103 
1104 static void
1105 buf_fini(void)
1106 {
1107 #if defined(_KERNEL)
1108 	/*
1109 	 * Large allocations which do not require contiguous pages
1110 	 * should be using vmem_free() in the linux kernel\
1111 	 */
1112 	vmem_free(buf_hash_table.ht_table,
1113 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1114 #else
1115 	kmem_free(buf_hash_table.ht_table,
1116 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1117 #endif
1118 	for (int i = 0; i < BUF_LOCKS; i++)
1119 		mutex_destroy(BUF_HASH_LOCK(i));
1120 	kmem_cache_destroy(hdr_full_cache);
1121 	kmem_cache_destroy(hdr_full_crypt_cache);
1122 	kmem_cache_destroy(hdr_l2only_cache);
1123 	kmem_cache_destroy(buf_cache);
1124 }
1125 
1126 /*
1127  * Constructor callback - called when the cache is empty
1128  * and a new buf is requested.
1129  */
1130 static int
1131 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1132 {
1133 	(void) unused, (void) kmflag;
1134 	arc_buf_hdr_t *hdr = vbuf;
1135 
1136 	memset(hdr, 0, HDR_FULL_SIZE);
1137 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
1138 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1139 	zfs_refcount_create(&hdr->b_l1hdr.b_refcnt);
1140 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1141 	list_link_init(&hdr->b_l1hdr.b_arc_node);
1142 	list_link_init(&hdr->b_l2hdr.b_l2node);
1143 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1144 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1145 
1146 	return (0);
1147 }
1148 
1149 static int
1150 hdr_full_crypt_cons(void *vbuf, void *unused, int kmflag)
1151 {
1152 	(void) unused;
1153 	arc_buf_hdr_t *hdr = vbuf;
1154 
1155 	hdr_full_cons(vbuf, unused, kmflag);
1156 	memset(&hdr->b_crypt_hdr, 0, sizeof (hdr->b_crypt_hdr));
1157 	arc_space_consume(sizeof (hdr->b_crypt_hdr), ARC_SPACE_HDRS);
1158 
1159 	return (0);
1160 }
1161 
1162 static int
1163 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1164 {
1165 	(void) unused, (void) kmflag;
1166 	arc_buf_hdr_t *hdr = vbuf;
1167 
1168 	memset(hdr, 0, HDR_L2ONLY_SIZE);
1169 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1170 
1171 	return (0);
1172 }
1173 
1174 static int
1175 buf_cons(void *vbuf, void *unused, int kmflag)
1176 {
1177 	(void) unused, (void) kmflag;
1178 	arc_buf_t *buf = vbuf;
1179 
1180 	memset(buf, 0, sizeof (arc_buf_t));
1181 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1182 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1183 
1184 	return (0);
1185 }
1186 
1187 /*
1188  * Destructor callback - called when a cached buf is
1189  * no longer required.
1190  */
1191 static void
1192 hdr_full_dest(void *vbuf, void *unused)
1193 {
1194 	(void) unused;
1195 	arc_buf_hdr_t *hdr = vbuf;
1196 
1197 	ASSERT(HDR_EMPTY(hdr));
1198 	cv_destroy(&hdr->b_l1hdr.b_cv);
1199 	zfs_refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1200 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1201 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1202 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1203 }
1204 
1205 static void
1206 hdr_full_crypt_dest(void *vbuf, void *unused)
1207 {
1208 	(void) vbuf, (void) unused;
1209 
1210 	hdr_full_dest(vbuf, unused);
1211 	arc_space_return(sizeof (((arc_buf_hdr_t *)NULL)->b_crypt_hdr),
1212 	    ARC_SPACE_HDRS);
1213 }
1214 
1215 static void
1216 hdr_l2only_dest(void *vbuf, void *unused)
1217 {
1218 	(void) unused;
1219 	arc_buf_hdr_t *hdr = vbuf;
1220 
1221 	ASSERT(HDR_EMPTY(hdr));
1222 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1223 }
1224 
1225 static void
1226 buf_dest(void *vbuf, void *unused)
1227 {
1228 	(void) unused;
1229 	arc_buf_t *buf = vbuf;
1230 
1231 	mutex_destroy(&buf->b_evict_lock);
1232 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1233 }
1234 
1235 static void
1236 buf_init(void)
1237 {
1238 	uint64_t *ct = NULL;
1239 	uint64_t hsize = 1ULL << 12;
1240 	int i, j;
1241 
1242 	/*
1243 	 * The hash table is big enough to fill all of physical memory
1244 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1245 	 * By default, the table will take up
1246 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1247 	 */
1248 	while (hsize * zfs_arc_average_blocksize < arc_all_memory())
1249 		hsize <<= 1;
1250 retry:
1251 	buf_hash_table.ht_mask = hsize - 1;
1252 #if defined(_KERNEL)
1253 	/*
1254 	 * Large allocations which do not require contiguous pages
1255 	 * should be using vmem_alloc() in the linux kernel
1256 	 */
1257 	buf_hash_table.ht_table =
1258 	    vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1259 #else
1260 	buf_hash_table.ht_table =
1261 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1262 #endif
1263 	if (buf_hash_table.ht_table == NULL) {
1264 		ASSERT(hsize > (1ULL << 8));
1265 		hsize >>= 1;
1266 		goto retry;
1267 	}
1268 
1269 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1270 	    0, hdr_full_cons, hdr_full_dest, NULL, NULL, NULL, 0);
1271 	hdr_full_crypt_cache = kmem_cache_create("arc_buf_hdr_t_full_crypt",
1272 	    HDR_FULL_CRYPT_SIZE, 0, hdr_full_crypt_cons, hdr_full_crypt_dest,
1273 	    NULL, NULL, NULL, 0);
1274 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1275 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, NULL,
1276 	    NULL, NULL, 0);
1277 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1278 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1279 
1280 	for (i = 0; i < 256; i++)
1281 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1282 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1283 
1284 	for (i = 0; i < BUF_LOCKS; i++)
1285 		mutex_init(BUF_HASH_LOCK(i), NULL, MUTEX_DEFAULT, NULL);
1286 }
1287 
1288 #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1289 
1290 /*
1291  * This is the size that the buf occupies in memory. If the buf is compressed,
1292  * it will correspond to the compressed size. You should use this method of
1293  * getting the buf size unless you explicitly need the logical size.
1294  */
1295 uint64_t
1296 arc_buf_size(arc_buf_t *buf)
1297 {
1298 	return (ARC_BUF_COMPRESSED(buf) ?
1299 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1300 }
1301 
1302 uint64_t
1303 arc_buf_lsize(arc_buf_t *buf)
1304 {
1305 	return (HDR_GET_LSIZE(buf->b_hdr));
1306 }
1307 
1308 /*
1309  * This function will return B_TRUE if the buffer is encrypted in memory.
1310  * This buffer can be decrypted by calling arc_untransform().
1311  */
1312 boolean_t
1313 arc_is_encrypted(arc_buf_t *buf)
1314 {
1315 	return (ARC_BUF_ENCRYPTED(buf) != 0);
1316 }
1317 
1318 /*
1319  * Returns B_TRUE if the buffer represents data that has not had its MAC
1320  * verified yet.
1321  */
1322 boolean_t
1323 arc_is_unauthenticated(arc_buf_t *buf)
1324 {
1325 	return (HDR_NOAUTH(buf->b_hdr) != 0);
1326 }
1327 
1328 void
1329 arc_get_raw_params(arc_buf_t *buf, boolean_t *byteorder, uint8_t *salt,
1330     uint8_t *iv, uint8_t *mac)
1331 {
1332 	arc_buf_hdr_t *hdr = buf->b_hdr;
1333 
1334 	ASSERT(HDR_PROTECTED(hdr));
1335 
1336 	memcpy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
1337 	memcpy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
1338 	memcpy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
1339 	*byteorder = (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
1340 	    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
1341 }
1342 
1343 /*
1344  * Indicates how this buffer is compressed in memory. If it is not compressed
1345  * the value will be ZIO_COMPRESS_OFF. It can be made normally readable with
1346  * arc_untransform() as long as it is also unencrypted.
1347  */
1348 enum zio_compress
1349 arc_get_compression(arc_buf_t *buf)
1350 {
1351 	return (ARC_BUF_COMPRESSED(buf) ?
1352 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1353 }
1354 
1355 /*
1356  * Return the compression algorithm used to store this data in the ARC. If ARC
1357  * compression is enabled or this is an encrypted block, this will be the same
1358  * as what's used to store it on-disk. Otherwise, this will be ZIO_COMPRESS_OFF.
1359  */
1360 static inline enum zio_compress
1361 arc_hdr_get_compress(arc_buf_hdr_t *hdr)
1362 {
1363 	return (HDR_COMPRESSION_ENABLED(hdr) ?
1364 	    HDR_GET_COMPRESS(hdr) : ZIO_COMPRESS_OFF);
1365 }
1366 
1367 uint8_t
1368 arc_get_complevel(arc_buf_t *buf)
1369 {
1370 	return (buf->b_hdr->b_complevel);
1371 }
1372 
1373 static inline boolean_t
1374 arc_buf_is_shared(arc_buf_t *buf)
1375 {
1376 	boolean_t shared = (buf->b_data != NULL &&
1377 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1378 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1379 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1380 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1381 	IMPLY(shared, ARC_BUF_SHARED(buf));
1382 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1383 
1384 	/*
1385 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1386 	 * already being shared" requirement prevents us from doing that.
1387 	 */
1388 
1389 	return (shared);
1390 }
1391 
1392 /*
1393  * Free the checksum associated with this header. If there is no checksum, this
1394  * is a no-op.
1395  */
1396 static inline void
1397 arc_cksum_free(arc_buf_hdr_t *hdr)
1398 {
1399 	ASSERT(HDR_HAS_L1HDR(hdr));
1400 
1401 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1402 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1403 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1404 		hdr->b_l1hdr.b_freeze_cksum = NULL;
1405 	}
1406 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1407 }
1408 
1409 /*
1410  * Return true iff at least one of the bufs on hdr is not compressed.
1411  * Encrypted buffers count as compressed.
1412  */
1413 static boolean_t
1414 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1415 {
1416 	ASSERT(hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY_OR_LOCKED(hdr));
1417 
1418 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1419 		if (!ARC_BUF_COMPRESSED(b)) {
1420 			return (B_TRUE);
1421 		}
1422 	}
1423 	return (B_FALSE);
1424 }
1425 
1426 
1427 /*
1428  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1429  * matches the checksum that is stored in the hdr. If there is no checksum,
1430  * or if the buf is compressed, this is a no-op.
1431  */
1432 static void
1433 arc_cksum_verify(arc_buf_t *buf)
1434 {
1435 	arc_buf_hdr_t *hdr = buf->b_hdr;
1436 	zio_cksum_t zc;
1437 
1438 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1439 		return;
1440 
1441 	if (ARC_BUF_COMPRESSED(buf))
1442 		return;
1443 
1444 	ASSERT(HDR_HAS_L1HDR(hdr));
1445 
1446 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1447 
1448 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1449 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1450 		return;
1451 	}
1452 
1453 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1454 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1455 		panic("buffer modified while frozen!");
1456 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1457 }
1458 
1459 /*
1460  * This function makes the assumption that data stored in the L2ARC
1461  * will be transformed exactly as it is in the main pool. Because of
1462  * this we can verify the checksum against the reading process's bp.
1463  */
1464 static boolean_t
1465 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1466 {
1467 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1468 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1469 
1470 	/*
1471 	 * Block pointers always store the checksum for the logical data.
1472 	 * If the block pointer has the gang bit set, then the checksum
1473 	 * it represents is for the reconstituted data and not for an
1474 	 * individual gang member. The zio pipeline, however, must be able to
1475 	 * determine the checksum of each of the gang constituents so it
1476 	 * treats the checksum comparison differently than what we need
1477 	 * for l2arc blocks. This prevents us from using the
1478 	 * zio_checksum_error() interface directly. Instead we must call the
1479 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1480 	 * generated using the correct checksum algorithm and accounts for the
1481 	 * logical I/O size and not just a gang fragment.
1482 	 */
1483 	return (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1484 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1485 	    zio->io_offset, NULL) == 0);
1486 }
1487 
1488 /*
1489  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1490  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1491  * isn't modified later on. If buf is compressed or there is already a checksum
1492  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1493  */
1494 static void
1495 arc_cksum_compute(arc_buf_t *buf)
1496 {
1497 	arc_buf_hdr_t *hdr = buf->b_hdr;
1498 
1499 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1500 		return;
1501 
1502 	ASSERT(HDR_HAS_L1HDR(hdr));
1503 
1504 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1505 	if (hdr->b_l1hdr.b_freeze_cksum != NULL || ARC_BUF_COMPRESSED(buf)) {
1506 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1507 		return;
1508 	}
1509 
1510 	ASSERT(!ARC_BUF_ENCRYPTED(buf));
1511 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1512 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1513 	    KM_SLEEP);
1514 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1515 	    hdr->b_l1hdr.b_freeze_cksum);
1516 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1517 	arc_buf_watch(buf);
1518 }
1519 
1520 #ifndef _KERNEL
1521 void
1522 arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1523 {
1524 	(void) sig, (void) unused;
1525 	panic("Got SIGSEGV at address: 0x%lx\n", (long)si->si_addr);
1526 }
1527 #endif
1528 
1529 static void
1530 arc_buf_unwatch(arc_buf_t *buf)
1531 {
1532 #ifndef _KERNEL
1533 	if (arc_watch) {
1534 		ASSERT0(mprotect(buf->b_data, arc_buf_size(buf),
1535 		    PROT_READ | PROT_WRITE));
1536 	}
1537 #else
1538 	(void) buf;
1539 #endif
1540 }
1541 
1542 static void
1543 arc_buf_watch(arc_buf_t *buf)
1544 {
1545 #ifndef _KERNEL
1546 	if (arc_watch)
1547 		ASSERT0(mprotect(buf->b_data, arc_buf_size(buf),
1548 		    PROT_READ));
1549 #else
1550 	(void) buf;
1551 #endif
1552 }
1553 
1554 static arc_buf_contents_t
1555 arc_buf_type(arc_buf_hdr_t *hdr)
1556 {
1557 	arc_buf_contents_t type;
1558 	if (HDR_ISTYPE_METADATA(hdr)) {
1559 		type = ARC_BUFC_METADATA;
1560 	} else {
1561 		type = ARC_BUFC_DATA;
1562 	}
1563 	VERIFY3U(hdr->b_type, ==, type);
1564 	return (type);
1565 }
1566 
1567 boolean_t
1568 arc_is_metadata(arc_buf_t *buf)
1569 {
1570 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1571 }
1572 
1573 static uint32_t
1574 arc_bufc_to_flags(arc_buf_contents_t type)
1575 {
1576 	switch (type) {
1577 	case ARC_BUFC_DATA:
1578 		/* metadata field is 0 if buffer contains normal data */
1579 		return (0);
1580 	case ARC_BUFC_METADATA:
1581 		return (ARC_FLAG_BUFC_METADATA);
1582 	default:
1583 		break;
1584 	}
1585 	panic("undefined ARC buffer type!");
1586 	return ((uint32_t)-1);
1587 }
1588 
1589 void
1590 arc_buf_thaw(arc_buf_t *buf)
1591 {
1592 	arc_buf_hdr_t *hdr = buf->b_hdr;
1593 
1594 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1595 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1596 
1597 	arc_cksum_verify(buf);
1598 
1599 	/*
1600 	 * Compressed buffers do not manipulate the b_freeze_cksum.
1601 	 */
1602 	if (ARC_BUF_COMPRESSED(buf))
1603 		return;
1604 
1605 	ASSERT(HDR_HAS_L1HDR(hdr));
1606 	arc_cksum_free(hdr);
1607 	arc_buf_unwatch(buf);
1608 }
1609 
1610 void
1611 arc_buf_freeze(arc_buf_t *buf)
1612 {
1613 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1614 		return;
1615 
1616 	if (ARC_BUF_COMPRESSED(buf))
1617 		return;
1618 
1619 	ASSERT(HDR_HAS_L1HDR(buf->b_hdr));
1620 	arc_cksum_compute(buf);
1621 }
1622 
1623 /*
1624  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1625  * the following functions should be used to ensure that the flags are
1626  * updated in a thread-safe way. When manipulating the flags either
1627  * the hash_lock must be held or the hdr must be undiscoverable. This
1628  * ensures that we're not racing with any other threads when updating
1629  * the flags.
1630  */
1631 static inline void
1632 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1633 {
1634 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1635 	hdr->b_flags |= flags;
1636 }
1637 
1638 static inline void
1639 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1640 {
1641 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1642 	hdr->b_flags &= ~flags;
1643 }
1644 
1645 /*
1646  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1647  * done in a special way since we have to clear and set bits
1648  * at the same time. Consumers that wish to set the compression bits
1649  * must use this function to ensure that the flags are updated in
1650  * thread-safe manner.
1651  */
1652 static void
1653 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1654 {
1655 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1656 
1657 	/*
1658 	 * Holes and embedded blocks will always have a psize = 0 so
1659 	 * we ignore the compression of the blkptr and set the
1660 	 * want to uncompress them. Mark them as uncompressed.
1661 	 */
1662 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1663 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1664 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1665 	} else {
1666 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1667 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1668 	}
1669 
1670 	HDR_SET_COMPRESS(hdr, cmp);
1671 	ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1672 }
1673 
1674 /*
1675  * Looks for another buf on the same hdr which has the data decompressed, copies
1676  * from it, and returns true. If no such buf exists, returns false.
1677  */
1678 static boolean_t
1679 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
1680 {
1681 	arc_buf_hdr_t *hdr = buf->b_hdr;
1682 	boolean_t copied = B_FALSE;
1683 
1684 	ASSERT(HDR_HAS_L1HDR(hdr));
1685 	ASSERT3P(buf->b_data, !=, NULL);
1686 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1687 
1688 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
1689 	    from = from->b_next) {
1690 		/* can't use our own data buffer */
1691 		if (from == buf) {
1692 			continue;
1693 		}
1694 
1695 		if (!ARC_BUF_COMPRESSED(from)) {
1696 			memcpy(buf->b_data, from->b_data, arc_buf_size(buf));
1697 			copied = B_TRUE;
1698 			break;
1699 		}
1700 	}
1701 
1702 	/*
1703 	 * There were no decompressed bufs, so there should not be a
1704 	 * checksum on the hdr either.
1705 	 */
1706 	if (zfs_flags & ZFS_DEBUG_MODIFY)
1707 		EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
1708 
1709 	return (copied);
1710 }
1711 
1712 /*
1713  * Allocates an ARC buf header that's in an evicted & L2-cached state.
1714  * This is used during l2arc reconstruction to make empty ARC buffers
1715  * which circumvent the regular disk->arc->l2arc path and instead come
1716  * into being in the reverse order, i.e. l2arc->arc.
1717  */
1718 static arc_buf_hdr_t *
1719 arc_buf_alloc_l2only(size_t size, arc_buf_contents_t type, l2arc_dev_t *dev,
1720     dva_t dva, uint64_t daddr, int32_t psize, uint64_t birth,
1721     enum zio_compress compress, uint8_t complevel, boolean_t protected,
1722     boolean_t prefetch, arc_state_type_t arcs_state)
1723 {
1724 	arc_buf_hdr_t	*hdr;
1725 
1726 	ASSERT(size != 0);
1727 	hdr = kmem_cache_alloc(hdr_l2only_cache, KM_SLEEP);
1728 	hdr->b_birth = birth;
1729 	hdr->b_type = type;
1730 	hdr->b_flags = 0;
1731 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L2HDR);
1732 	HDR_SET_LSIZE(hdr, size);
1733 	HDR_SET_PSIZE(hdr, psize);
1734 	arc_hdr_set_compress(hdr, compress);
1735 	hdr->b_complevel = complevel;
1736 	if (protected)
1737 		arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
1738 	if (prefetch)
1739 		arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
1740 	hdr->b_spa = spa_load_guid(dev->l2ad_vdev->vdev_spa);
1741 
1742 	hdr->b_dva = dva;
1743 
1744 	hdr->b_l2hdr.b_dev = dev;
1745 	hdr->b_l2hdr.b_daddr = daddr;
1746 	hdr->b_l2hdr.b_arcs_state = arcs_state;
1747 
1748 	return (hdr);
1749 }
1750 
1751 /*
1752  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
1753  */
1754 static uint64_t
1755 arc_hdr_size(arc_buf_hdr_t *hdr)
1756 {
1757 	uint64_t size;
1758 
1759 	if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
1760 	    HDR_GET_PSIZE(hdr) > 0) {
1761 		size = HDR_GET_PSIZE(hdr);
1762 	} else {
1763 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
1764 		size = HDR_GET_LSIZE(hdr);
1765 	}
1766 	return (size);
1767 }
1768 
1769 static int
1770 arc_hdr_authenticate(arc_buf_hdr_t *hdr, spa_t *spa, uint64_t dsobj)
1771 {
1772 	int ret;
1773 	uint64_t csize;
1774 	uint64_t lsize = HDR_GET_LSIZE(hdr);
1775 	uint64_t psize = HDR_GET_PSIZE(hdr);
1776 	void *tmpbuf = NULL;
1777 	abd_t *abd = hdr->b_l1hdr.b_pabd;
1778 
1779 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1780 	ASSERT(HDR_AUTHENTICATED(hdr));
1781 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1782 
1783 	/*
1784 	 * The MAC is calculated on the compressed data that is stored on disk.
1785 	 * However, if compressed arc is disabled we will only have the
1786 	 * decompressed data available to us now. Compress it into a temporary
1787 	 * abd so we can verify the MAC. The performance overhead of this will
1788 	 * be relatively low, since most objects in an encrypted objset will
1789 	 * be encrypted (instead of authenticated) anyway.
1790 	 */
1791 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1792 	    !HDR_COMPRESSION_ENABLED(hdr)) {
1793 		tmpbuf = zio_buf_alloc(lsize);
1794 		abd = abd_get_from_buf(tmpbuf, lsize);
1795 		abd_take_ownership_of_buf(abd, B_TRUE);
1796 		csize = zio_compress_data(HDR_GET_COMPRESS(hdr),
1797 		    hdr->b_l1hdr.b_pabd, tmpbuf, lsize, hdr->b_complevel);
1798 		ASSERT3U(csize, <=, psize);
1799 		abd_zero_off(abd, csize, psize - csize);
1800 	}
1801 
1802 	/*
1803 	 * Authentication is best effort. We authenticate whenever the key is
1804 	 * available. If we succeed we clear ARC_FLAG_NOAUTH.
1805 	 */
1806 	if (hdr->b_crypt_hdr.b_ot == DMU_OT_OBJSET) {
1807 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1808 		ASSERT3U(lsize, ==, psize);
1809 		ret = spa_do_crypt_objset_mac_abd(B_FALSE, spa, dsobj, abd,
1810 		    psize, hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
1811 	} else {
1812 		ret = spa_do_crypt_mac_abd(B_FALSE, spa, dsobj, abd, psize,
1813 		    hdr->b_crypt_hdr.b_mac);
1814 	}
1815 
1816 	if (ret == 0)
1817 		arc_hdr_clear_flags(hdr, ARC_FLAG_NOAUTH);
1818 	else if (ret != ENOENT)
1819 		goto error;
1820 
1821 	if (tmpbuf != NULL)
1822 		abd_free(abd);
1823 
1824 	return (0);
1825 
1826 error:
1827 	if (tmpbuf != NULL)
1828 		abd_free(abd);
1829 
1830 	return (ret);
1831 }
1832 
1833 /*
1834  * This function will take a header that only has raw encrypted data in
1835  * b_crypt_hdr.b_rabd and decrypt it into a new buffer which is stored in
1836  * b_l1hdr.b_pabd. If designated in the header flags, this function will
1837  * also decompress the data.
1838  */
1839 static int
1840 arc_hdr_decrypt(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb)
1841 {
1842 	int ret;
1843 	abd_t *cabd = NULL;
1844 	void *tmp = NULL;
1845 	boolean_t no_crypt = B_FALSE;
1846 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
1847 
1848 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1849 	ASSERT(HDR_ENCRYPTED(hdr));
1850 
1851 	arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
1852 
1853 	ret = spa_do_crypt_abd(B_FALSE, spa, zb, hdr->b_crypt_hdr.b_ot,
1854 	    B_FALSE, bswap, hdr->b_crypt_hdr.b_salt, hdr->b_crypt_hdr.b_iv,
1855 	    hdr->b_crypt_hdr.b_mac, HDR_GET_PSIZE(hdr), hdr->b_l1hdr.b_pabd,
1856 	    hdr->b_crypt_hdr.b_rabd, &no_crypt);
1857 	if (ret != 0)
1858 		goto error;
1859 
1860 	if (no_crypt) {
1861 		abd_copy(hdr->b_l1hdr.b_pabd, hdr->b_crypt_hdr.b_rabd,
1862 		    HDR_GET_PSIZE(hdr));
1863 	}
1864 
1865 	/*
1866 	 * If this header has disabled arc compression but the b_pabd is
1867 	 * compressed after decrypting it, we need to decompress the newly
1868 	 * decrypted data.
1869 	 */
1870 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
1871 	    !HDR_COMPRESSION_ENABLED(hdr)) {
1872 		/*
1873 		 * We want to make sure that we are correctly honoring the
1874 		 * zfs_abd_scatter_enabled setting, so we allocate an abd here
1875 		 * and then loan a buffer from it, rather than allocating a
1876 		 * linear buffer and wrapping it in an abd later.
1877 		 */
1878 		cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
1879 		    ARC_HDR_DO_ADAPT);
1880 		tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
1881 
1882 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1883 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
1884 		    HDR_GET_LSIZE(hdr), &hdr->b_complevel);
1885 		if (ret != 0) {
1886 			abd_return_buf(cabd, tmp, arc_hdr_size(hdr));
1887 			goto error;
1888 		}
1889 
1890 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
1891 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
1892 		    arc_hdr_size(hdr), hdr);
1893 		hdr->b_l1hdr.b_pabd = cabd;
1894 	}
1895 
1896 	return (0);
1897 
1898 error:
1899 	arc_hdr_free_abd(hdr, B_FALSE);
1900 	if (cabd != NULL)
1901 		arc_free_data_buf(hdr, cabd, arc_hdr_size(hdr), hdr);
1902 
1903 	return (ret);
1904 }
1905 
1906 /*
1907  * This function is called during arc_buf_fill() to prepare the header's
1908  * abd plaintext pointer for use. This involves authenticated protected
1909  * data and decrypting encrypted data into the plaintext abd.
1910  */
1911 static int
1912 arc_fill_hdr_crypt(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, spa_t *spa,
1913     const zbookmark_phys_t *zb, boolean_t noauth)
1914 {
1915 	int ret;
1916 
1917 	ASSERT(HDR_PROTECTED(hdr));
1918 
1919 	if (hash_lock != NULL)
1920 		mutex_enter(hash_lock);
1921 
1922 	if (HDR_NOAUTH(hdr) && !noauth) {
1923 		/*
1924 		 * The caller requested authenticated data but our data has
1925 		 * not been authenticated yet. Verify the MAC now if we can.
1926 		 */
1927 		ret = arc_hdr_authenticate(hdr, spa, zb->zb_objset);
1928 		if (ret != 0)
1929 			goto error;
1930 	} else if (HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd == NULL) {
1931 		/*
1932 		 * If we only have the encrypted version of the data, but the
1933 		 * unencrypted version was requested we take this opportunity
1934 		 * to store the decrypted version in the header for future use.
1935 		 */
1936 		ret = arc_hdr_decrypt(hdr, spa, zb);
1937 		if (ret != 0)
1938 			goto error;
1939 	}
1940 
1941 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1942 
1943 	if (hash_lock != NULL)
1944 		mutex_exit(hash_lock);
1945 
1946 	return (0);
1947 
1948 error:
1949 	if (hash_lock != NULL)
1950 		mutex_exit(hash_lock);
1951 
1952 	return (ret);
1953 }
1954 
1955 /*
1956  * This function is used by the dbuf code to decrypt bonus buffers in place.
1957  * The dbuf code itself doesn't have any locking for decrypting a shared dnode
1958  * block, so we use the hash lock here to protect against concurrent calls to
1959  * arc_buf_fill().
1960  */
1961 static void
1962 arc_buf_untransform_in_place(arc_buf_t *buf)
1963 {
1964 	arc_buf_hdr_t *hdr = buf->b_hdr;
1965 
1966 	ASSERT(HDR_ENCRYPTED(hdr));
1967 	ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
1968 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
1969 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
1970 
1971 	zio_crypt_copy_dnode_bonus(hdr->b_l1hdr.b_pabd, buf->b_data,
1972 	    arc_buf_size(buf));
1973 	buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
1974 	buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
1975 	hdr->b_crypt_hdr.b_ebufcnt -= 1;
1976 }
1977 
1978 /*
1979  * Given a buf that has a data buffer attached to it, this function will
1980  * efficiently fill the buf with data of the specified compression setting from
1981  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
1982  * are already sharing a data buf, no copy is performed.
1983  *
1984  * If the buf is marked as compressed but uncompressed data was requested, this
1985  * will allocate a new data buffer for the buf, remove that flag, and fill the
1986  * buf with uncompressed data. You can't request a compressed buf on a hdr with
1987  * uncompressed data, and (since we haven't added support for it yet) if you
1988  * want compressed data your buf must already be marked as compressed and have
1989  * the correct-sized data buffer.
1990  */
1991 static int
1992 arc_buf_fill(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
1993     arc_fill_flags_t flags)
1994 {
1995 	int error = 0;
1996 	arc_buf_hdr_t *hdr = buf->b_hdr;
1997 	boolean_t hdr_compressed =
1998 	    (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
1999 	boolean_t compressed = (flags & ARC_FILL_COMPRESSED) != 0;
2000 	boolean_t encrypted = (flags & ARC_FILL_ENCRYPTED) != 0;
2001 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2002 	kmutex_t *hash_lock = (flags & ARC_FILL_LOCKED) ? NULL : HDR_LOCK(hdr);
2003 
2004 	ASSERT3P(buf->b_data, !=, NULL);
2005 	IMPLY(compressed, hdr_compressed || ARC_BUF_ENCRYPTED(buf));
2006 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2007 	IMPLY(encrypted, HDR_ENCRYPTED(hdr));
2008 	IMPLY(encrypted, ARC_BUF_ENCRYPTED(buf));
2009 	IMPLY(encrypted, ARC_BUF_COMPRESSED(buf));
2010 	IMPLY(encrypted, !ARC_BUF_SHARED(buf));
2011 
2012 	/*
2013 	 * If the caller wanted encrypted data we just need to copy it from
2014 	 * b_rabd and potentially byteswap it. We won't be able to do any
2015 	 * further transforms on it.
2016 	 */
2017 	if (encrypted) {
2018 		ASSERT(HDR_HAS_RABD(hdr));
2019 		abd_copy_to_buf(buf->b_data, hdr->b_crypt_hdr.b_rabd,
2020 		    HDR_GET_PSIZE(hdr));
2021 		goto byteswap;
2022 	}
2023 
2024 	/*
2025 	 * Adjust encrypted and authenticated headers to accommodate
2026 	 * the request if needed. Dnode blocks (ARC_FILL_IN_PLACE) are
2027 	 * allowed to fail decryption due to keys not being loaded
2028 	 * without being marked as an IO error.
2029 	 */
2030 	if (HDR_PROTECTED(hdr)) {
2031 		error = arc_fill_hdr_crypt(hdr, hash_lock, spa,
2032 		    zb, !!(flags & ARC_FILL_NOAUTH));
2033 		if (error == EACCES && (flags & ARC_FILL_IN_PLACE) != 0) {
2034 			return (error);
2035 		} else if (error != 0) {
2036 			if (hash_lock != NULL)
2037 				mutex_enter(hash_lock);
2038 			arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
2039 			if (hash_lock != NULL)
2040 				mutex_exit(hash_lock);
2041 			return (error);
2042 		}
2043 	}
2044 
2045 	/*
2046 	 * There is a special case here for dnode blocks which are
2047 	 * decrypting their bonus buffers. These blocks may request to
2048 	 * be decrypted in-place. This is necessary because there may
2049 	 * be many dnodes pointing into this buffer and there is
2050 	 * currently no method to synchronize replacing the backing
2051 	 * b_data buffer and updating all of the pointers. Here we use
2052 	 * the hash lock to ensure there are no races. If the need
2053 	 * arises for other types to be decrypted in-place, they must
2054 	 * add handling here as well.
2055 	 */
2056 	if ((flags & ARC_FILL_IN_PLACE) != 0) {
2057 		ASSERT(!hdr_compressed);
2058 		ASSERT(!compressed);
2059 		ASSERT(!encrypted);
2060 
2061 		if (HDR_ENCRYPTED(hdr) && ARC_BUF_ENCRYPTED(buf)) {
2062 			ASSERT3U(hdr->b_crypt_hdr.b_ot, ==, DMU_OT_DNODE);
2063 
2064 			if (hash_lock != NULL)
2065 				mutex_enter(hash_lock);
2066 			arc_buf_untransform_in_place(buf);
2067 			if (hash_lock != NULL)
2068 				mutex_exit(hash_lock);
2069 
2070 			/* Compute the hdr's checksum if necessary */
2071 			arc_cksum_compute(buf);
2072 		}
2073 
2074 		return (0);
2075 	}
2076 
2077 	if (hdr_compressed == compressed) {
2078 		if (!arc_buf_is_shared(buf)) {
2079 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
2080 			    arc_buf_size(buf));
2081 		}
2082 	} else {
2083 		ASSERT(hdr_compressed);
2084 		ASSERT(!compressed);
2085 
2086 		/*
2087 		 * If the buf is sharing its data with the hdr, unlink it and
2088 		 * allocate a new data buffer for the buf.
2089 		 */
2090 		if (arc_buf_is_shared(buf)) {
2091 			ASSERT(ARC_BUF_COMPRESSED(buf));
2092 
2093 			/* We need to give the buf its own b_data */
2094 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2095 			buf->b_data =
2096 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2097 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2098 
2099 			/* Previously overhead was 0; just add new overhead */
2100 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2101 		} else if (ARC_BUF_COMPRESSED(buf)) {
2102 			/* We need to reallocate the buf's b_data */
2103 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2104 			    buf);
2105 			buf->b_data =
2106 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2107 
2108 			/* We increased the size of b_data; update overhead */
2109 			ARCSTAT_INCR(arcstat_overhead_size,
2110 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2111 		}
2112 
2113 		/*
2114 		 * Regardless of the buf's previous compression settings, it
2115 		 * should not be compressed at the end of this function.
2116 		 */
2117 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2118 
2119 		/*
2120 		 * Try copying the data from another buf which already has a
2121 		 * decompressed version. If that's not possible, it's time to
2122 		 * bite the bullet and decompress the data from the hdr.
2123 		 */
2124 		if (arc_buf_try_copy_decompressed_data(buf)) {
2125 			/* Skip byteswapping and checksumming (already done) */
2126 			return (0);
2127 		} else {
2128 			error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2129 			    hdr->b_l1hdr.b_pabd, buf->b_data,
2130 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr),
2131 			    &hdr->b_complevel);
2132 
2133 			/*
2134 			 * Absent hardware errors or software bugs, this should
2135 			 * be impossible, but log it anyway so we can debug it.
2136 			 */
2137 			if (error != 0) {
2138 				zfs_dbgmsg(
2139 				    "hdr %px, compress %d, psize %d, lsize %d",
2140 				    hdr, arc_hdr_get_compress(hdr),
2141 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2142 				if (hash_lock != NULL)
2143 					mutex_enter(hash_lock);
2144 				arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
2145 				if (hash_lock != NULL)
2146 					mutex_exit(hash_lock);
2147 				return (SET_ERROR(EIO));
2148 			}
2149 		}
2150 	}
2151 
2152 byteswap:
2153 	/* Byteswap the buf's data if necessary */
2154 	if (bswap != DMU_BSWAP_NUMFUNCS) {
2155 		ASSERT(!HDR_SHARED_DATA(hdr));
2156 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2157 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2158 	}
2159 
2160 	/* Compute the hdr's checksum if necessary */
2161 	arc_cksum_compute(buf);
2162 
2163 	return (0);
2164 }
2165 
2166 /*
2167  * If this function is being called to decrypt an encrypted buffer or verify an
2168  * authenticated one, the key must be loaded and a mapping must be made
2169  * available in the keystore via spa_keystore_create_mapping() or one of its
2170  * callers.
2171  */
2172 int
2173 arc_untransform(arc_buf_t *buf, spa_t *spa, const zbookmark_phys_t *zb,
2174     boolean_t in_place)
2175 {
2176 	int ret;
2177 	arc_fill_flags_t flags = 0;
2178 
2179 	if (in_place)
2180 		flags |= ARC_FILL_IN_PLACE;
2181 
2182 	ret = arc_buf_fill(buf, spa, zb, flags);
2183 	if (ret == ECKSUM) {
2184 		/*
2185 		 * Convert authentication and decryption errors to EIO
2186 		 * (and generate an ereport) before leaving the ARC.
2187 		 */
2188 		ret = SET_ERROR(EIO);
2189 		spa_log_error(spa, zb);
2190 		(void) zfs_ereport_post(FM_EREPORT_ZFS_AUTHENTICATION,
2191 		    spa, NULL, zb, NULL, 0);
2192 	}
2193 
2194 	return (ret);
2195 }
2196 
2197 /*
2198  * Increment the amount of evictable space in the arc_state_t's refcount.
2199  * We account for the space used by the hdr and the arc buf individually
2200  * so that we can add and remove them from the refcount individually.
2201  */
2202 static void
2203 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2204 {
2205 	arc_buf_contents_t type = arc_buf_type(hdr);
2206 
2207 	ASSERT(HDR_HAS_L1HDR(hdr));
2208 
2209 	if (GHOST_STATE(state)) {
2210 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2211 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2212 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2213 		ASSERT(!HDR_HAS_RABD(hdr));
2214 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2215 		    HDR_GET_LSIZE(hdr), hdr);
2216 		return;
2217 	}
2218 
2219 	if (hdr->b_l1hdr.b_pabd != NULL) {
2220 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2221 		    arc_hdr_size(hdr), hdr);
2222 	}
2223 	if (HDR_HAS_RABD(hdr)) {
2224 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2225 		    HDR_GET_PSIZE(hdr), hdr);
2226 	}
2227 
2228 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2229 	    buf = buf->b_next) {
2230 		if (arc_buf_is_shared(buf))
2231 			continue;
2232 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2233 		    arc_buf_size(buf), buf);
2234 	}
2235 }
2236 
2237 /*
2238  * Decrement the amount of evictable space in the arc_state_t's refcount.
2239  * We account for the space used by the hdr and the arc buf individually
2240  * so that we can add and remove them from the refcount individually.
2241  */
2242 static void
2243 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2244 {
2245 	arc_buf_contents_t type = arc_buf_type(hdr);
2246 
2247 	ASSERT(HDR_HAS_L1HDR(hdr));
2248 
2249 	if (GHOST_STATE(state)) {
2250 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2251 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2252 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2253 		ASSERT(!HDR_HAS_RABD(hdr));
2254 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2255 		    HDR_GET_LSIZE(hdr), hdr);
2256 		return;
2257 	}
2258 
2259 	if (hdr->b_l1hdr.b_pabd != NULL) {
2260 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2261 		    arc_hdr_size(hdr), hdr);
2262 	}
2263 	if (HDR_HAS_RABD(hdr)) {
2264 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2265 		    HDR_GET_PSIZE(hdr), hdr);
2266 	}
2267 
2268 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2269 	    buf = buf->b_next) {
2270 		if (arc_buf_is_shared(buf))
2271 			continue;
2272 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2273 		    arc_buf_size(buf), buf);
2274 	}
2275 }
2276 
2277 /*
2278  * Add a reference to this hdr indicating that someone is actively
2279  * referencing that memory. When the refcount transitions from 0 to 1,
2280  * we remove it from the respective arc_state_t list to indicate that
2281  * it is not evictable.
2282  */
2283 static void
2284 add_reference(arc_buf_hdr_t *hdr, const void *tag)
2285 {
2286 	arc_state_t *state;
2287 
2288 	ASSERT(HDR_HAS_L1HDR(hdr));
2289 	if (!HDR_EMPTY(hdr) && !MUTEX_HELD(HDR_LOCK(hdr))) {
2290 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2291 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2292 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2293 	}
2294 
2295 	state = hdr->b_l1hdr.b_state;
2296 
2297 	if ((zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2298 	    (state != arc_anon)) {
2299 		/* We don't use the L2-only state list. */
2300 		if (state != arc_l2c_only) {
2301 			multilist_remove(&state->arcs_list[arc_buf_type(hdr)],
2302 			    hdr);
2303 			arc_evictable_space_decrement(hdr, state);
2304 		}
2305 		/* remove the prefetch flag if we get a reference */
2306 		if (HDR_HAS_L2HDR(hdr))
2307 			l2arc_hdr_arcstats_decrement_state(hdr);
2308 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2309 		if (HDR_HAS_L2HDR(hdr))
2310 			l2arc_hdr_arcstats_increment_state(hdr);
2311 	}
2312 }
2313 
2314 /*
2315  * Remove a reference from this hdr. When the reference transitions from
2316  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2317  * list making it eligible for eviction.
2318  */
2319 static int
2320 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, const void *tag)
2321 {
2322 	int cnt;
2323 	arc_state_t *state = hdr->b_l1hdr.b_state;
2324 
2325 	ASSERT(HDR_HAS_L1HDR(hdr));
2326 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2327 	ASSERT(!GHOST_STATE(state));
2328 
2329 	/*
2330 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2331 	 * check to prevent usage of the arc_l2c_only list.
2332 	 */
2333 	if (((cnt = zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2334 	    (state != arc_anon)) {
2335 		multilist_insert(&state->arcs_list[arc_buf_type(hdr)], hdr);
2336 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2337 		arc_evictable_space_increment(hdr, state);
2338 	}
2339 	return (cnt);
2340 }
2341 
2342 /*
2343  * Returns detailed information about a specific arc buffer.  When the
2344  * state_index argument is set the function will calculate the arc header
2345  * list position for its arc state.  Since this requires a linear traversal
2346  * callers are strongly encourage not to do this.  However, it can be helpful
2347  * for targeted analysis so the functionality is provided.
2348  */
2349 void
2350 arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
2351 {
2352 	(void) state_index;
2353 	arc_buf_hdr_t *hdr = ab->b_hdr;
2354 	l1arc_buf_hdr_t *l1hdr = NULL;
2355 	l2arc_buf_hdr_t *l2hdr = NULL;
2356 	arc_state_t *state = NULL;
2357 
2358 	memset(abi, 0, sizeof (arc_buf_info_t));
2359 
2360 	if (hdr == NULL)
2361 		return;
2362 
2363 	abi->abi_flags = hdr->b_flags;
2364 
2365 	if (HDR_HAS_L1HDR(hdr)) {
2366 		l1hdr = &hdr->b_l1hdr;
2367 		state = l1hdr->b_state;
2368 	}
2369 	if (HDR_HAS_L2HDR(hdr))
2370 		l2hdr = &hdr->b_l2hdr;
2371 
2372 	if (l1hdr) {
2373 		abi->abi_bufcnt = l1hdr->b_bufcnt;
2374 		abi->abi_access = l1hdr->b_arc_access;
2375 		abi->abi_mru_hits = l1hdr->b_mru_hits;
2376 		abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
2377 		abi->abi_mfu_hits = l1hdr->b_mfu_hits;
2378 		abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
2379 		abi->abi_holds = zfs_refcount_count(&l1hdr->b_refcnt);
2380 	}
2381 
2382 	if (l2hdr) {
2383 		abi->abi_l2arc_dattr = l2hdr->b_daddr;
2384 		abi->abi_l2arc_hits = l2hdr->b_hits;
2385 	}
2386 
2387 	abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
2388 	abi->abi_state_contents = arc_buf_type(hdr);
2389 	abi->abi_size = arc_hdr_size(hdr);
2390 }
2391 
2392 /*
2393  * Move the supplied buffer to the indicated state. The hash lock
2394  * for the buffer must be held by the caller.
2395  */
2396 static void
2397 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2398     kmutex_t *hash_lock)
2399 {
2400 	arc_state_t *old_state;
2401 	int64_t refcnt;
2402 	uint32_t bufcnt;
2403 	boolean_t update_old, update_new;
2404 	arc_buf_contents_t buftype = arc_buf_type(hdr);
2405 
2406 	/*
2407 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2408 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
2409 	 * L1 hdr doesn't always exist when we change state to arc_anon before
2410 	 * destroying a header, in which case reallocating to add the L1 hdr is
2411 	 * pointless.
2412 	 */
2413 	if (HDR_HAS_L1HDR(hdr)) {
2414 		old_state = hdr->b_l1hdr.b_state;
2415 		refcnt = zfs_refcount_count(&hdr->b_l1hdr.b_refcnt);
2416 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2417 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL ||
2418 		    HDR_HAS_RABD(hdr));
2419 	} else {
2420 		old_state = arc_l2c_only;
2421 		refcnt = 0;
2422 		bufcnt = 0;
2423 		update_old = B_FALSE;
2424 	}
2425 	update_new = update_old;
2426 
2427 	ASSERT(MUTEX_HELD(hash_lock));
2428 	ASSERT3P(new_state, !=, old_state);
2429 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2430 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2431 
2432 	/*
2433 	 * If this buffer is evictable, transfer it from the
2434 	 * old state list to the new state list.
2435 	 */
2436 	if (refcnt == 0) {
2437 		if (old_state != arc_anon && old_state != arc_l2c_only) {
2438 			ASSERT(HDR_HAS_L1HDR(hdr));
2439 			multilist_remove(&old_state->arcs_list[buftype], hdr);
2440 
2441 			if (GHOST_STATE(old_state)) {
2442 				ASSERT0(bufcnt);
2443 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2444 				update_old = B_TRUE;
2445 			}
2446 			arc_evictable_space_decrement(hdr, old_state);
2447 		}
2448 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2449 			/*
2450 			 * An L1 header always exists here, since if we're
2451 			 * moving to some L1-cached state (i.e. not l2c_only or
2452 			 * anonymous), we realloc the header to add an L1hdr
2453 			 * beforehand.
2454 			 */
2455 			ASSERT(HDR_HAS_L1HDR(hdr));
2456 			multilist_insert(&new_state->arcs_list[buftype], hdr);
2457 
2458 			if (GHOST_STATE(new_state)) {
2459 				ASSERT0(bufcnt);
2460 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2461 				update_new = B_TRUE;
2462 			}
2463 			arc_evictable_space_increment(hdr, new_state);
2464 		}
2465 	}
2466 
2467 	ASSERT(!HDR_EMPTY(hdr));
2468 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2469 		buf_hash_remove(hdr);
2470 
2471 	/* adjust state sizes (ignore arc_l2c_only) */
2472 
2473 	if (update_new && new_state != arc_l2c_only) {
2474 		ASSERT(HDR_HAS_L1HDR(hdr));
2475 		if (GHOST_STATE(new_state)) {
2476 			ASSERT0(bufcnt);
2477 
2478 			/*
2479 			 * When moving a header to a ghost state, we first
2480 			 * remove all arc buffers. Thus, we'll have a
2481 			 * bufcnt of zero, and no arc buffer to use for
2482 			 * the reference. As a result, we use the arc
2483 			 * header pointer for the reference.
2484 			 */
2485 			(void) zfs_refcount_add_many(&new_state->arcs_size,
2486 			    HDR_GET_LSIZE(hdr), hdr);
2487 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2488 			ASSERT(!HDR_HAS_RABD(hdr));
2489 		} else {
2490 			uint32_t buffers = 0;
2491 
2492 			/*
2493 			 * Each individual buffer holds a unique reference,
2494 			 * thus we must remove each of these references one
2495 			 * at a time.
2496 			 */
2497 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2498 			    buf = buf->b_next) {
2499 				ASSERT3U(bufcnt, !=, 0);
2500 				buffers++;
2501 
2502 				/*
2503 				 * When the arc_buf_t is sharing the data
2504 				 * block with the hdr, the owner of the
2505 				 * reference belongs to the hdr. Only
2506 				 * add to the refcount if the arc_buf_t is
2507 				 * not shared.
2508 				 */
2509 				if (arc_buf_is_shared(buf))
2510 					continue;
2511 
2512 				(void) zfs_refcount_add_many(
2513 				    &new_state->arcs_size,
2514 				    arc_buf_size(buf), buf);
2515 			}
2516 			ASSERT3U(bufcnt, ==, buffers);
2517 
2518 			if (hdr->b_l1hdr.b_pabd != NULL) {
2519 				(void) zfs_refcount_add_many(
2520 				    &new_state->arcs_size,
2521 				    arc_hdr_size(hdr), hdr);
2522 			}
2523 
2524 			if (HDR_HAS_RABD(hdr)) {
2525 				(void) zfs_refcount_add_many(
2526 				    &new_state->arcs_size,
2527 				    HDR_GET_PSIZE(hdr), hdr);
2528 			}
2529 		}
2530 	}
2531 
2532 	if (update_old && old_state != arc_l2c_only) {
2533 		ASSERT(HDR_HAS_L1HDR(hdr));
2534 		if (GHOST_STATE(old_state)) {
2535 			ASSERT0(bufcnt);
2536 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2537 			ASSERT(!HDR_HAS_RABD(hdr));
2538 
2539 			/*
2540 			 * When moving a header off of a ghost state,
2541 			 * the header will not contain any arc buffers.
2542 			 * We use the arc header pointer for the reference
2543 			 * which is exactly what we did when we put the
2544 			 * header on the ghost state.
2545 			 */
2546 
2547 			(void) zfs_refcount_remove_many(&old_state->arcs_size,
2548 			    HDR_GET_LSIZE(hdr), hdr);
2549 		} else {
2550 			uint32_t buffers = 0;
2551 
2552 			/*
2553 			 * Each individual buffer holds a unique reference,
2554 			 * thus we must remove each of these references one
2555 			 * at a time.
2556 			 */
2557 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2558 			    buf = buf->b_next) {
2559 				ASSERT3U(bufcnt, !=, 0);
2560 				buffers++;
2561 
2562 				/*
2563 				 * When the arc_buf_t is sharing the data
2564 				 * block with the hdr, the owner of the
2565 				 * reference belongs to the hdr. Only
2566 				 * add to the refcount if the arc_buf_t is
2567 				 * not shared.
2568 				 */
2569 				if (arc_buf_is_shared(buf))
2570 					continue;
2571 
2572 				(void) zfs_refcount_remove_many(
2573 				    &old_state->arcs_size, arc_buf_size(buf),
2574 				    buf);
2575 			}
2576 			ASSERT3U(bufcnt, ==, buffers);
2577 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
2578 			    HDR_HAS_RABD(hdr));
2579 
2580 			if (hdr->b_l1hdr.b_pabd != NULL) {
2581 				(void) zfs_refcount_remove_many(
2582 				    &old_state->arcs_size, arc_hdr_size(hdr),
2583 				    hdr);
2584 			}
2585 
2586 			if (HDR_HAS_RABD(hdr)) {
2587 				(void) zfs_refcount_remove_many(
2588 				    &old_state->arcs_size, HDR_GET_PSIZE(hdr),
2589 				    hdr);
2590 			}
2591 		}
2592 	}
2593 
2594 	if (HDR_HAS_L1HDR(hdr)) {
2595 		hdr->b_l1hdr.b_state = new_state;
2596 
2597 		if (HDR_HAS_L2HDR(hdr) && new_state != arc_l2c_only) {
2598 			l2arc_hdr_arcstats_decrement_state(hdr);
2599 			hdr->b_l2hdr.b_arcs_state = new_state->arcs_state;
2600 			l2arc_hdr_arcstats_increment_state(hdr);
2601 		}
2602 	}
2603 }
2604 
2605 void
2606 arc_space_consume(uint64_t space, arc_space_type_t type)
2607 {
2608 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2609 
2610 	switch (type) {
2611 	default:
2612 		break;
2613 	case ARC_SPACE_DATA:
2614 		ARCSTAT_INCR(arcstat_data_size, space);
2615 		break;
2616 	case ARC_SPACE_META:
2617 		ARCSTAT_INCR(arcstat_metadata_size, space);
2618 		break;
2619 	case ARC_SPACE_BONUS:
2620 		ARCSTAT_INCR(arcstat_bonus_size, space);
2621 		break;
2622 	case ARC_SPACE_DNODE:
2623 		aggsum_add(&arc_sums.arcstat_dnode_size, space);
2624 		break;
2625 	case ARC_SPACE_DBUF:
2626 		ARCSTAT_INCR(arcstat_dbuf_size, space);
2627 		break;
2628 	case ARC_SPACE_HDRS:
2629 		ARCSTAT_INCR(arcstat_hdr_size, space);
2630 		break;
2631 	case ARC_SPACE_L2HDRS:
2632 		aggsum_add(&arc_sums.arcstat_l2_hdr_size, space);
2633 		break;
2634 	case ARC_SPACE_ABD_CHUNK_WASTE:
2635 		/*
2636 		 * Note: this includes space wasted by all scatter ABD's, not
2637 		 * just those allocated by the ARC.  But the vast majority of
2638 		 * scatter ABD's come from the ARC, because other users are
2639 		 * very short-lived.
2640 		 */
2641 		ARCSTAT_INCR(arcstat_abd_chunk_waste_size, space);
2642 		break;
2643 	}
2644 
2645 	if (type != ARC_SPACE_DATA && type != ARC_SPACE_ABD_CHUNK_WASTE)
2646 		aggsum_add(&arc_sums.arcstat_meta_used, space);
2647 
2648 	aggsum_add(&arc_sums.arcstat_size, space);
2649 }
2650 
2651 void
2652 arc_space_return(uint64_t space, arc_space_type_t type)
2653 {
2654 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2655 
2656 	switch (type) {
2657 	default:
2658 		break;
2659 	case ARC_SPACE_DATA:
2660 		ARCSTAT_INCR(arcstat_data_size, -space);
2661 		break;
2662 	case ARC_SPACE_META:
2663 		ARCSTAT_INCR(arcstat_metadata_size, -space);
2664 		break;
2665 	case ARC_SPACE_BONUS:
2666 		ARCSTAT_INCR(arcstat_bonus_size, -space);
2667 		break;
2668 	case ARC_SPACE_DNODE:
2669 		aggsum_add(&arc_sums.arcstat_dnode_size, -space);
2670 		break;
2671 	case ARC_SPACE_DBUF:
2672 		ARCSTAT_INCR(arcstat_dbuf_size, -space);
2673 		break;
2674 	case ARC_SPACE_HDRS:
2675 		ARCSTAT_INCR(arcstat_hdr_size, -space);
2676 		break;
2677 	case ARC_SPACE_L2HDRS:
2678 		aggsum_add(&arc_sums.arcstat_l2_hdr_size, -space);
2679 		break;
2680 	case ARC_SPACE_ABD_CHUNK_WASTE:
2681 		ARCSTAT_INCR(arcstat_abd_chunk_waste_size, -space);
2682 		break;
2683 	}
2684 
2685 	if (type != ARC_SPACE_DATA && type != ARC_SPACE_ABD_CHUNK_WASTE) {
2686 		ASSERT(aggsum_compare(&arc_sums.arcstat_meta_used,
2687 		    space) >= 0);
2688 		ARCSTAT_MAX(arcstat_meta_max,
2689 		    aggsum_upper_bound(&arc_sums.arcstat_meta_used));
2690 		aggsum_add(&arc_sums.arcstat_meta_used, -space);
2691 	}
2692 
2693 	ASSERT(aggsum_compare(&arc_sums.arcstat_size, space) >= 0);
2694 	aggsum_add(&arc_sums.arcstat_size, -space);
2695 }
2696 
2697 /*
2698  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2699  * with the hdr's b_pabd.
2700  */
2701 static boolean_t
2702 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2703 {
2704 	/*
2705 	 * The criteria for sharing a hdr's data are:
2706 	 * 1. the buffer is not encrypted
2707 	 * 2. the hdr's compression matches the buf's compression
2708 	 * 3. the hdr doesn't need to be byteswapped
2709 	 * 4. the hdr isn't already being shared
2710 	 * 5. the buf is either compressed or it is the last buf in the hdr list
2711 	 *
2712 	 * Criterion #5 maintains the invariant that shared uncompressed
2713 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2714 	 * might ask, "if a compressed buf is allocated first, won't that be the
2715 	 * last thing in the list?", but in that case it's impossible to create
2716 	 * a shared uncompressed buf anyway (because the hdr must be compressed
2717 	 * to have the compressed buf). You might also think that #3 is
2718 	 * sufficient to make this guarantee, however it's possible
2719 	 * (specifically in the rare L2ARC write race mentioned in
2720 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2721 	 * is shareable, but wasn't at the time of its allocation. Rather than
2722 	 * allow a new shared uncompressed buf to be created and then shuffle
2723 	 * the list around to make it the last element, this simply disallows
2724 	 * sharing if the new buf isn't the first to be added.
2725 	 */
2726 	ASSERT3P(buf->b_hdr, ==, hdr);
2727 	boolean_t hdr_compressed =
2728 	    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF;
2729 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2730 	return (!ARC_BUF_ENCRYPTED(buf) &&
2731 	    buf_compressed == hdr_compressed &&
2732 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2733 	    !HDR_SHARED_DATA(hdr) &&
2734 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2735 }
2736 
2737 /*
2738  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2739  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2740  * copy was made successfully, or an error code otherwise.
2741  */
2742 static int
2743 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, spa_t *spa, const zbookmark_phys_t *zb,
2744     const void *tag, boolean_t encrypted, boolean_t compressed,
2745     boolean_t noauth, boolean_t fill, arc_buf_t **ret)
2746 {
2747 	arc_buf_t *buf;
2748 	arc_fill_flags_t flags = ARC_FILL_LOCKED;
2749 
2750 	ASSERT(HDR_HAS_L1HDR(hdr));
2751 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2752 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2753 	    hdr->b_type == ARC_BUFC_METADATA);
2754 	ASSERT3P(ret, !=, NULL);
2755 	ASSERT3P(*ret, ==, NULL);
2756 	IMPLY(encrypted, compressed);
2757 
2758 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2759 	buf->b_hdr = hdr;
2760 	buf->b_data = NULL;
2761 	buf->b_next = hdr->b_l1hdr.b_buf;
2762 	buf->b_flags = 0;
2763 
2764 	add_reference(hdr, tag);
2765 
2766 	/*
2767 	 * We're about to change the hdr's b_flags. We must either
2768 	 * hold the hash_lock or be undiscoverable.
2769 	 */
2770 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
2771 
2772 	/*
2773 	 * Only honor requests for compressed bufs if the hdr is actually
2774 	 * compressed. This must be overridden if the buffer is encrypted since
2775 	 * encrypted buffers cannot be decompressed.
2776 	 */
2777 	if (encrypted) {
2778 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2779 		buf->b_flags |= ARC_BUF_FLAG_ENCRYPTED;
2780 		flags |= ARC_FILL_COMPRESSED | ARC_FILL_ENCRYPTED;
2781 	} else if (compressed &&
2782 	    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
2783 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2784 		flags |= ARC_FILL_COMPRESSED;
2785 	}
2786 
2787 	if (noauth) {
2788 		ASSERT0(encrypted);
2789 		flags |= ARC_FILL_NOAUTH;
2790 	}
2791 
2792 	/*
2793 	 * If the hdr's data can be shared then we share the data buffer and
2794 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2795 	 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2796 	 * buffer to store the buf's data.
2797 	 *
2798 	 * There are two additional restrictions here because we're sharing
2799 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2800 	 * actively involved in an L2ARC write, because if this buf is used by
2801 	 * an arc_write() then the hdr's data buffer will be released when the
2802 	 * write completes, even though the L2ARC write might still be using it.
2803 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2804 	 * need to be ABD-aware.  It must be allocated via
2805 	 * zio_[data_]buf_alloc(), not as a page, because we need to be able
2806 	 * to abd_release_ownership_of_buf(), which isn't allowed on "linear
2807 	 * page" buffers because the ABD code needs to handle freeing them
2808 	 * specially.
2809 	 */
2810 	boolean_t can_share = arc_can_share(hdr, buf) &&
2811 	    !HDR_L2_WRITING(hdr) &&
2812 	    hdr->b_l1hdr.b_pabd != NULL &&
2813 	    abd_is_linear(hdr->b_l1hdr.b_pabd) &&
2814 	    !abd_is_linear_page(hdr->b_l1hdr.b_pabd);
2815 
2816 	/* Set up b_data and sharing */
2817 	if (can_share) {
2818 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2819 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2820 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2821 	} else {
2822 		buf->b_data =
2823 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2824 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2825 	}
2826 	VERIFY3P(buf->b_data, !=, NULL);
2827 
2828 	hdr->b_l1hdr.b_buf = buf;
2829 	hdr->b_l1hdr.b_bufcnt += 1;
2830 	if (encrypted)
2831 		hdr->b_crypt_hdr.b_ebufcnt += 1;
2832 
2833 	/*
2834 	 * If the user wants the data from the hdr, we need to either copy or
2835 	 * decompress the data.
2836 	 */
2837 	if (fill) {
2838 		ASSERT3P(zb, !=, NULL);
2839 		return (arc_buf_fill(buf, spa, zb, flags));
2840 	}
2841 
2842 	return (0);
2843 }
2844 
2845 static const char *arc_onloan_tag = "onloan";
2846 
2847 static inline void
2848 arc_loaned_bytes_update(int64_t delta)
2849 {
2850 	atomic_add_64(&arc_loaned_bytes, delta);
2851 
2852 	/* assert that it did not wrap around */
2853 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2854 }
2855 
2856 /*
2857  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2858  * flight data by arc_tempreserve_space() until they are "returned". Loaned
2859  * buffers must be returned to the arc before they can be used by the DMU or
2860  * freed.
2861  */
2862 arc_buf_t *
2863 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2864 {
2865 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2866 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2867 
2868 	arc_loaned_bytes_update(arc_buf_size(buf));
2869 
2870 	return (buf);
2871 }
2872 
2873 arc_buf_t *
2874 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2875     enum zio_compress compression_type, uint8_t complevel)
2876 {
2877 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2878 	    psize, lsize, compression_type, complevel);
2879 
2880 	arc_loaned_bytes_update(arc_buf_size(buf));
2881 
2882 	return (buf);
2883 }
2884 
2885 arc_buf_t *
2886 arc_loan_raw_buf(spa_t *spa, uint64_t dsobj, boolean_t byteorder,
2887     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac,
2888     dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
2889     enum zio_compress compression_type, uint8_t complevel)
2890 {
2891 	arc_buf_t *buf = arc_alloc_raw_buf(spa, arc_onloan_tag, dsobj,
2892 	    byteorder, salt, iv, mac, ot, psize, lsize, compression_type,
2893 	    complevel);
2894 
2895 	atomic_add_64(&arc_loaned_bytes, psize);
2896 	return (buf);
2897 }
2898 
2899 
2900 /*
2901  * Return a loaned arc buffer to the arc.
2902  */
2903 void
2904 arc_return_buf(arc_buf_t *buf, const void *tag)
2905 {
2906 	arc_buf_hdr_t *hdr = buf->b_hdr;
2907 
2908 	ASSERT3P(buf->b_data, !=, NULL);
2909 	ASSERT(HDR_HAS_L1HDR(hdr));
2910 	(void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2911 	(void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2912 
2913 	arc_loaned_bytes_update(-arc_buf_size(buf));
2914 }
2915 
2916 /* Detach an arc_buf from a dbuf (tag) */
2917 void
2918 arc_loan_inuse_buf(arc_buf_t *buf, const void *tag)
2919 {
2920 	arc_buf_hdr_t *hdr = buf->b_hdr;
2921 
2922 	ASSERT3P(buf->b_data, !=, NULL);
2923 	ASSERT(HDR_HAS_L1HDR(hdr));
2924 	(void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2925 	(void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2926 
2927 	arc_loaned_bytes_update(arc_buf_size(buf));
2928 }
2929 
2930 static void
2931 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2932 {
2933 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2934 
2935 	df->l2df_abd = abd;
2936 	df->l2df_size = size;
2937 	df->l2df_type = type;
2938 	mutex_enter(&l2arc_free_on_write_mtx);
2939 	list_insert_head(l2arc_free_on_write, df);
2940 	mutex_exit(&l2arc_free_on_write_mtx);
2941 }
2942 
2943 static void
2944 arc_hdr_free_on_write(arc_buf_hdr_t *hdr, boolean_t free_rdata)
2945 {
2946 	arc_state_t *state = hdr->b_l1hdr.b_state;
2947 	arc_buf_contents_t type = arc_buf_type(hdr);
2948 	uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
2949 
2950 	/* protected by hash lock, if in the hash table */
2951 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2952 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2953 		ASSERT(state != arc_anon && state != arc_l2c_only);
2954 
2955 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2956 		    size, hdr);
2957 	}
2958 	(void) zfs_refcount_remove_many(&state->arcs_size, size, hdr);
2959 	if (type == ARC_BUFC_METADATA) {
2960 		arc_space_return(size, ARC_SPACE_META);
2961 	} else {
2962 		ASSERT(type == ARC_BUFC_DATA);
2963 		arc_space_return(size, ARC_SPACE_DATA);
2964 	}
2965 
2966 	if (free_rdata) {
2967 		l2arc_free_abd_on_write(hdr->b_crypt_hdr.b_rabd, size, type);
2968 	} else {
2969 		l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2970 	}
2971 }
2972 
2973 /*
2974  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2975  * data buffer, we transfer the refcount ownership to the hdr and update
2976  * the appropriate kstats.
2977  */
2978 static void
2979 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2980 {
2981 	ASSERT(arc_can_share(hdr, buf));
2982 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2983 	ASSERT(!ARC_BUF_ENCRYPTED(buf));
2984 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
2985 
2986 	/*
2987 	 * Start sharing the data buffer. We transfer the
2988 	 * refcount ownership to the hdr since it always owns
2989 	 * the refcount whenever an arc_buf_t is shared.
2990 	 */
2991 	zfs_refcount_transfer_ownership_many(&hdr->b_l1hdr.b_state->arcs_size,
2992 	    arc_hdr_size(hdr), buf, hdr);
2993 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
2994 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
2995 	    HDR_ISTYPE_METADATA(hdr));
2996 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2997 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2998 
2999 	/*
3000 	 * Since we've transferred ownership to the hdr we need
3001 	 * to increment its compressed and uncompressed kstats and
3002 	 * decrement the overhead size.
3003 	 */
3004 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3005 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3006 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3007 }
3008 
3009 static void
3010 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3011 {
3012 	ASSERT(arc_buf_is_shared(buf));
3013 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3014 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3015 
3016 	/*
3017 	 * We are no longer sharing this buffer so we need
3018 	 * to transfer its ownership to the rightful owner.
3019 	 */
3020 	zfs_refcount_transfer_ownership_many(&hdr->b_l1hdr.b_state->arcs_size,
3021 	    arc_hdr_size(hdr), hdr, buf);
3022 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3023 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3024 	abd_free(hdr->b_l1hdr.b_pabd);
3025 	hdr->b_l1hdr.b_pabd = NULL;
3026 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3027 
3028 	/*
3029 	 * Since the buffer is no longer shared between
3030 	 * the arc buf and the hdr, count it as overhead.
3031 	 */
3032 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3033 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3034 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3035 }
3036 
3037 /*
3038  * Remove an arc_buf_t from the hdr's buf list and return the last
3039  * arc_buf_t on the list. If no buffers remain on the list then return
3040  * NULL.
3041  */
3042 static arc_buf_t *
3043 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3044 {
3045 	ASSERT(HDR_HAS_L1HDR(hdr));
3046 	ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3047 
3048 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3049 	arc_buf_t *lastbuf = NULL;
3050 
3051 	/*
3052 	 * Remove the buf from the hdr list and locate the last
3053 	 * remaining buffer on the list.
3054 	 */
3055 	while (*bufp != NULL) {
3056 		if (*bufp == buf)
3057 			*bufp = buf->b_next;
3058 
3059 		/*
3060 		 * If we've removed a buffer in the middle of
3061 		 * the list then update the lastbuf and update
3062 		 * bufp.
3063 		 */
3064 		if (*bufp != NULL) {
3065 			lastbuf = *bufp;
3066 			bufp = &(*bufp)->b_next;
3067 		}
3068 	}
3069 	buf->b_next = NULL;
3070 	ASSERT3P(lastbuf, !=, buf);
3071 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
3072 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
3073 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3074 
3075 	return (lastbuf);
3076 }
3077 
3078 /*
3079  * Free up buf->b_data and pull the arc_buf_t off of the arc_buf_hdr_t's
3080  * list and free it.
3081  */
3082 static void
3083 arc_buf_destroy_impl(arc_buf_t *buf)
3084 {
3085 	arc_buf_hdr_t *hdr = buf->b_hdr;
3086 
3087 	/*
3088 	 * Free up the data associated with the buf but only if we're not
3089 	 * sharing this with the hdr. If we are sharing it with the hdr, the
3090 	 * hdr is responsible for doing the free.
3091 	 */
3092 	if (buf->b_data != NULL) {
3093 		/*
3094 		 * We're about to change the hdr's b_flags. We must either
3095 		 * hold the hash_lock or be undiscoverable.
3096 		 */
3097 		ASSERT(HDR_EMPTY_OR_LOCKED(hdr));
3098 
3099 		arc_cksum_verify(buf);
3100 		arc_buf_unwatch(buf);
3101 
3102 		if (arc_buf_is_shared(buf)) {
3103 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3104 		} else {
3105 			uint64_t size = arc_buf_size(buf);
3106 			arc_free_data_buf(hdr, buf->b_data, size, buf);
3107 			ARCSTAT_INCR(arcstat_overhead_size, -size);
3108 		}
3109 		buf->b_data = NULL;
3110 
3111 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3112 		hdr->b_l1hdr.b_bufcnt -= 1;
3113 
3114 		if (ARC_BUF_ENCRYPTED(buf)) {
3115 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
3116 
3117 			/*
3118 			 * If we have no more encrypted buffers and we've
3119 			 * already gotten a copy of the decrypted data we can
3120 			 * free b_rabd to save some space.
3121 			 */
3122 			if (hdr->b_crypt_hdr.b_ebufcnt == 0 &&
3123 			    HDR_HAS_RABD(hdr) && hdr->b_l1hdr.b_pabd != NULL &&
3124 			    !HDR_IO_IN_PROGRESS(hdr)) {
3125 				arc_hdr_free_abd(hdr, B_TRUE);
3126 			}
3127 		}
3128 	}
3129 
3130 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3131 
3132 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3133 		/*
3134 		 * If the current arc_buf_t is sharing its data buffer with the
3135 		 * hdr, then reassign the hdr's b_pabd to share it with the new
3136 		 * buffer at the end of the list. The shared buffer is always
3137 		 * the last one on the hdr's buffer list.
3138 		 *
3139 		 * There is an equivalent case for compressed bufs, but since
3140 		 * they aren't guaranteed to be the last buf in the list and
3141 		 * that is an exceedingly rare case, we just allow that space be
3142 		 * wasted temporarily. We must also be careful not to share
3143 		 * encrypted buffers, since they cannot be shared.
3144 		 */
3145 		if (lastbuf != NULL && !ARC_BUF_ENCRYPTED(lastbuf)) {
3146 			/* Only one buf can be shared at once */
3147 			VERIFY(!arc_buf_is_shared(lastbuf));
3148 			/* hdr is uncompressed so can't have compressed buf */
3149 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3150 
3151 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3152 			arc_hdr_free_abd(hdr, B_FALSE);
3153 
3154 			/*
3155 			 * We must setup a new shared block between the
3156 			 * last buffer and the hdr. The data would have
3157 			 * been allocated by the arc buf so we need to transfer
3158 			 * ownership to the hdr since it's now being shared.
3159 			 */
3160 			arc_share_buf(hdr, lastbuf);
3161 		}
3162 	} else if (HDR_SHARED_DATA(hdr)) {
3163 		/*
3164 		 * Uncompressed shared buffers are always at the end
3165 		 * of the list. Compressed buffers don't have the
3166 		 * same requirements. This makes it hard to
3167 		 * simply assert that the lastbuf is shared so
3168 		 * we rely on the hdr's compression flags to determine
3169 		 * if we have a compressed, shared buffer.
3170 		 */
3171 		ASSERT3P(lastbuf, !=, NULL);
3172 		ASSERT(arc_buf_is_shared(lastbuf) ||
3173 		    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
3174 	}
3175 
3176 	/*
3177 	 * Free the checksum if we're removing the last uncompressed buf from
3178 	 * this hdr.
3179 	 */
3180 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
3181 		arc_cksum_free(hdr);
3182 	}
3183 
3184 	/* clean up the buf */
3185 	buf->b_hdr = NULL;
3186 	kmem_cache_free(buf_cache, buf);
3187 }
3188 
3189 static void
3190 arc_hdr_alloc_abd(arc_buf_hdr_t *hdr, int alloc_flags)
3191 {
3192 	uint64_t size;
3193 	boolean_t alloc_rdata = ((alloc_flags & ARC_HDR_ALLOC_RDATA) != 0);
3194 
3195 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3196 	ASSERT(HDR_HAS_L1HDR(hdr));
3197 	ASSERT(!HDR_SHARED_DATA(hdr) || alloc_rdata);
3198 	IMPLY(alloc_rdata, HDR_PROTECTED(hdr));
3199 
3200 	if (alloc_rdata) {
3201 		size = HDR_GET_PSIZE(hdr);
3202 		ASSERT3P(hdr->b_crypt_hdr.b_rabd, ==, NULL);
3203 		hdr->b_crypt_hdr.b_rabd = arc_get_data_abd(hdr, size, hdr,
3204 		    alloc_flags);
3205 		ASSERT3P(hdr->b_crypt_hdr.b_rabd, !=, NULL);
3206 		ARCSTAT_INCR(arcstat_raw_size, size);
3207 	} else {
3208 		size = arc_hdr_size(hdr);
3209 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3210 		hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, size, hdr,
3211 		    alloc_flags);
3212 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3213 	}
3214 
3215 	ARCSTAT_INCR(arcstat_compressed_size, size);
3216 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3217 }
3218 
3219 static void
3220 arc_hdr_free_abd(arc_buf_hdr_t *hdr, boolean_t free_rdata)
3221 {
3222 	uint64_t size = (free_rdata) ? HDR_GET_PSIZE(hdr) : arc_hdr_size(hdr);
3223 
3224 	ASSERT(HDR_HAS_L1HDR(hdr));
3225 	ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
3226 	IMPLY(free_rdata, HDR_HAS_RABD(hdr));
3227 
3228 	/*
3229 	 * If the hdr is currently being written to the l2arc then
3230 	 * we defer freeing the data by adding it to the l2arc_free_on_write
3231 	 * list. The l2arc will free the data once it's finished
3232 	 * writing it to the l2arc device.
3233 	 */
3234 	if (HDR_L2_WRITING(hdr)) {
3235 		arc_hdr_free_on_write(hdr, free_rdata);
3236 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
3237 	} else if (free_rdata) {
3238 		arc_free_data_abd(hdr, hdr->b_crypt_hdr.b_rabd, size, hdr);
3239 	} else {
3240 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd, size, hdr);
3241 	}
3242 
3243 	if (free_rdata) {
3244 		hdr->b_crypt_hdr.b_rabd = NULL;
3245 		ARCSTAT_INCR(arcstat_raw_size, -size);
3246 	} else {
3247 		hdr->b_l1hdr.b_pabd = NULL;
3248 	}
3249 
3250 	if (hdr->b_l1hdr.b_pabd == NULL && !HDR_HAS_RABD(hdr))
3251 		hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3252 
3253 	ARCSTAT_INCR(arcstat_compressed_size, -size);
3254 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3255 }
3256 
3257 /*
3258  * Allocate empty anonymous ARC header.  The header will get its identity
3259  * assigned and buffers attached later as part of read or write operations.
3260  *
3261  * In case of read arc_read() assigns header its identify (b_dva + b_birth),
3262  * inserts it into ARC hash to become globally visible and allocates physical
3263  * (b_pabd) or raw (b_rabd) ABD buffer to read into from disk.  On disk read
3264  * completion arc_read_done() allocates ARC buffer(s) as needed, potentially
3265  * sharing one of them with the physical ABD buffer.
3266  *
3267  * In case of write arc_alloc_buf() allocates ARC buffer to be filled with
3268  * data.  Then after compression and/or encryption arc_write_ready() allocates
3269  * and fills (or potentially shares) physical (b_pabd) or raw (b_rabd) ABD
3270  * buffer.  On disk write completion arc_write_done() assigns the header its
3271  * new identity (b_dva + b_birth) and inserts into ARC hash.
3272  *
3273  * In case of partial overwrite the old data is read first as described. Then
3274  * arc_release() either allocates new anonymous ARC header and moves the ARC
3275  * buffer to it, or reuses the old ARC header by discarding its identity and
3276  * removing it from ARC hash.  After buffer modification normal write process
3277  * follows as described.
3278  */
3279 static arc_buf_hdr_t *
3280 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3281     boolean_t protected, enum zio_compress compression_type, uint8_t complevel,
3282     arc_buf_contents_t type)
3283 {
3284 	arc_buf_hdr_t *hdr;
3285 
3286 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3287 	if (protected) {
3288 		hdr = kmem_cache_alloc(hdr_full_crypt_cache, KM_PUSHPAGE);
3289 	} else {
3290 		hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3291 	}
3292 
3293 	ASSERT(HDR_EMPTY(hdr));
3294 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3295 	HDR_SET_PSIZE(hdr, psize);
3296 	HDR_SET_LSIZE(hdr, lsize);
3297 	hdr->b_spa = spa;
3298 	hdr->b_type = type;
3299 	hdr->b_flags = 0;
3300 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3301 	arc_hdr_set_compress(hdr, compression_type);
3302 	hdr->b_complevel = complevel;
3303 	if (protected)
3304 		arc_hdr_set_flags(hdr, ARC_FLAG_PROTECTED);
3305 
3306 	hdr->b_l1hdr.b_state = arc_anon;
3307 	hdr->b_l1hdr.b_arc_access = 0;
3308 	hdr->b_l1hdr.b_mru_hits = 0;
3309 	hdr->b_l1hdr.b_mru_ghost_hits = 0;
3310 	hdr->b_l1hdr.b_mfu_hits = 0;
3311 	hdr->b_l1hdr.b_mfu_ghost_hits = 0;
3312 	hdr->b_l1hdr.b_bufcnt = 0;
3313 	hdr->b_l1hdr.b_buf = NULL;
3314 
3315 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3316 
3317 	return (hdr);
3318 }
3319 
3320 /*
3321  * Transition between the two allocation states for the arc_buf_hdr struct.
3322  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3323  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3324  * version is used when a cache buffer is only in the L2ARC in order to reduce
3325  * memory usage.
3326  */
3327 static arc_buf_hdr_t *
3328 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3329 {
3330 	ASSERT(HDR_HAS_L2HDR(hdr));
3331 
3332 	arc_buf_hdr_t *nhdr;
3333 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3334 
3335 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3336 	    (old == hdr_l2only_cache && new == hdr_full_cache));
3337 
3338 	/*
3339 	 * if the caller wanted a new full header and the header is to be
3340 	 * encrypted we will actually allocate the header from the full crypt
3341 	 * cache instead. The same applies to freeing from the old cache.
3342 	 */
3343 	if (HDR_PROTECTED(hdr) && new == hdr_full_cache)
3344 		new = hdr_full_crypt_cache;
3345 	if (HDR_PROTECTED(hdr) && old == hdr_full_cache)
3346 		old = hdr_full_crypt_cache;
3347 
3348 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3349 
3350 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3351 	buf_hash_remove(hdr);
3352 
3353 	memcpy(nhdr, hdr, HDR_L2ONLY_SIZE);
3354 
3355 	if (new == hdr_full_cache || new == hdr_full_crypt_cache) {
3356 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3357 		/*
3358 		 * arc_access and arc_change_state need to be aware that a
3359 		 * header has just come out of L2ARC, so we set its state to
3360 		 * l2c_only even though it's about to change.
3361 		 */
3362 		nhdr->b_l1hdr.b_state = arc_l2c_only;
3363 
3364 		/* Verify previous threads set to NULL before freeing */
3365 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
3366 		ASSERT(!HDR_HAS_RABD(hdr));
3367 	} else {
3368 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3369 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
3370 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3371 
3372 		/*
3373 		 * If we've reached here, We must have been called from
3374 		 * arc_evict_hdr(), as such we should have already been
3375 		 * removed from any ghost list we were previously on
3376 		 * (which protects us from racing with arc_evict_state),
3377 		 * thus no locking is needed during this check.
3378 		 */
3379 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3380 
3381 		/*
3382 		 * A buffer must not be moved into the arc_l2c_only
3383 		 * state if it's not finished being written out to the
3384 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3385 		 * might try to be accessed, even though it was removed.
3386 		 */
3387 		VERIFY(!HDR_L2_WRITING(hdr));
3388 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3389 		ASSERT(!HDR_HAS_RABD(hdr));
3390 
3391 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3392 	}
3393 	/*
3394 	 * The header has been reallocated so we need to re-insert it into any
3395 	 * lists it was on.
3396 	 */
3397 	(void) buf_hash_insert(nhdr, NULL);
3398 
3399 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3400 
3401 	mutex_enter(&dev->l2ad_mtx);
3402 
3403 	/*
3404 	 * We must place the realloc'ed header back into the list at
3405 	 * the same spot. Otherwise, if it's placed earlier in the list,
3406 	 * l2arc_write_buffers() could find it during the function's
3407 	 * write phase, and try to write it out to the l2arc.
3408 	 */
3409 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3410 	list_remove(&dev->l2ad_buflist, hdr);
3411 
3412 	mutex_exit(&dev->l2ad_mtx);
3413 
3414 	/*
3415 	 * Since we're using the pointer address as the tag when
3416 	 * incrementing and decrementing the l2ad_alloc refcount, we
3417 	 * must remove the old pointer (that we're about to destroy) and
3418 	 * add the new pointer to the refcount. Otherwise we'd remove
3419 	 * the wrong pointer address when calling arc_hdr_destroy() later.
3420 	 */
3421 
3422 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
3423 	    arc_hdr_size(hdr), hdr);
3424 	(void) zfs_refcount_add_many(&dev->l2ad_alloc,
3425 	    arc_hdr_size(nhdr), nhdr);
3426 
3427 	buf_discard_identity(hdr);
3428 	kmem_cache_free(old, hdr);
3429 
3430 	return (nhdr);
3431 }
3432 
3433 /*
3434  * This function allows an L1 header to be reallocated as a crypt
3435  * header and vice versa. If we are going to a crypt header, the
3436  * new fields will be zeroed out.
3437  */
3438 static arc_buf_hdr_t *
3439 arc_hdr_realloc_crypt(arc_buf_hdr_t *hdr, boolean_t need_crypt)
3440 {
3441 	arc_buf_hdr_t *nhdr;
3442 	arc_buf_t *buf;
3443 	kmem_cache_t *ncache, *ocache;
3444 
3445 	/*
3446 	 * This function requires that hdr is in the arc_anon state.
3447 	 * Therefore it won't have any L2ARC data for us to worry
3448 	 * about copying.
3449 	 */
3450 	ASSERT(HDR_HAS_L1HDR(hdr));
3451 	ASSERT(!HDR_HAS_L2HDR(hdr));
3452 	ASSERT3U(!!HDR_PROTECTED(hdr), !=, need_crypt);
3453 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3454 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3455 	ASSERT(!list_link_active(&hdr->b_l2hdr.b_l2node));
3456 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3457 
3458 	if (need_crypt) {
3459 		ncache = hdr_full_crypt_cache;
3460 		ocache = hdr_full_cache;
3461 	} else {
3462 		ncache = hdr_full_cache;
3463 		ocache = hdr_full_crypt_cache;
3464 	}
3465 
3466 	nhdr = kmem_cache_alloc(ncache, KM_PUSHPAGE);
3467 
3468 	/*
3469 	 * Copy all members that aren't locks or condvars to the new header.
3470 	 * No lists are pointing to us (as we asserted above), so we don't
3471 	 * need to worry about the list nodes.
3472 	 */
3473 	nhdr->b_dva = hdr->b_dva;
3474 	nhdr->b_birth = hdr->b_birth;
3475 	nhdr->b_type = hdr->b_type;
3476 	nhdr->b_flags = hdr->b_flags;
3477 	nhdr->b_psize = hdr->b_psize;
3478 	nhdr->b_lsize = hdr->b_lsize;
3479 	nhdr->b_spa = hdr->b_spa;
3480 	nhdr->b_l1hdr.b_freeze_cksum = hdr->b_l1hdr.b_freeze_cksum;
3481 	nhdr->b_l1hdr.b_bufcnt = hdr->b_l1hdr.b_bufcnt;
3482 	nhdr->b_l1hdr.b_byteswap = hdr->b_l1hdr.b_byteswap;
3483 	nhdr->b_l1hdr.b_state = hdr->b_l1hdr.b_state;
3484 	nhdr->b_l1hdr.b_arc_access = hdr->b_l1hdr.b_arc_access;
3485 	nhdr->b_l1hdr.b_mru_hits = hdr->b_l1hdr.b_mru_hits;
3486 	nhdr->b_l1hdr.b_mru_ghost_hits = hdr->b_l1hdr.b_mru_ghost_hits;
3487 	nhdr->b_l1hdr.b_mfu_hits = hdr->b_l1hdr.b_mfu_hits;
3488 	nhdr->b_l1hdr.b_mfu_ghost_hits = hdr->b_l1hdr.b_mfu_ghost_hits;
3489 	nhdr->b_l1hdr.b_acb = hdr->b_l1hdr.b_acb;
3490 	nhdr->b_l1hdr.b_pabd = hdr->b_l1hdr.b_pabd;
3491 
3492 	/*
3493 	 * This zfs_refcount_add() exists only to ensure that the individual
3494 	 * arc buffers always point to a header that is referenced, avoiding
3495 	 * a small race condition that could trigger ASSERTs.
3496 	 */
3497 	(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, FTAG);
3498 	nhdr->b_l1hdr.b_buf = hdr->b_l1hdr.b_buf;
3499 	for (buf = nhdr->b_l1hdr.b_buf; buf != NULL; buf = buf->b_next) {
3500 		mutex_enter(&buf->b_evict_lock);
3501 		buf->b_hdr = nhdr;
3502 		mutex_exit(&buf->b_evict_lock);
3503 	}
3504 
3505 	zfs_refcount_transfer(&nhdr->b_l1hdr.b_refcnt, &hdr->b_l1hdr.b_refcnt);
3506 	(void) zfs_refcount_remove(&nhdr->b_l1hdr.b_refcnt, FTAG);
3507 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3508 
3509 	if (need_crypt) {
3510 		arc_hdr_set_flags(nhdr, ARC_FLAG_PROTECTED);
3511 	} else {
3512 		arc_hdr_clear_flags(nhdr, ARC_FLAG_PROTECTED);
3513 	}
3514 
3515 	/* unset all members of the original hdr */
3516 	memset(&hdr->b_dva, 0, sizeof (dva_t));
3517 	hdr->b_birth = 0;
3518 	hdr->b_type = ARC_BUFC_INVALID;
3519 	hdr->b_flags = 0;
3520 	hdr->b_psize = 0;
3521 	hdr->b_lsize = 0;
3522 	hdr->b_spa = 0;
3523 	hdr->b_l1hdr.b_freeze_cksum = NULL;
3524 	hdr->b_l1hdr.b_buf = NULL;
3525 	hdr->b_l1hdr.b_bufcnt = 0;
3526 	hdr->b_l1hdr.b_byteswap = 0;
3527 	hdr->b_l1hdr.b_state = NULL;
3528 	hdr->b_l1hdr.b_arc_access = 0;
3529 	hdr->b_l1hdr.b_mru_hits = 0;
3530 	hdr->b_l1hdr.b_mru_ghost_hits = 0;
3531 	hdr->b_l1hdr.b_mfu_hits = 0;
3532 	hdr->b_l1hdr.b_mfu_ghost_hits = 0;
3533 	hdr->b_l1hdr.b_acb = NULL;
3534 	hdr->b_l1hdr.b_pabd = NULL;
3535 
3536 	if (ocache == hdr_full_crypt_cache) {
3537 		ASSERT(!HDR_HAS_RABD(hdr));
3538 		hdr->b_crypt_hdr.b_ot = DMU_OT_NONE;
3539 		hdr->b_crypt_hdr.b_ebufcnt = 0;
3540 		hdr->b_crypt_hdr.b_dsobj = 0;
3541 		memset(hdr->b_crypt_hdr.b_salt, 0, ZIO_DATA_SALT_LEN);
3542 		memset(hdr->b_crypt_hdr.b_iv, 0, ZIO_DATA_IV_LEN);
3543 		memset(hdr->b_crypt_hdr.b_mac, 0, ZIO_DATA_MAC_LEN);
3544 	}
3545 
3546 	buf_discard_identity(hdr);
3547 	kmem_cache_free(ocache, hdr);
3548 
3549 	return (nhdr);
3550 }
3551 
3552 /*
3553  * This function is used by the send / receive code to convert a newly
3554  * allocated arc_buf_t to one that is suitable for a raw encrypted write. It
3555  * is also used to allow the root objset block to be updated without altering
3556  * its embedded MACs. Both block types will always be uncompressed so we do not
3557  * have to worry about compression type or psize.
3558  */
3559 void
3560 arc_convert_to_raw(arc_buf_t *buf, uint64_t dsobj, boolean_t byteorder,
3561     dmu_object_type_t ot, const uint8_t *salt, const uint8_t *iv,
3562     const uint8_t *mac)
3563 {
3564 	arc_buf_hdr_t *hdr = buf->b_hdr;
3565 
3566 	ASSERT(ot == DMU_OT_DNODE || ot == DMU_OT_OBJSET);
3567 	ASSERT(HDR_HAS_L1HDR(hdr));
3568 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3569 
3570 	buf->b_flags |= (ARC_BUF_FLAG_COMPRESSED | ARC_BUF_FLAG_ENCRYPTED);
3571 	if (!HDR_PROTECTED(hdr))
3572 		hdr = arc_hdr_realloc_crypt(hdr, B_TRUE);
3573 	hdr->b_crypt_hdr.b_dsobj = dsobj;
3574 	hdr->b_crypt_hdr.b_ot = ot;
3575 	hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3576 	    DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3577 	if (!arc_hdr_has_uncompressed_buf(hdr))
3578 		arc_cksum_free(hdr);
3579 
3580 	if (salt != NULL)
3581 		memcpy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
3582 	if (iv != NULL)
3583 		memcpy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
3584 	if (mac != NULL)
3585 		memcpy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
3586 }
3587 
3588 /*
3589  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3590  * The buf is returned thawed since we expect the consumer to modify it.
3591  */
3592 arc_buf_t *
3593 arc_alloc_buf(spa_t *spa, const void *tag, arc_buf_contents_t type,
3594     int32_t size)
3595 {
3596 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3597 	    B_FALSE, ZIO_COMPRESS_OFF, 0, type);
3598 
3599 	arc_buf_t *buf = NULL;
3600 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE, B_FALSE,
3601 	    B_FALSE, B_FALSE, &buf));
3602 	arc_buf_thaw(buf);
3603 
3604 	return (buf);
3605 }
3606 
3607 /*
3608  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3609  * for bufs containing metadata.
3610  */
3611 arc_buf_t *
3612 arc_alloc_compressed_buf(spa_t *spa, const void *tag, uint64_t psize,
3613     uint64_t lsize, enum zio_compress compression_type, uint8_t complevel)
3614 {
3615 	ASSERT3U(lsize, >, 0);
3616 	ASSERT3U(lsize, >=, psize);
3617 	ASSERT3U(compression_type, >, ZIO_COMPRESS_OFF);
3618 	ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3619 
3620 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3621 	    B_FALSE, compression_type, complevel, ARC_BUFC_DATA);
3622 
3623 	arc_buf_t *buf = NULL;
3624 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE,
3625 	    B_TRUE, B_FALSE, B_FALSE, &buf));
3626 	arc_buf_thaw(buf);
3627 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3628 
3629 	/*
3630 	 * To ensure that the hdr has the correct data in it if we call
3631 	 * arc_untransform() on this buf before it's been written to disk,
3632 	 * it's easiest if we just set up sharing between the buf and the hdr.
3633 	 */
3634 	arc_share_buf(hdr, buf);
3635 
3636 	return (buf);
3637 }
3638 
3639 arc_buf_t *
3640 arc_alloc_raw_buf(spa_t *spa, const void *tag, uint64_t dsobj,
3641     boolean_t byteorder, const uint8_t *salt, const uint8_t *iv,
3642     const uint8_t *mac, dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
3643     enum zio_compress compression_type, uint8_t complevel)
3644 {
3645 	arc_buf_hdr_t *hdr;
3646 	arc_buf_t *buf;
3647 	arc_buf_contents_t type = DMU_OT_IS_METADATA(ot) ?
3648 	    ARC_BUFC_METADATA : ARC_BUFC_DATA;
3649 
3650 	ASSERT3U(lsize, >, 0);
3651 	ASSERT3U(lsize, >=, psize);
3652 	ASSERT3U(compression_type, >=, ZIO_COMPRESS_OFF);
3653 	ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3654 
3655 	hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize, B_TRUE,
3656 	    compression_type, complevel, type);
3657 
3658 	hdr->b_crypt_hdr.b_dsobj = dsobj;
3659 	hdr->b_crypt_hdr.b_ot = ot;
3660 	hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3661 	    DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3662 	memcpy(hdr->b_crypt_hdr.b_salt, salt, ZIO_DATA_SALT_LEN);
3663 	memcpy(hdr->b_crypt_hdr.b_iv, iv, ZIO_DATA_IV_LEN);
3664 	memcpy(hdr->b_crypt_hdr.b_mac, mac, ZIO_DATA_MAC_LEN);
3665 
3666 	/*
3667 	 * This buffer will be considered encrypted even if the ot is not an
3668 	 * encrypted type. It will become authenticated instead in
3669 	 * arc_write_ready().
3670 	 */
3671 	buf = NULL;
3672 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_TRUE, B_TRUE,
3673 	    B_FALSE, B_FALSE, &buf));
3674 	arc_buf_thaw(buf);
3675 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3676 
3677 	return (buf);
3678 }
3679 
3680 static void
3681 l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
3682     boolean_t state_only)
3683 {
3684 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3685 	l2arc_dev_t *dev = l2hdr->b_dev;
3686 	uint64_t lsize = HDR_GET_LSIZE(hdr);
3687 	uint64_t psize = HDR_GET_PSIZE(hdr);
3688 	uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
3689 	arc_buf_contents_t type = hdr->b_type;
3690 	int64_t lsize_s;
3691 	int64_t psize_s;
3692 	int64_t asize_s;
3693 
3694 	if (incr) {
3695 		lsize_s = lsize;
3696 		psize_s = psize;
3697 		asize_s = asize;
3698 	} else {
3699 		lsize_s = -lsize;
3700 		psize_s = -psize;
3701 		asize_s = -asize;
3702 	}
3703 
3704 	/* If the buffer is a prefetch, count it as such. */
3705 	if (HDR_PREFETCH(hdr)) {
3706 		ARCSTAT_INCR(arcstat_l2_prefetch_asize, asize_s);
3707 	} else {
3708 		/*
3709 		 * We use the value stored in the L2 header upon initial
3710 		 * caching in L2ARC. This value will be updated in case
3711 		 * an MRU/MRU_ghost buffer transitions to MFU but the L2ARC
3712 		 * metadata (log entry) cannot currently be updated. Having
3713 		 * the ARC state in the L2 header solves the problem of a
3714 		 * possibly absent L1 header (apparent in buffers restored
3715 		 * from persistent L2ARC).
3716 		 */
3717 		switch (hdr->b_l2hdr.b_arcs_state) {
3718 			case ARC_STATE_MRU_GHOST:
3719 			case ARC_STATE_MRU:
3720 				ARCSTAT_INCR(arcstat_l2_mru_asize, asize_s);
3721 				break;
3722 			case ARC_STATE_MFU_GHOST:
3723 			case ARC_STATE_MFU:
3724 				ARCSTAT_INCR(arcstat_l2_mfu_asize, asize_s);
3725 				break;
3726 			default:
3727 				break;
3728 		}
3729 	}
3730 
3731 	if (state_only)
3732 		return;
3733 
3734 	ARCSTAT_INCR(arcstat_l2_psize, psize_s);
3735 	ARCSTAT_INCR(arcstat_l2_lsize, lsize_s);
3736 
3737 	switch (type) {
3738 		case ARC_BUFC_DATA:
3739 			ARCSTAT_INCR(arcstat_l2_bufc_data_asize, asize_s);
3740 			break;
3741 		case ARC_BUFC_METADATA:
3742 			ARCSTAT_INCR(arcstat_l2_bufc_metadata_asize, asize_s);
3743 			break;
3744 		default:
3745 			break;
3746 	}
3747 }
3748 
3749 
3750 static void
3751 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3752 {
3753 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3754 	l2arc_dev_t *dev = l2hdr->b_dev;
3755 	uint64_t psize = HDR_GET_PSIZE(hdr);
3756 	uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
3757 
3758 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3759 	ASSERT(HDR_HAS_L2HDR(hdr));
3760 
3761 	list_remove(&dev->l2ad_buflist, hdr);
3762 
3763 	l2arc_hdr_arcstats_decrement(hdr);
3764 	vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3765 
3766 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3767 	    hdr);
3768 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3769 }
3770 
3771 static void
3772 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3773 {
3774 	if (HDR_HAS_L1HDR(hdr)) {
3775 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3776 		    hdr->b_l1hdr.b_bufcnt > 0);
3777 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3778 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3779 	}
3780 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3781 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
3782 
3783 	if (HDR_HAS_L2HDR(hdr)) {
3784 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3785 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3786 
3787 		if (!buflist_held)
3788 			mutex_enter(&dev->l2ad_mtx);
3789 
3790 		/*
3791 		 * Even though we checked this conditional above, we
3792 		 * need to check this again now that we have the
3793 		 * l2ad_mtx. This is because we could be racing with
3794 		 * another thread calling l2arc_evict() which might have
3795 		 * destroyed this header's L2 portion as we were waiting
3796 		 * to acquire the l2ad_mtx. If that happens, we don't
3797 		 * want to re-destroy the header's L2 portion.
3798 		 */
3799 		if (HDR_HAS_L2HDR(hdr)) {
3800 
3801 			if (!HDR_EMPTY(hdr))
3802 				buf_discard_identity(hdr);
3803 
3804 			arc_hdr_l2hdr_destroy(hdr);
3805 		}
3806 
3807 		if (!buflist_held)
3808 			mutex_exit(&dev->l2ad_mtx);
3809 	}
3810 
3811 	/*
3812 	 * The header's identify can only be safely discarded once it is no
3813 	 * longer discoverable.  This requires removing it from the hash table
3814 	 * and the l2arc header list.  After this point the hash lock can not
3815 	 * be used to protect the header.
3816 	 */
3817 	if (!HDR_EMPTY(hdr))
3818 		buf_discard_identity(hdr);
3819 
3820 	if (HDR_HAS_L1HDR(hdr)) {
3821 		arc_cksum_free(hdr);
3822 
3823 		while (hdr->b_l1hdr.b_buf != NULL)
3824 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3825 
3826 		if (hdr->b_l1hdr.b_pabd != NULL)
3827 			arc_hdr_free_abd(hdr, B_FALSE);
3828 
3829 		if (HDR_HAS_RABD(hdr))
3830 			arc_hdr_free_abd(hdr, B_TRUE);
3831 	}
3832 
3833 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3834 	if (HDR_HAS_L1HDR(hdr)) {
3835 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3836 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3837 
3838 		if (!HDR_PROTECTED(hdr)) {
3839 			kmem_cache_free(hdr_full_cache, hdr);
3840 		} else {
3841 			kmem_cache_free(hdr_full_crypt_cache, hdr);
3842 		}
3843 	} else {
3844 		kmem_cache_free(hdr_l2only_cache, hdr);
3845 	}
3846 }
3847 
3848 void
3849 arc_buf_destroy(arc_buf_t *buf, const void *tag)
3850 {
3851 	arc_buf_hdr_t *hdr = buf->b_hdr;
3852 
3853 	if (hdr->b_l1hdr.b_state == arc_anon) {
3854 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3855 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3856 		VERIFY0(remove_reference(hdr, NULL, tag));
3857 		arc_hdr_destroy(hdr);
3858 		return;
3859 	}
3860 
3861 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3862 	mutex_enter(hash_lock);
3863 
3864 	ASSERT3P(hdr, ==, buf->b_hdr);
3865 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3866 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3867 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3868 	ASSERT3P(buf->b_data, !=, NULL);
3869 
3870 	(void) remove_reference(hdr, hash_lock, tag);
3871 	arc_buf_destroy_impl(buf);
3872 	mutex_exit(hash_lock);
3873 }
3874 
3875 /*
3876  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3877  * state of the header is dependent on its state prior to entering this
3878  * function. The following transitions are possible:
3879  *
3880  *    - arc_mru -> arc_mru_ghost
3881  *    - arc_mfu -> arc_mfu_ghost
3882  *    - arc_mru_ghost -> arc_l2c_only
3883  *    - arc_mru_ghost -> deleted
3884  *    - arc_mfu_ghost -> arc_l2c_only
3885  *    - arc_mfu_ghost -> deleted
3886  *
3887  * Return total size of evicted data buffers for eviction progress tracking.
3888  * When evicting from ghost states return logical buffer size to make eviction
3889  * progress at the same (or at least comparable) rate as from non-ghost states.
3890  *
3891  * Return *real_evicted for actual ARC size reduction to wake up threads
3892  * waiting for it.  For non-ghost states it includes size of evicted data
3893  * buffers (the headers are not freed there).  For ghost states it includes
3894  * only the evicted headers size.
3895  */
3896 static int64_t
3897 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, uint64_t *real_evicted)
3898 {
3899 	arc_state_t *evicted_state, *state;
3900 	int64_t bytes_evicted = 0;
3901 	int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3902 	    arc_min_prescient_prefetch_ms : arc_min_prefetch_ms;
3903 
3904 	ASSERT(MUTEX_HELD(hash_lock));
3905 	ASSERT(HDR_HAS_L1HDR(hdr));
3906 
3907 	*real_evicted = 0;
3908 	state = hdr->b_l1hdr.b_state;
3909 	if (GHOST_STATE(state)) {
3910 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3911 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3912 
3913 		/*
3914 		 * l2arc_write_buffers() relies on a header's L1 portion
3915 		 * (i.e. its b_pabd field) during it's write phase.
3916 		 * Thus, we cannot push a header onto the arc_l2c_only
3917 		 * state (removing its L1 piece) until the header is
3918 		 * done being written to the l2arc.
3919 		 */
3920 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3921 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3922 			return (bytes_evicted);
3923 		}
3924 
3925 		ARCSTAT_BUMP(arcstat_deleted);
3926 		bytes_evicted += HDR_GET_LSIZE(hdr);
3927 
3928 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3929 
3930 		if (HDR_HAS_L2HDR(hdr)) {
3931 			ASSERT(hdr->b_l1hdr.b_pabd == NULL);
3932 			ASSERT(!HDR_HAS_RABD(hdr));
3933 			/*
3934 			 * This buffer is cached on the 2nd Level ARC;
3935 			 * don't destroy the header.
3936 			 */
3937 			arc_change_state(arc_l2c_only, hdr, hash_lock);
3938 			/*
3939 			 * dropping from L1+L2 cached to L2-only,
3940 			 * realloc to remove the L1 header.
3941 			 */
3942 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3943 			    hdr_l2only_cache);
3944 			*real_evicted += HDR_FULL_SIZE - HDR_L2ONLY_SIZE;
3945 		} else {
3946 			arc_change_state(arc_anon, hdr, hash_lock);
3947 			arc_hdr_destroy(hdr);
3948 			*real_evicted += HDR_FULL_SIZE;
3949 		}
3950 		return (bytes_evicted);
3951 	}
3952 
3953 	ASSERT(state == arc_mru || state == arc_mfu);
3954 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3955 
3956 	/* prefetch buffers have a minimum lifespan */
3957 	if (HDR_IO_IN_PROGRESS(hdr) ||
3958 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3959 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3960 	    MSEC_TO_TICK(min_lifetime))) {
3961 		ARCSTAT_BUMP(arcstat_evict_skip);
3962 		return (bytes_evicted);
3963 	}
3964 
3965 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3966 	while (hdr->b_l1hdr.b_buf) {
3967 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3968 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3969 			ARCSTAT_BUMP(arcstat_mutex_miss);
3970 			break;
3971 		}
3972 		if (buf->b_data != NULL) {
3973 			bytes_evicted += HDR_GET_LSIZE(hdr);
3974 			*real_evicted += HDR_GET_LSIZE(hdr);
3975 		}
3976 		mutex_exit(&buf->b_evict_lock);
3977 		arc_buf_destroy_impl(buf);
3978 	}
3979 
3980 	if (HDR_HAS_L2HDR(hdr)) {
3981 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3982 	} else {
3983 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3984 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3985 			    HDR_GET_LSIZE(hdr));
3986 
3987 			switch (state->arcs_state) {
3988 				case ARC_STATE_MRU:
3989 					ARCSTAT_INCR(
3990 					    arcstat_evict_l2_eligible_mru,
3991 					    HDR_GET_LSIZE(hdr));
3992 					break;
3993 				case ARC_STATE_MFU:
3994 					ARCSTAT_INCR(
3995 					    arcstat_evict_l2_eligible_mfu,
3996 					    HDR_GET_LSIZE(hdr));
3997 					break;
3998 				default:
3999 					break;
4000 			}
4001 		} else {
4002 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
4003 			    HDR_GET_LSIZE(hdr));
4004 		}
4005 	}
4006 
4007 	if (hdr->b_l1hdr.b_bufcnt == 0) {
4008 		arc_cksum_free(hdr);
4009 
4010 		bytes_evicted += arc_hdr_size(hdr);
4011 		*real_evicted += arc_hdr_size(hdr);
4012 
4013 		/*
4014 		 * If this hdr is being evicted and has a compressed
4015 		 * buffer then we discard it here before we change states.
4016 		 * This ensures that the accounting is updated correctly
4017 		 * in arc_free_data_impl().
4018 		 */
4019 		if (hdr->b_l1hdr.b_pabd != NULL)
4020 			arc_hdr_free_abd(hdr, B_FALSE);
4021 
4022 		if (HDR_HAS_RABD(hdr))
4023 			arc_hdr_free_abd(hdr, B_TRUE);
4024 
4025 		arc_change_state(evicted_state, hdr, hash_lock);
4026 		ASSERT(HDR_IN_HASH_TABLE(hdr));
4027 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
4028 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
4029 	}
4030 
4031 	return (bytes_evicted);
4032 }
4033 
4034 static void
4035 arc_set_need_free(void)
4036 {
4037 	ASSERT(MUTEX_HELD(&arc_evict_lock));
4038 	int64_t remaining = arc_free_memory() - arc_sys_free / 2;
4039 	arc_evict_waiter_t *aw = list_tail(&arc_evict_waiters);
4040 	if (aw == NULL) {
4041 		arc_need_free = MAX(-remaining, 0);
4042 	} else {
4043 		arc_need_free =
4044 		    MAX(-remaining, (int64_t)(aw->aew_count - arc_evict_count));
4045 	}
4046 }
4047 
4048 static uint64_t
4049 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
4050     uint64_t spa, uint64_t bytes)
4051 {
4052 	multilist_sublist_t *mls;
4053 	uint64_t bytes_evicted = 0, real_evicted = 0;
4054 	arc_buf_hdr_t *hdr;
4055 	kmutex_t *hash_lock;
4056 	int evict_count = zfs_arc_evict_batch_limit;
4057 
4058 	ASSERT3P(marker, !=, NULL);
4059 
4060 	mls = multilist_sublist_lock(ml, idx);
4061 
4062 	for (hdr = multilist_sublist_prev(mls, marker); likely(hdr != NULL);
4063 	    hdr = multilist_sublist_prev(mls, marker)) {
4064 		if ((evict_count <= 0) || (bytes_evicted >= bytes))
4065 			break;
4066 
4067 		/*
4068 		 * To keep our iteration location, move the marker
4069 		 * forward. Since we're not holding hdr's hash lock, we
4070 		 * must be very careful and not remove 'hdr' from the
4071 		 * sublist. Otherwise, other consumers might mistake the
4072 		 * 'hdr' as not being on a sublist when they call the
4073 		 * multilist_link_active() function (they all rely on
4074 		 * the hash lock protecting concurrent insertions and
4075 		 * removals). multilist_sublist_move_forward() was
4076 		 * specifically implemented to ensure this is the case
4077 		 * (only 'marker' will be removed and re-inserted).
4078 		 */
4079 		multilist_sublist_move_forward(mls, marker);
4080 
4081 		/*
4082 		 * The only case where the b_spa field should ever be
4083 		 * zero, is the marker headers inserted by
4084 		 * arc_evict_state(). It's possible for multiple threads
4085 		 * to be calling arc_evict_state() concurrently (e.g.
4086 		 * dsl_pool_close() and zio_inject_fault()), so we must
4087 		 * skip any markers we see from these other threads.
4088 		 */
4089 		if (hdr->b_spa == 0)
4090 			continue;
4091 
4092 		/* we're only interested in evicting buffers of a certain spa */
4093 		if (spa != 0 && hdr->b_spa != spa) {
4094 			ARCSTAT_BUMP(arcstat_evict_skip);
4095 			continue;
4096 		}
4097 
4098 		hash_lock = HDR_LOCK(hdr);
4099 
4100 		/*
4101 		 * We aren't calling this function from any code path
4102 		 * that would already be holding a hash lock, so we're
4103 		 * asserting on this assumption to be defensive in case
4104 		 * this ever changes. Without this check, it would be
4105 		 * possible to incorrectly increment arcstat_mutex_miss
4106 		 * below (e.g. if the code changed such that we called
4107 		 * this function with a hash lock held).
4108 		 */
4109 		ASSERT(!MUTEX_HELD(hash_lock));
4110 
4111 		if (mutex_tryenter(hash_lock)) {
4112 			uint64_t revicted;
4113 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock,
4114 			    &revicted);
4115 			mutex_exit(hash_lock);
4116 
4117 			bytes_evicted += evicted;
4118 			real_evicted += revicted;
4119 
4120 			/*
4121 			 * If evicted is zero, arc_evict_hdr() must have
4122 			 * decided to skip this header, don't increment
4123 			 * evict_count in this case.
4124 			 */
4125 			if (evicted != 0)
4126 				evict_count--;
4127 
4128 		} else {
4129 			ARCSTAT_BUMP(arcstat_mutex_miss);
4130 		}
4131 	}
4132 
4133 	multilist_sublist_unlock(mls);
4134 
4135 	/*
4136 	 * Increment the count of evicted bytes, and wake up any threads that
4137 	 * are waiting for the count to reach this value.  Since the list is
4138 	 * ordered by ascending aew_count, we pop off the beginning of the
4139 	 * list until we reach the end, or a waiter that's past the current
4140 	 * "count".  Doing this outside the loop reduces the number of times
4141 	 * we need to acquire the global arc_evict_lock.
4142 	 *
4143 	 * Only wake when there's sufficient free memory in the system
4144 	 * (specifically, arc_sys_free/2, which by default is a bit more than
4145 	 * 1/64th of RAM).  See the comments in arc_wait_for_eviction().
4146 	 */
4147 	mutex_enter(&arc_evict_lock);
4148 	arc_evict_count += real_evicted;
4149 
4150 	if (arc_free_memory() > arc_sys_free / 2) {
4151 		arc_evict_waiter_t *aw;
4152 		while ((aw = list_head(&arc_evict_waiters)) != NULL &&
4153 		    aw->aew_count <= arc_evict_count) {
4154 			list_remove(&arc_evict_waiters, aw);
4155 			cv_broadcast(&aw->aew_cv);
4156 		}
4157 	}
4158 	arc_set_need_free();
4159 	mutex_exit(&arc_evict_lock);
4160 
4161 	/*
4162 	 * If the ARC size is reduced from arc_c_max to arc_c_min (especially
4163 	 * if the average cached block is small), eviction can be on-CPU for
4164 	 * many seconds.  To ensure that other threads that may be bound to
4165 	 * this CPU are able to make progress, make a voluntary preemption
4166 	 * call here.
4167 	 */
4168 	cond_resched();
4169 
4170 	return (bytes_evicted);
4171 }
4172 
4173 /*
4174  * Allocate an array of buffer headers used as placeholders during arc state
4175  * eviction.
4176  */
4177 static arc_buf_hdr_t **
4178 arc_state_alloc_markers(int count)
4179 {
4180 	arc_buf_hdr_t **markers;
4181 
4182 	markers = kmem_zalloc(sizeof (*markers) * count, KM_SLEEP);
4183 	for (int i = 0; i < count; i++) {
4184 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
4185 
4186 		/*
4187 		 * A b_spa of 0 is used to indicate that this header is
4188 		 * a marker. This fact is used in arc_evict_type() and
4189 		 * arc_evict_state_impl().
4190 		 */
4191 		markers[i]->b_spa = 0;
4192 
4193 	}
4194 	return (markers);
4195 }
4196 
4197 static void
4198 arc_state_free_markers(arc_buf_hdr_t **markers, int count)
4199 {
4200 	for (int i = 0; i < count; i++)
4201 		kmem_cache_free(hdr_full_cache, markers[i]);
4202 	kmem_free(markers, sizeof (*markers) * count);
4203 }
4204 
4205 /*
4206  * Evict buffers from the given arc state, until we've removed the
4207  * specified number of bytes. Move the removed buffers to the
4208  * appropriate evict state.
4209  *
4210  * This function makes a "best effort". It skips over any buffers
4211  * it can't get a hash_lock on, and so, may not catch all candidates.
4212  * It may also return without evicting as much space as requested.
4213  *
4214  * If bytes is specified using the special value ARC_EVICT_ALL, this
4215  * will evict all available (i.e. unlocked and evictable) buffers from
4216  * the given arc state; which is used by arc_flush().
4217  */
4218 static uint64_t
4219 arc_evict_state(arc_state_t *state, uint64_t spa, uint64_t bytes,
4220     arc_buf_contents_t type)
4221 {
4222 	uint64_t total_evicted = 0;
4223 	multilist_t *ml = &state->arcs_list[type];
4224 	int num_sublists;
4225 	arc_buf_hdr_t **markers;
4226 
4227 	num_sublists = multilist_get_num_sublists(ml);
4228 
4229 	/*
4230 	 * If we've tried to evict from each sublist, made some
4231 	 * progress, but still have not hit the target number of bytes
4232 	 * to evict, we want to keep trying. The markers allow us to
4233 	 * pick up where we left off for each individual sublist, rather
4234 	 * than starting from the tail each time.
4235 	 */
4236 	if (zthr_iscurthread(arc_evict_zthr)) {
4237 		markers = arc_state_evict_markers;
4238 		ASSERT3S(num_sublists, <=, arc_state_evict_marker_count);
4239 	} else {
4240 		markers = arc_state_alloc_markers(num_sublists);
4241 	}
4242 	for (int i = 0; i < num_sublists; i++) {
4243 		multilist_sublist_t *mls;
4244 
4245 		mls = multilist_sublist_lock(ml, i);
4246 		multilist_sublist_insert_tail(mls, markers[i]);
4247 		multilist_sublist_unlock(mls);
4248 	}
4249 
4250 	/*
4251 	 * While we haven't hit our target number of bytes to evict, or
4252 	 * we're evicting all available buffers.
4253 	 */
4254 	while (total_evicted < bytes) {
4255 		int sublist_idx = multilist_get_random_index(ml);
4256 		uint64_t scan_evicted = 0;
4257 
4258 		/*
4259 		 * Try to reduce pinned dnodes with a floor of arc_dnode_limit.
4260 		 * Request that 10% of the LRUs be scanned by the superblock
4261 		 * shrinker.
4262 		 */
4263 		if (type == ARC_BUFC_DATA && aggsum_compare(
4264 		    &arc_sums.arcstat_dnode_size, arc_dnode_size_limit) > 0) {
4265 			arc_prune_async((aggsum_upper_bound(
4266 			    &arc_sums.arcstat_dnode_size) -
4267 			    arc_dnode_size_limit) / sizeof (dnode_t) /
4268 			    zfs_arc_dnode_reduce_percent);
4269 		}
4270 
4271 		/*
4272 		 * Start eviction using a randomly selected sublist,
4273 		 * this is to try and evenly balance eviction across all
4274 		 * sublists. Always starting at the same sublist
4275 		 * (e.g. index 0) would cause evictions to favor certain
4276 		 * sublists over others.
4277 		 */
4278 		for (int i = 0; i < num_sublists; i++) {
4279 			uint64_t bytes_remaining;
4280 			uint64_t bytes_evicted;
4281 
4282 			if (total_evicted < bytes)
4283 				bytes_remaining = bytes - total_evicted;
4284 			else
4285 				break;
4286 
4287 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
4288 			    markers[sublist_idx], spa, bytes_remaining);
4289 
4290 			scan_evicted += bytes_evicted;
4291 			total_evicted += bytes_evicted;
4292 
4293 			/* we've reached the end, wrap to the beginning */
4294 			if (++sublist_idx >= num_sublists)
4295 				sublist_idx = 0;
4296 		}
4297 
4298 		/*
4299 		 * If we didn't evict anything during this scan, we have
4300 		 * no reason to believe we'll evict more during another
4301 		 * scan, so break the loop.
4302 		 */
4303 		if (scan_evicted == 0) {
4304 			/* This isn't possible, let's make that obvious */
4305 			ASSERT3S(bytes, !=, 0);
4306 
4307 			/*
4308 			 * When bytes is ARC_EVICT_ALL, the only way to
4309 			 * break the loop is when scan_evicted is zero.
4310 			 * In that case, we actually have evicted enough,
4311 			 * so we don't want to increment the kstat.
4312 			 */
4313 			if (bytes != ARC_EVICT_ALL) {
4314 				ASSERT3S(total_evicted, <, bytes);
4315 				ARCSTAT_BUMP(arcstat_evict_not_enough);
4316 			}
4317 
4318 			break;
4319 		}
4320 	}
4321 
4322 	for (int i = 0; i < num_sublists; i++) {
4323 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4324 		multilist_sublist_remove(mls, markers[i]);
4325 		multilist_sublist_unlock(mls);
4326 	}
4327 	if (markers != arc_state_evict_markers)
4328 		arc_state_free_markers(markers, num_sublists);
4329 
4330 	return (total_evicted);
4331 }
4332 
4333 /*
4334  * Flush all "evictable" data of the given type from the arc state
4335  * specified. This will not evict any "active" buffers (i.e. referenced).
4336  *
4337  * When 'retry' is set to B_FALSE, the function will make a single pass
4338  * over the state and evict any buffers that it can. Since it doesn't
4339  * continually retry the eviction, it might end up leaving some buffers
4340  * in the ARC due to lock misses.
4341  *
4342  * When 'retry' is set to B_TRUE, the function will continually retry the
4343  * eviction until *all* evictable buffers have been removed from the
4344  * state. As a result, if concurrent insertions into the state are
4345  * allowed (e.g. if the ARC isn't shutting down), this function might
4346  * wind up in an infinite loop, continually trying to evict buffers.
4347  */
4348 static uint64_t
4349 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4350     boolean_t retry)
4351 {
4352 	uint64_t evicted = 0;
4353 
4354 	while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
4355 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
4356 
4357 		if (!retry)
4358 			break;
4359 	}
4360 
4361 	return (evicted);
4362 }
4363 
4364 /*
4365  * Evict the specified number of bytes from the state specified,
4366  * restricting eviction to the spa and type given. This function
4367  * prevents us from trying to evict more from a state's list than
4368  * is "evictable", and to skip evicting altogether when passed a
4369  * negative value for "bytes". In contrast, arc_evict_state() will
4370  * evict everything it can, when passed a negative value for "bytes".
4371  */
4372 static uint64_t
4373 arc_evict_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
4374     arc_buf_contents_t type)
4375 {
4376 	uint64_t delta;
4377 
4378 	if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
4379 		delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
4380 		    bytes);
4381 		return (arc_evict_state(state, spa, delta, type));
4382 	}
4383 
4384 	return (0);
4385 }
4386 
4387 /*
4388  * The goal of this function is to evict enough meta data buffers from the
4389  * ARC in order to enforce the arc_meta_limit.  Achieving this is slightly
4390  * more complicated than it appears because it is common for data buffers
4391  * to have holds on meta data buffers.  In addition, dnode meta data buffers
4392  * will be held by the dnodes in the block preventing them from being freed.
4393  * This means we can't simply traverse the ARC and expect to always find
4394  * enough unheld meta data buffer to release.
4395  *
4396  * Therefore, this function has been updated to make alternating passes
4397  * over the ARC releasing data buffers and then newly unheld meta data
4398  * buffers.  This ensures forward progress is maintained and meta_used
4399  * will decrease.  Normally this is sufficient, but if required the ARC
4400  * will call the registered prune callbacks causing dentry and inodes to
4401  * be dropped from the VFS cache.  This will make dnode meta data buffers
4402  * available for reclaim.
4403  */
4404 static uint64_t
4405 arc_evict_meta_balanced(uint64_t meta_used)
4406 {
4407 	int64_t delta, prune = 0, adjustmnt;
4408 	uint64_t total_evicted = 0;
4409 	arc_buf_contents_t type = ARC_BUFC_DATA;
4410 	int restarts = MAX(zfs_arc_meta_adjust_restarts, 0);
4411 
4412 restart:
4413 	/*
4414 	 * This slightly differs than the way we evict from the mru in
4415 	 * arc_evict because we don't have a "target" value (i.e. no
4416 	 * "meta" arc_p). As a result, I think we can completely
4417 	 * cannibalize the metadata in the MRU before we evict the
4418 	 * metadata from the MFU. I think we probably need to implement a
4419 	 * "metadata arc_p" value to do this properly.
4420 	 */
4421 	adjustmnt = meta_used - arc_meta_limit;
4422 
4423 	if (adjustmnt > 0 &&
4424 	    zfs_refcount_count(&arc_mru->arcs_esize[type]) > 0) {
4425 		delta = MIN(zfs_refcount_count(&arc_mru->arcs_esize[type]),
4426 		    adjustmnt);
4427 		total_evicted += arc_evict_impl(arc_mru, 0, delta, type);
4428 		adjustmnt -= delta;
4429 	}
4430 
4431 	/*
4432 	 * We can't afford to recalculate adjustmnt here. If we do,
4433 	 * new metadata buffers can sneak into the MRU or ANON lists,
4434 	 * thus penalize the MFU metadata. Although the fudge factor is
4435 	 * small, it has been empirically shown to be significant for
4436 	 * certain workloads (e.g. creating many empty directories). As
4437 	 * such, we use the original calculation for adjustmnt, and
4438 	 * simply decrement the amount of data evicted from the MRU.
4439 	 */
4440 
4441 	if (adjustmnt > 0 &&
4442 	    zfs_refcount_count(&arc_mfu->arcs_esize[type]) > 0) {
4443 		delta = MIN(zfs_refcount_count(&arc_mfu->arcs_esize[type]),
4444 		    adjustmnt);
4445 		total_evicted += arc_evict_impl(arc_mfu, 0, delta, type);
4446 	}
4447 
4448 	adjustmnt = meta_used - arc_meta_limit;
4449 
4450 	if (adjustmnt > 0 &&
4451 	    zfs_refcount_count(&arc_mru_ghost->arcs_esize[type]) > 0) {
4452 		delta = MIN(adjustmnt,
4453 		    zfs_refcount_count(&arc_mru_ghost->arcs_esize[type]));
4454 		total_evicted += arc_evict_impl(arc_mru_ghost, 0, delta, type);
4455 		adjustmnt -= delta;
4456 	}
4457 
4458 	if (adjustmnt > 0 &&
4459 	    zfs_refcount_count(&arc_mfu_ghost->arcs_esize[type]) > 0) {
4460 		delta = MIN(adjustmnt,
4461 		    zfs_refcount_count(&arc_mfu_ghost->arcs_esize[type]));
4462 		total_evicted += arc_evict_impl(arc_mfu_ghost, 0, delta, type);
4463 	}
4464 
4465 	/*
4466 	 * If after attempting to make the requested adjustment to the ARC
4467 	 * the meta limit is still being exceeded then request that the
4468 	 * higher layers drop some cached objects which have holds on ARC
4469 	 * meta buffers.  Requests to the upper layers will be made with
4470 	 * increasingly large scan sizes until the ARC is below the limit.
4471 	 */
4472 	if (meta_used > arc_meta_limit) {
4473 		if (type == ARC_BUFC_DATA) {
4474 			type = ARC_BUFC_METADATA;
4475 		} else {
4476 			type = ARC_BUFC_DATA;
4477 
4478 			if (zfs_arc_meta_prune) {
4479 				prune += zfs_arc_meta_prune;
4480 				arc_prune_async(prune);
4481 			}
4482 		}
4483 
4484 		if (restarts > 0) {
4485 			restarts--;
4486 			goto restart;
4487 		}
4488 	}
4489 	return (total_evicted);
4490 }
4491 
4492 /*
4493  * Evict metadata buffers from the cache, such that arcstat_meta_used is
4494  * capped by the arc_meta_limit tunable.
4495  */
4496 static uint64_t
4497 arc_evict_meta_only(uint64_t meta_used)
4498 {
4499 	uint64_t total_evicted = 0;
4500 	int64_t target;
4501 
4502 	/*
4503 	 * If we're over the meta limit, we want to evict enough
4504 	 * metadata to get back under the meta limit. We don't want to
4505 	 * evict so much that we drop the MRU below arc_p, though. If
4506 	 * we're over the meta limit more than we're over arc_p, we
4507 	 * evict some from the MRU here, and some from the MFU below.
4508 	 */
4509 	target = MIN((int64_t)(meta_used - arc_meta_limit),
4510 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4511 	    zfs_refcount_count(&arc_mru->arcs_size) - arc_p));
4512 
4513 	total_evicted += arc_evict_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4514 
4515 	/*
4516 	 * Similar to the above, we want to evict enough bytes to get us
4517 	 * below the meta limit, but not so much as to drop us below the
4518 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
4519 	 */
4520 	target = MIN((int64_t)(meta_used - arc_meta_limit),
4521 	    (int64_t)(zfs_refcount_count(&arc_mfu->arcs_size) -
4522 	    (arc_c - arc_p)));
4523 
4524 	total_evicted += arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4525 
4526 	return (total_evicted);
4527 }
4528 
4529 static uint64_t
4530 arc_evict_meta(uint64_t meta_used)
4531 {
4532 	if (zfs_arc_meta_strategy == ARC_STRATEGY_META_ONLY)
4533 		return (arc_evict_meta_only(meta_used));
4534 	else
4535 		return (arc_evict_meta_balanced(meta_used));
4536 }
4537 
4538 /*
4539  * Return the type of the oldest buffer in the given arc state
4540  *
4541  * This function will select a random sublist of type ARC_BUFC_DATA and
4542  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
4543  * is compared, and the type which contains the "older" buffer will be
4544  * returned.
4545  */
4546 static arc_buf_contents_t
4547 arc_evict_type(arc_state_t *state)
4548 {
4549 	multilist_t *data_ml = &state->arcs_list[ARC_BUFC_DATA];
4550 	multilist_t *meta_ml = &state->arcs_list[ARC_BUFC_METADATA];
4551 	int data_idx = multilist_get_random_index(data_ml);
4552 	int meta_idx = multilist_get_random_index(meta_ml);
4553 	multilist_sublist_t *data_mls;
4554 	multilist_sublist_t *meta_mls;
4555 	arc_buf_contents_t type;
4556 	arc_buf_hdr_t *data_hdr;
4557 	arc_buf_hdr_t *meta_hdr;
4558 
4559 	/*
4560 	 * We keep the sublist lock until we're finished, to prevent
4561 	 * the headers from being destroyed via arc_evict_state().
4562 	 */
4563 	data_mls = multilist_sublist_lock(data_ml, data_idx);
4564 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4565 
4566 	/*
4567 	 * These two loops are to ensure we skip any markers that
4568 	 * might be at the tail of the lists due to arc_evict_state().
4569 	 */
4570 
4571 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4572 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4573 		if (data_hdr->b_spa != 0)
4574 			break;
4575 	}
4576 
4577 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4578 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4579 		if (meta_hdr->b_spa != 0)
4580 			break;
4581 	}
4582 
4583 	if (data_hdr == NULL && meta_hdr == NULL) {
4584 		type = ARC_BUFC_DATA;
4585 	} else if (data_hdr == NULL) {
4586 		ASSERT3P(meta_hdr, !=, NULL);
4587 		type = ARC_BUFC_METADATA;
4588 	} else if (meta_hdr == NULL) {
4589 		ASSERT3P(data_hdr, !=, NULL);
4590 		type = ARC_BUFC_DATA;
4591 	} else {
4592 		ASSERT3P(data_hdr, !=, NULL);
4593 		ASSERT3P(meta_hdr, !=, NULL);
4594 
4595 		/* The headers can't be on the sublist without an L1 header */
4596 		ASSERT(HDR_HAS_L1HDR(data_hdr));
4597 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
4598 
4599 		if (data_hdr->b_l1hdr.b_arc_access <
4600 		    meta_hdr->b_l1hdr.b_arc_access) {
4601 			type = ARC_BUFC_DATA;
4602 		} else {
4603 			type = ARC_BUFC_METADATA;
4604 		}
4605 	}
4606 
4607 	multilist_sublist_unlock(meta_mls);
4608 	multilist_sublist_unlock(data_mls);
4609 
4610 	return (type);
4611 }
4612 
4613 /*
4614  * Evict buffers from the cache, such that arcstat_size is capped by arc_c.
4615  */
4616 static uint64_t
4617 arc_evict(void)
4618 {
4619 	uint64_t total_evicted = 0;
4620 	uint64_t bytes;
4621 	int64_t target;
4622 	uint64_t asize = aggsum_value(&arc_sums.arcstat_size);
4623 	uint64_t ameta = aggsum_value(&arc_sums.arcstat_meta_used);
4624 
4625 	/*
4626 	 * If we're over arc_meta_limit, we want to correct that before
4627 	 * potentially evicting data buffers below.
4628 	 */
4629 	total_evicted += arc_evict_meta(ameta);
4630 
4631 	/*
4632 	 * Adjust MRU size
4633 	 *
4634 	 * If we're over the target cache size, we want to evict enough
4635 	 * from the list to get back to our target size. We don't want
4636 	 * to evict too much from the MRU, such that it drops below
4637 	 * arc_p. So, if we're over our target cache size more than
4638 	 * the MRU is over arc_p, we'll evict enough to get back to
4639 	 * arc_p here, and then evict more from the MFU below.
4640 	 */
4641 	target = MIN((int64_t)(asize - arc_c),
4642 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4643 	    zfs_refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4644 
4645 	/*
4646 	 * If we're below arc_meta_min, always prefer to evict data.
4647 	 * Otherwise, try to satisfy the requested number of bytes to
4648 	 * evict from the type which contains older buffers; in an
4649 	 * effort to keep newer buffers in the cache regardless of their
4650 	 * type. If we cannot satisfy the number of bytes from this
4651 	 * type, spill over into the next type.
4652 	 */
4653 	if (arc_evict_type(arc_mru) == ARC_BUFC_METADATA &&
4654 	    ameta > arc_meta_min) {
4655 		bytes = arc_evict_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4656 		total_evicted += bytes;
4657 
4658 		/*
4659 		 * If we couldn't evict our target number of bytes from
4660 		 * metadata, we try to get the rest from data.
4661 		 */
4662 		target -= bytes;
4663 
4664 		total_evicted +=
4665 		    arc_evict_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4666 	} else {
4667 		bytes = arc_evict_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4668 		total_evicted += bytes;
4669 
4670 		/*
4671 		 * If we couldn't evict our target number of bytes from
4672 		 * data, we try to get the rest from metadata.
4673 		 */
4674 		target -= bytes;
4675 
4676 		total_evicted +=
4677 		    arc_evict_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4678 	}
4679 
4680 	/*
4681 	 * Re-sum ARC stats after the first round of evictions.
4682 	 */
4683 	asize = aggsum_value(&arc_sums.arcstat_size);
4684 	ameta = aggsum_value(&arc_sums.arcstat_meta_used);
4685 
4686 
4687 	/*
4688 	 * Adjust MFU size
4689 	 *
4690 	 * Now that we've tried to evict enough from the MRU to get its
4691 	 * size back to arc_p, if we're still above the target cache
4692 	 * size, we evict the rest from the MFU.
4693 	 */
4694 	target = asize - arc_c;
4695 
4696 	if (arc_evict_type(arc_mfu) == ARC_BUFC_METADATA &&
4697 	    ameta > arc_meta_min) {
4698 		bytes = arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4699 		total_evicted += bytes;
4700 
4701 		/*
4702 		 * If we couldn't evict our target number of bytes from
4703 		 * metadata, we try to get the rest from data.
4704 		 */
4705 		target -= bytes;
4706 
4707 		total_evicted +=
4708 		    arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4709 	} else {
4710 		bytes = arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4711 		total_evicted += bytes;
4712 
4713 		/*
4714 		 * If we couldn't evict our target number of bytes from
4715 		 * data, we try to get the rest from data.
4716 		 */
4717 		target -= bytes;
4718 
4719 		total_evicted +=
4720 		    arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4721 	}
4722 
4723 	/*
4724 	 * Adjust ghost lists
4725 	 *
4726 	 * In addition to the above, the ARC also defines target values
4727 	 * for the ghost lists. The sum of the mru list and mru ghost
4728 	 * list should never exceed the target size of the cache, and
4729 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
4730 	 * ghost list should never exceed twice the target size of the
4731 	 * cache. The following logic enforces these limits on the ghost
4732 	 * caches, and evicts from them as needed.
4733 	 */
4734 	target = zfs_refcount_count(&arc_mru->arcs_size) +
4735 	    zfs_refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4736 
4737 	bytes = arc_evict_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4738 	total_evicted += bytes;
4739 
4740 	target -= bytes;
4741 
4742 	total_evicted +=
4743 	    arc_evict_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4744 
4745 	/*
4746 	 * We assume the sum of the mru list and mfu list is less than
4747 	 * or equal to arc_c (we enforced this above), which means we
4748 	 * can use the simpler of the two equations below:
4749 	 *
4750 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4751 	 *		    mru ghost + mfu ghost <= arc_c
4752 	 */
4753 	target = zfs_refcount_count(&arc_mru_ghost->arcs_size) +
4754 	    zfs_refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4755 
4756 	bytes = arc_evict_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4757 	total_evicted += bytes;
4758 
4759 	target -= bytes;
4760 
4761 	total_evicted +=
4762 	    arc_evict_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4763 
4764 	return (total_evicted);
4765 }
4766 
4767 void
4768 arc_flush(spa_t *spa, boolean_t retry)
4769 {
4770 	uint64_t guid = 0;
4771 
4772 	/*
4773 	 * If retry is B_TRUE, a spa must not be specified since we have
4774 	 * no good way to determine if all of a spa's buffers have been
4775 	 * evicted from an arc state.
4776 	 */
4777 	ASSERT(!retry || spa == 0);
4778 
4779 	if (spa != NULL)
4780 		guid = spa_load_guid(spa);
4781 
4782 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4783 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4784 
4785 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4786 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4787 
4788 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4789 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4790 
4791 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4792 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4793 }
4794 
4795 void
4796 arc_reduce_target_size(int64_t to_free)
4797 {
4798 	uint64_t asize = aggsum_value(&arc_sums.arcstat_size);
4799 
4800 	/*
4801 	 * All callers want the ARC to actually evict (at least) this much
4802 	 * memory.  Therefore we reduce from the lower of the current size and
4803 	 * the target size.  This way, even if arc_c is much higher than
4804 	 * arc_size (as can be the case after many calls to arc_freed(), we will
4805 	 * immediately have arc_c < arc_size and therefore the arc_evict_zthr
4806 	 * will evict.
4807 	 */
4808 	uint64_t c = MIN(arc_c, asize);
4809 
4810 	if (c > to_free && c - to_free > arc_c_min) {
4811 		arc_c = c - to_free;
4812 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4813 		if (arc_p > arc_c)
4814 			arc_p = (arc_c >> 1);
4815 		ASSERT(arc_c >= arc_c_min);
4816 		ASSERT((int64_t)arc_p >= 0);
4817 	} else {
4818 		arc_c = arc_c_min;
4819 	}
4820 
4821 	if (asize > arc_c) {
4822 		/* See comment in arc_evict_cb_check() on why lock+flag */
4823 		mutex_enter(&arc_evict_lock);
4824 		arc_evict_needed = B_TRUE;
4825 		mutex_exit(&arc_evict_lock);
4826 		zthr_wakeup(arc_evict_zthr);
4827 	}
4828 }
4829 
4830 /*
4831  * Determine if the system is under memory pressure and is asking
4832  * to reclaim memory. A return value of B_TRUE indicates that the system
4833  * is under memory pressure and that the arc should adjust accordingly.
4834  */
4835 boolean_t
4836 arc_reclaim_needed(void)
4837 {
4838 	return (arc_available_memory() < 0);
4839 }
4840 
4841 void
4842 arc_kmem_reap_soon(void)
4843 {
4844 	size_t			i;
4845 	kmem_cache_t		*prev_cache = NULL;
4846 	kmem_cache_t		*prev_data_cache = NULL;
4847 
4848 #ifdef _KERNEL
4849 	if ((aggsum_compare(&arc_sums.arcstat_meta_used,
4850 	    arc_meta_limit) >= 0) && zfs_arc_meta_prune) {
4851 		/*
4852 		 * We are exceeding our meta-data cache limit.
4853 		 * Prune some entries to release holds on meta-data.
4854 		 */
4855 		arc_prune_async(zfs_arc_meta_prune);
4856 	}
4857 #if defined(_ILP32)
4858 	/*
4859 	 * Reclaim unused memory from all kmem caches.
4860 	 */
4861 	kmem_reap();
4862 #endif
4863 #endif
4864 
4865 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4866 #if defined(_ILP32)
4867 		/* reach upper limit of cache size on 32-bit */
4868 		if (zio_buf_cache[i] == NULL)
4869 			break;
4870 #endif
4871 		if (zio_buf_cache[i] != prev_cache) {
4872 			prev_cache = zio_buf_cache[i];
4873 			kmem_cache_reap_now(zio_buf_cache[i]);
4874 		}
4875 		if (zio_data_buf_cache[i] != prev_data_cache) {
4876 			prev_data_cache = zio_data_buf_cache[i];
4877 			kmem_cache_reap_now(zio_data_buf_cache[i]);
4878 		}
4879 	}
4880 	kmem_cache_reap_now(buf_cache);
4881 	kmem_cache_reap_now(hdr_full_cache);
4882 	kmem_cache_reap_now(hdr_l2only_cache);
4883 	kmem_cache_reap_now(zfs_btree_leaf_cache);
4884 	abd_cache_reap_now();
4885 }
4886 
4887 static boolean_t
4888 arc_evict_cb_check(void *arg, zthr_t *zthr)
4889 {
4890 	(void) arg, (void) zthr;
4891 
4892 #ifdef ZFS_DEBUG
4893 	/*
4894 	 * This is necessary in order to keep the kstat information
4895 	 * up to date for tools that display kstat data such as the
4896 	 * mdb ::arc dcmd and the Linux crash utility.  These tools
4897 	 * typically do not call kstat's update function, but simply
4898 	 * dump out stats from the most recent update.  Without
4899 	 * this call, these commands may show stale stats for the
4900 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists.  Even
4901 	 * with this call, the data might be out of date if the
4902 	 * evict thread hasn't been woken recently; but that should
4903 	 * suffice.  The arc_state_t structures can be queried
4904 	 * directly if more accurate information is needed.
4905 	 */
4906 	if (arc_ksp != NULL)
4907 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4908 #endif
4909 
4910 	/*
4911 	 * We have to rely on arc_wait_for_eviction() to tell us when to
4912 	 * evict, rather than checking if we are overflowing here, so that we
4913 	 * are sure to not leave arc_wait_for_eviction() waiting on aew_cv.
4914 	 * If we have become "not overflowing" since arc_wait_for_eviction()
4915 	 * checked, we need to wake it up.  We could broadcast the CV here,
4916 	 * but arc_wait_for_eviction() may have not yet gone to sleep.  We
4917 	 * would need to use a mutex to ensure that this function doesn't
4918 	 * broadcast until arc_wait_for_eviction() has gone to sleep (e.g.
4919 	 * the arc_evict_lock).  However, the lock ordering of such a lock
4920 	 * would necessarily be incorrect with respect to the zthr_lock,
4921 	 * which is held before this function is called, and is held by
4922 	 * arc_wait_for_eviction() when it calls zthr_wakeup().
4923 	 */
4924 	return (arc_evict_needed);
4925 }
4926 
4927 /*
4928  * Keep arc_size under arc_c by running arc_evict which evicts data
4929  * from the ARC.
4930  */
4931 static void
4932 arc_evict_cb(void *arg, zthr_t *zthr)
4933 {
4934 	(void) arg, (void) zthr;
4935 
4936 	uint64_t evicted = 0;
4937 	fstrans_cookie_t cookie = spl_fstrans_mark();
4938 
4939 	/* Evict from cache */
4940 	evicted = arc_evict();
4941 
4942 	/*
4943 	 * If evicted is zero, we couldn't evict anything
4944 	 * via arc_evict(). This could be due to hash lock
4945 	 * collisions, but more likely due to the majority of
4946 	 * arc buffers being unevictable. Therefore, even if
4947 	 * arc_size is above arc_c, another pass is unlikely to
4948 	 * be helpful and could potentially cause us to enter an
4949 	 * infinite loop.  Additionally, zthr_iscancelled() is
4950 	 * checked here so that if the arc is shutting down, the
4951 	 * broadcast will wake any remaining arc evict waiters.
4952 	 */
4953 	mutex_enter(&arc_evict_lock);
4954 	arc_evict_needed = !zthr_iscancelled(arc_evict_zthr) &&
4955 	    evicted > 0 && aggsum_compare(&arc_sums.arcstat_size, arc_c) > 0;
4956 	if (!arc_evict_needed) {
4957 		/*
4958 		 * We're either no longer overflowing, or we
4959 		 * can't evict anything more, so we should wake
4960 		 * arc_get_data_impl() sooner.
4961 		 */
4962 		arc_evict_waiter_t *aw;
4963 		while ((aw = list_remove_head(&arc_evict_waiters)) != NULL) {
4964 			cv_broadcast(&aw->aew_cv);
4965 		}
4966 		arc_set_need_free();
4967 	}
4968 	mutex_exit(&arc_evict_lock);
4969 	spl_fstrans_unmark(cookie);
4970 }
4971 
4972 static boolean_t
4973 arc_reap_cb_check(void *arg, zthr_t *zthr)
4974 {
4975 	(void) arg, (void) zthr;
4976 
4977 	int64_t free_memory = arc_available_memory();
4978 	static int reap_cb_check_counter = 0;
4979 
4980 	/*
4981 	 * If a kmem reap is already active, don't schedule more.  We must
4982 	 * check for this because kmem_cache_reap_soon() won't actually
4983 	 * block on the cache being reaped (this is to prevent callers from
4984 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4985 	 * on a system with many, many full magazines, can take minutes).
4986 	 */
4987 	if (!kmem_cache_reap_active() && free_memory < 0) {
4988 
4989 		arc_no_grow = B_TRUE;
4990 		arc_warm = B_TRUE;
4991 		/*
4992 		 * Wait at least zfs_grow_retry (default 5) seconds
4993 		 * before considering growing.
4994 		 */
4995 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4996 		return (B_TRUE);
4997 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4998 		arc_no_grow = B_TRUE;
4999 	} else if (gethrtime() >= arc_growtime) {
5000 		arc_no_grow = B_FALSE;
5001 	}
5002 
5003 	/*
5004 	 * Called unconditionally every 60 seconds to reclaim unused
5005 	 * zstd compression and decompression context. This is done
5006 	 * here to avoid the need for an independent thread.
5007 	 */
5008 	if (!((reap_cb_check_counter++) % 60))
5009 		zfs_zstd_cache_reap_now();
5010 
5011 	return (B_FALSE);
5012 }
5013 
5014 /*
5015  * Keep enough free memory in the system by reaping the ARC's kmem
5016  * caches.  To cause more slabs to be reapable, we may reduce the
5017  * target size of the cache (arc_c), causing the arc_evict_cb()
5018  * to free more buffers.
5019  */
5020 static void
5021 arc_reap_cb(void *arg, zthr_t *zthr)
5022 {
5023 	(void) arg, (void) zthr;
5024 
5025 	int64_t free_memory;
5026 	fstrans_cookie_t cookie = spl_fstrans_mark();
5027 
5028 	/*
5029 	 * Kick off asynchronous kmem_reap()'s of all our caches.
5030 	 */
5031 	arc_kmem_reap_soon();
5032 
5033 	/*
5034 	 * Wait at least arc_kmem_cache_reap_retry_ms between
5035 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
5036 	 * end up in a situation where we spend lots of time reaping
5037 	 * caches, while we're near arc_c_min.  Waiting here also gives the
5038 	 * subsequent free memory check a chance of finding that the
5039 	 * asynchronous reap has already freed enough memory, and we don't
5040 	 * need to call arc_reduce_target_size().
5041 	 */
5042 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
5043 
5044 	/*
5045 	 * Reduce the target size as needed to maintain the amount of free
5046 	 * memory in the system at a fraction of the arc_size (1/128th by
5047 	 * default).  If oversubscribed (free_memory < 0) then reduce the
5048 	 * target arc_size by the deficit amount plus the fractional
5049 	 * amount.  If free memory is positive but less than the fractional
5050 	 * amount, reduce by what is needed to hit the fractional amount.
5051 	 */
5052 	free_memory = arc_available_memory();
5053 
5054 	int64_t to_free =
5055 	    (arc_c >> arc_shrink_shift) - free_memory;
5056 	if (to_free > 0) {
5057 		arc_reduce_target_size(to_free);
5058 	}
5059 	spl_fstrans_unmark(cookie);
5060 }
5061 
5062 #ifdef _KERNEL
5063 /*
5064  * Determine the amount of memory eligible for eviction contained in the
5065  * ARC. All clean data reported by the ghost lists can always be safely
5066  * evicted. Due to arc_c_min, the same does not hold for all clean data
5067  * contained by the regular mru and mfu lists.
5068  *
5069  * In the case of the regular mru and mfu lists, we need to report as
5070  * much clean data as possible, such that evicting that same reported
5071  * data will not bring arc_size below arc_c_min. Thus, in certain
5072  * circumstances, the total amount of clean data in the mru and mfu
5073  * lists might not actually be evictable.
5074  *
5075  * The following two distinct cases are accounted for:
5076  *
5077  * 1. The sum of the amount of dirty data contained by both the mru and
5078  *    mfu lists, plus the ARC's other accounting (e.g. the anon list),
5079  *    is greater than or equal to arc_c_min.
5080  *    (i.e. amount of dirty data >= arc_c_min)
5081  *
5082  *    This is the easy case; all clean data contained by the mru and mfu
5083  *    lists is evictable. Evicting all clean data can only drop arc_size
5084  *    to the amount of dirty data, which is greater than arc_c_min.
5085  *
5086  * 2. The sum of the amount of dirty data contained by both the mru and
5087  *    mfu lists, plus the ARC's other accounting (e.g. the anon list),
5088  *    is less than arc_c_min.
5089  *    (i.e. arc_c_min > amount of dirty data)
5090  *
5091  *    2.1. arc_size is greater than or equal arc_c_min.
5092  *         (i.e. arc_size >= arc_c_min > amount of dirty data)
5093  *
5094  *         In this case, not all clean data from the regular mru and mfu
5095  *         lists is actually evictable; we must leave enough clean data
5096  *         to keep arc_size above arc_c_min. Thus, the maximum amount of
5097  *         evictable data from the two lists combined, is exactly the
5098  *         difference between arc_size and arc_c_min.
5099  *
5100  *    2.2. arc_size is less than arc_c_min
5101  *         (i.e. arc_c_min > arc_size > amount of dirty data)
5102  *
5103  *         In this case, none of the data contained in the mru and mfu
5104  *         lists is evictable, even if it's clean. Since arc_size is
5105  *         already below arc_c_min, evicting any more would only
5106  *         increase this negative difference.
5107  */
5108 
5109 #endif /* _KERNEL */
5110 
5111 /*
5112  * Adapt arc info given the number of bytes we are trying to add and
5113  * the state that we are coming from.  This function is only called
5114  * when we are adding new content to the cache.
5115  */
5116 static void
5117 arc_adapt(int bytes, arc_state_t *state)
5118 {
5119 	int mult;
5120 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
5121 	int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
5122 	int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
5123 
5124 	ASSERT(bytes > 0);
5125 	/*
5126 	 * Adapt the target size of the MRU list:
5127 	 *	- if we just hit in the MRU ghost list, then increase
5128 	 *	  the target size of the MRU list.
5129 	 *	- if we just hit in the MFU ghost list, then increase
5130 	 *	  the target size of the MFU list by decreasing the
5131 	 *	  target size of the MRU list.
5132 	 */
5133 	if (state == arc_mru_ghost) {
5134 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
5135 		if (!zfs_arc_p_dampener_disable)
5136 			mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
5137 
5138 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
5139 	} else if (state == arc_mfu_ghost) {
5140 		uint64_t delta;
5141 
5142 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
5143 		if (!zfs_arc_p_dampener_disable)
5144 			mult = MIN(mult, 10);
5145 
5146 		delta = MIN(bytes * mult, arc_p);
5147 		arc_p = MAX(arc_p_min, arc_p - delta);
5148 	}
5149 	ASSERT((int64_t)arc_p >= 0);
5150 
5151 	/*
5152 	 * Wake reap thread if we do not have any available memory
5153 	 */
5154 	if (arc_reclaim_needed()) {
5155 		zthr_wakeup(arc_reap_zthr);
5156 		return;
5157 	}
5158 
5159 	if (arc_no_grow)
5160 		return;
5161 
5162 	if (arc_c >= arc_c_max)
5163 		return;
5164 
5165 	/*
5166 	 * If we're within (2 * maxblocksize) bytes of the target
5167 	 * cache size, increment the target cache size
5168 	 */
5169 	ASSERT3U(arc_c, >=, 2ULL << SPA_MAXBLOCKSHIFT);
5170 	if (aggsum_upper_bound(&arc_sums.arcstat_size) >=
5171 	    arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
5172 		atomic_add_64(&arc_c, (int64_t)bytes);
5173 		if (arc_c > arc_c_max)
5174 			arc_c = arc_c_max;
5175 		else if (state == arc_anon)
5176 			atomic_add_64(&arc_p, (int64_t)bytes);
5177 		if (arc_p > arc_c)
5178 			arc_p = arc_c;
5179 	}
5180 	ASSERT((int64_t)arc_p >= 0);
5181 }
5182 
5183 /*
5184  * Check if arc_size has grown past our upper threshold, determined by
5185  * zfs_arc_overflow_shift.
5186  */
5187 static arc_ovf_level_t
5188 arc_is_overflowing(boolean_t use_reserve)
5189 {
5190 	/* Always allow at least one block of overflow */
5191 	int64_t overflow = MAX(SPA_MAXBLOCKSIZE,
5192 	    arc_c >> zfs_arc_overflow_shift);
5193 
5194 	/*
5195 	 * We just compare the lower bound here for performance reasons. Our
5196 	 * primary goals are to make sure that the arc never grows without
5197 	 * bound, and that it can reach its maximum size. This check
5198 	 * accomplishes both goals. The maximum amount we could run over by is
5199 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
5200 	 * in the ARC. In practice, that's in the tens of MB, which is low
5201 	 * enough to be safe.
5202 	 */
5203 	int64_t over = aggsum_lower_bound(&arc_sums.arcstat_size) -
5204 	    arc_c - overflow / 2;
5205 	if (!use_reserve)
5206 		overflow /= 2;
5207 	return (over < 0 ? ARC_OVF_NONE :
5208 	    over < overflow ? ARC_OVF_SOME : ARC_OVF_SEVERE);
5209 }
5210 
5211 static abd_t *
5212 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, const void *tag,
5213     int alloc_flags)
5214 {
5215 	arc_buf_contents_t type = arc_buf_type(hdr);
5216 
5217 	arc_get_data_impl(hdr, size, tag, alloc_flags);
5218 	if (type == ARC_BUFC_METADATA) {
5219 		return (abd_alloc(size, B_TRUE));
5220 	} else {
5221 		ASSERT(type == ARC_BUFC_DATA);
5222 		return (abd_alloc(size, B_FALSE));
5223 	}
5224 }
5225 
5226 static void *
5227 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, const void *tag)
5228 {
5229 	arc_buf_contents_t type = arc_buf_type(hdr);
5230 
5231 	arc_get_data_impl(hdr, size, tag, ARC_HDR_DO_ADAPT);
5232 	if (type == ARC_BUFC_METADATA) {
5233 		return (zio_buf_alloc(size));
5234 	} else {
5235 		ASSERT(type == ARC_BUFC_DATA);
5236 		return (zio_data_buf_alloc(size));
5237 	}
5238 }
5239 
5240 /*
5241  * Wait for the specified amount of data (in bytes) to be evicted from the
5242  * ARC, and for there to be sufficient free memory in the system.  Waiting for
5243  * eviction ensures that the memory used by the ARC decreases.  Waiting for
5244  * free memory ensures that the system won't run out of free pages, regardless
5245  * of ARC behavior and settings.  See arc_lowmem_init().
5246  */
5247 void
5248 arc_wait_for_eviction(uint64_t amount, boolean_t use_reserve)
5249 {
5250 	switch (arc_is_overflowing(use_reserve)) {
5251 	case ARC_OVF_NONE:
5252 		return;
5253 	case ARC_OVF_SOME:
5254 		/*
5255 		 * This is a bit racy without taking arc_evict_lock, but the
5256 		 * worst that can happen is we either call zthr_wakeup() extra
5257 		 * time due to race with other thread here, or the set flag
5258 		 * get cleared by arc_evict_cb(), which is unlikely due to
5259 		 * big hysteresis, but also not important since at this level
5260 		 * of overflow the eviction is purely advisory.  Same time
5261 		 * taking the global lock here every time without waiting for
5262 		 * the actual eviction creates a significant lock contention.
5263 		 */
5264 		if (!arc_evict_needed) {
5265 			arc_evict_needed = B_TRUE;
5266 			zthr_wakeup(arc_evict_zthr);
5267 		}
5268 		return;
5269 	case ARC_OVF_SEVERE:
5270 	default:
5271 	{
5272 		arc_evict_waiter_t aw;
5273 		list_link_init(&aw.aew_node);
5274 		cv_init(&aw.aew_cv, NULL, CV_DEFAULT, NULL);
5275 
5276 		uint64_t last_count = 0;
5277 		mutex_enter(&arc_evict_lock);
5278 		if (!list_is_empty(&arc_evict_waiters)) {
5279 			arc_evict_waiter_t *last =
5280 			    list_tail(&arc_evict_waiters);
5281 			last_count = last->aew_count;
5282 		} else if (!arc_evict_needed) {
5283 			arc_evict_needed = B_TRUE;
5284 			zthr_wakeup(arc_evict_zthr);
5285 		}
5286 		/*
5287 		 * Note, the last waiter's count may be less than
5288 		 * arc_evict_count if we are low on memory in which
5289 		 * case arc_evict_state_impl() may have deferred
5290 		 * wakeups (but still incremented arc_evict_count).
5291 		 */
5292 		aw.aew_count = MAX(last_count, arc_evict_count) + amount;
5293 
5294 		list_insert_tail(&arc_evict_waiters, &aw);
5295 
5296 		arc_set_need_free();
5297 
5298 		DTRACE_PROBE3(arc__wait__for__eviction,
5299 		    uint64_t, amount,
5300 		    uint64_t, arc_evict_count,
5301 		    uint64_t, aw.aew_count);
5302 
5303 		/*
5304 		 * We will be woken up either when arc_evict_count reaches
5305 		 * aew_count, or when the ARC is no longer overflowing and
5306 		 * eviction completes.
5307 		 * In case of "false" wakeup, we will still be on the list.
5308 		 */
5309 		do {
5310 			cv_wait(&aw.aew_cv, &arc_evict_lock);
5311 		} while (list_link_active(&aw.aew_node));
5312 		mutex_exit(&arc_evict_lock);
5313 
5314 		cv_destroy(&aw.aew_cv);
5315 	}
5316 	}
5317 }
5318 
5319 /*
5320  * Allocate a block and return it to the caller. If we are hitting the
5321  * hard limit for the cache size, we must sleep, waiting for the eviction
5322  * thread to catch up. If we're past the target size but below the hard
5323  * limit, we'll only signal the reclaim thread and continue on.
5324  */
5325 static void
5326 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, const void *tag,
5327     int alloc_flags)
5328 {
5329 	arc_state_t *state = hdr->b_l1hdr.b_state;
5330 	arc_buf_contents_t type = arc_buf_type(hdr);
5331 
5332 	if (alloc_flags & ARC_HDR_DO_ADAPT)
5333 		arc_adapt(size, state);
5334 
5335 	/*
5336 	 * If arc_size is currently overflowing, we must be adding data
5337 	 * faster than we are evicting.  To ensure we don't compound the
5338 	 * problem by adding more data and forcing arc_size to grow even
5339 	 * further past it's target size, we wait for the eviction thread to
5340 	 * make some progress.  We also wait for there to be sufficient free
5341 	 * memory in the system, as measured by arc_free_memory().
5342 	 *
5343 	 * Specifically, we wait for zfs_arc_eviction_pct percent of the
5344 	 * requested size to be evicted.  This should be more than 100%, to
5345 	 * ensure that that progress is also made towards getting arc_size
5346 	 * under arc_c.  See the comment above zfs_arc_eviction_pct.
5347 	 */
5348 	arc_wait_for_eviction(size * zfs_arc_eviction_pct / 100,
5349 	    alloc_flags & ARC_HDR_USE_RESERVE);
5350 
5351 	VERIFY3U(hdr->b_type, ==, type);
5352 	if (type == ARC_BUFC_METADATA) {
5353 		arc_space_consume(size, ARC_SPACE_META);
5354 	} else {
5355 		arc_space_consume(size, ARC_SPACE_DATA);
5356 	}
5357 
5358 	/*
5359 	 * Update the state size.  Note that ghost states have a
5360 	 * "ghost size" and so don't need to be updated.
5361 	 */
5362 	if (!GHOST_STATE(state)) {
5363 
5364 		(void) zfs_refcount_add_many(&state->arcs_size, size, tag);
5365 
5366 		/*
5367 		 * If this is reached via arc_read, the link is
5368 		 * protected by the hash lock. If reached via
5369 		 * arc_buf_alloc, the header should not be accessed by
5370 		 * any other thread. And, if reached via arc_read_done,
5371 		 * the hash lock will protect it if it's found in the
5372 		 * hash table; otherwise no other thread should be
5373 		 * trying to [add|remove]_reference it.
5374 		 */
5375 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5376 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5377 			(void) zfs_refcount_add_many(&state->arcs_esize[type],
5378 			    size, tag);
5379 		}
5380 
5381 		/*
5382 		 * If we are growing the cache, and we are adding anonymous
5383 		 * data, and we have outgrown arc_p, update arc_p
5384 		 */
5385 		if (aggsum_upper_bound(&arc_sums.arcstat_size) < arc_c &&
5386 		    hdr->b_l1hdr.b_state == arc_anon &&
5387 		    (zfs_refcount_count(&arc_anon->arcs_size) +
5388 		    zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
5389 			arc_p = MIN(arc_c, arc_p + size);
5390 	}
5391 }
5392 
5393 static void
5394 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size,
5395     const void *tag)
5396 {
5397 	arc_free_data_impl(hdr, size, tag);
5398 	abd_free(abd);
5399 }
5400 
5401 static void
5402 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, const void *tag)
5403 {
5404 	arc_buf_contents_t type = arc_buf_type(hdr);
5405 
5406 	arc_free_data_impl(hdr, size, tag);
5407 	if (type == ARC_BUFC_METADATA) {
5408 		zio_buf_free(buf, size);
5409 	} else {
5410 		ASSERT(type == ARC_BUFC_DATA);
5411 		zio_data_buf_free(buf, size);
5412 	}
5413 }
5414 
5415 /*
5416  * Free the arc data buffer.
5417  */
5418 static void
5419 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, const void *tag)
5420 {
5421 	arc_state_t *state = hdr->b_l1hdr.b_state;
5422 	arc_buf_contents_t type = arc_buf_type(hdr);
5423 
5424 	/* protected by hash lock, if in the hash table */
5425 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5426 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5427 		ASSERT(state != arc_anon && state != arc_l2c_only);
5428 
5429 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
5430 		    size, tag);
5431 	}
5432 	(void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
5433 
5434 	VERIFY3U(hdr->b_type, ==, type);
5435 	if (type == ARC_BUFC_METADATA) {
5436 		arc_space_return(size, ARC_SPACE_META);
5437 	} else {
5438 		ASSERT(type == ARC_BUFC_DATA);
5439 		arc_space_return(size, ARC_SPACE_DATA);
5440 	}
5441 }
5442 
5443 /*
5444  * This routine is called whenever a buffer is accessed.
5445  * NOTE: the hash lock is dropped in this function.
5446  */
5447 static void
5448 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5449 {
5450 	clock_t now;
5451 
5452 	ASSERT(MUTEX_HELD(hash_lock));
5453 	ASSERT(HDR_HAS_L1HDR(hdr));
5454 
5455 	if (hdr->b_l1hdr.b_state == arc_anon) {
5456 		/*
5457 		 * This buffer is not in the cache, and does not
5458 		 * appear in our "ghost" list.  Add the new buffer
5459 		 * to the MRU state.
5460 		 */
5461 
5462 		ASSERT0(hdr->b_l1hdr.b_arc_access);
5463 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5464 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5465 		arc_change_state(arc_mru, hdr, hash_lock);
5466 
5467 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
5468 		now = ddi_get_lbolt();
5469 
5470 		/*
5471 		 * If this buffer is here because of a prefetch, then either:
5472 		 * - clear the flag if this is a "referencing" read
5473 		 *   (any subsequent access will bump this into the MFU state).
5474 		 * or
5475 		 * - move the buffer to the head of the list if this is
5476 		 *   another prefetch (to make it less likely to be evicted).
5477 		 */
5478 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5479 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5480 				/* link protected by hash lock */
5481 				ASSERT(multilist_link_active(
5482 				    &hdr->b_l1hdr.b_arc_node));
5483 			} else {
5484 				if (HDR_HAS_L2HDR(hdr))
5485 					l2arc_hdr_arcstats_decrement_state(hdr);
5486 				arc_hdr_clear_flags(hdr,
5487 				    ARC_FLAG_PREFETCH |
5488 				    ARC_FLAG_PRESCIENT_PREFETCH);
5489 				hdr->b_l1hdr.b_mru_hits++;
5490 				ARCSTAT_BUMP(arcstat_mru_hits);
5491 				if (HDR_HAS_L2HDR(hdr))
5492 					l2arc_hdr_arcstats_increment_state(hdr);
5493 			}
5494 			hdr->b_l1hdr.b_arc_access = now;
5495 			return;
5496 		}
5497 
5498 		/*
5499 		 * This buffer has been "accessed" only once so far,
5500 		 * but it is still in the cache. Move it to the MFU
5501 		 * state.
5502 		 */
5503 		if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
5504 		    ARC_MINTIME)) {
5505 			/*
5506 			 * More than 125ms have passed since we
5507 			 * instantiated this buffer.  Move it to the
5508 			 * most frequently used state.
5509 			 */
5510 			hdr->b_l1hdr.b_arc_access = now;
5511 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5512 			arc_change_state(arc_mfu, hdr, hash_lock);
5513 		}
5514 		hdr->b_l1hdr.b_mru_hits++;
5515 		ARCSTAT_BUMP(arcstat_mru_hits);
5516 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5517 		arc_state_t	*new_state;
5518 		/*
5519 		 * This buffer has been "accessed" recently, but
5520 		 * was evicted from the cache.  Move it to the
5521 		 * MFU state.
5522 		 */
5523 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5524 			new_state = arc_mru;
5525 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5526 				if (HDR_HAS_L2HDR(hdr))
5527 					l2arc_hdr_arcstats_decrement_state(hdr);
5528 				arc_hdr_clear_flags(hdr,
5529 				    ARC_FLAG_PREFETCH |
5530 				    ARC_FLAG_PRESCIENT_PREFETCH);
5531 				if (HDR_HAS_L2HDR(hdr))
5532 					l2arc_hdr_arcstats_increment_state(hdr);
5533 			}
5534 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5535 		} else {
5536 			new_state = arc_mfu;
5537 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5538 		}
5539 
5540 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5541 		arc_change_state(new_state, hdr, hash_lock);
5542 
5543 		hdr->b_l1hdr.b_mru_ghost_hits++;
5544 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5545 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
5546 		/*
5547 		 * This buffer has been accessed more than once and is
5548 		 * still in the cache.  Keep it in the MFU state.
5549 		 *
5550 		 * NOTE: an add_reference() that occurred when we did
5551 		 * the arc_read() will have kicked this off the list.
5552 		 * If it was a prefetch, we will explicitly move it to
5553 		 * the head of the list now.
5554 		 */
5555 
5556 		hdr->b_l1hdr.b_mfu_hits++;
5557 		ARCSTAT_BUMP(arcstat_mfu_hits);
5558 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5559 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5560 		arc_state_t	*new_state = arc_mfu;
5561 		/*
5562 		 * This buffer has been accessed more than once but has
5563 		 * been evicted from the cache.  Move it back to the
5564 		 * MFU state.
5565 		 */
5566 
5567 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5568 			/*
5569 			 * This is a prefetch access...
5570 			 * move this block back to the MRU state.
5571 			 */
5572 			new_state = arc_mru;
5573 		}
5574 
5575 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5576 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5577 		arc_change_state(new_state, hdr, hash_lock);
5578 
5579 		hdr->b_l1hdr.b_mfu_ghost_hits++;
5580 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5581 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5582 		/*
5583 		 * This buffer is on the 2nd Level ARC.
5584 		 */
5585 
5586 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5587 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5588 		arc_change_state(arc_mfu, hdr, hash_lock);
5589 	} else {
5590 		cmn_err(CE_PANIC, "invalid arc state 0x%p",
5591 		    hdr->b_l1hdr.b_state);
5592 	}
5593 }
5594 
5595 /*
5596  * This routine is called by dbuf_hold() to update the arc_access() state
5597  * which otherwise would be skipped for entries in the dbuf cache.
5598  */
5599 void
5600 arc_buf_access(arc_buf_t *buf)
5601 {
5602 	mutex_enter(&buf->b_evict_lock);
5603 	arc_buf_hdr_t *hdr = buf->b_hdr;
5604 
5605 	/*
5606 	 * Avoid taking the hash_lock when possible as an optimization.
5607 	 * The header must be checked again under the hash_lock in order
5608 	 * to handle the case where it is concurrently being released.
5609 	 */
5610 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5611 		mutex_exit(&buf->b_evict_lock);
5612 		return;
5613 	}
5614 
5615 	kmutex_t *hash_lock = HDR_LOCK(hdr);
5616 	mutex_enter(hash_lock);
5617 
5618 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5619 		mutex_exit(hash_lock);
5620 		mutex_exit(&buf->b_evict_lock);
5621 		ARCSTAT_BUMP(arcstat_access_skip);
5622 		return;
5623 	}
5624 
5625 	mutex_exit(&buf->b_evict_lock);
5626 
5627 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5628 	    hdr->b_l1hdr.b_state == arc_mfu);
5629 
5630 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5631 	arc_access(hdr, hash_lock);
5632 	mutex_exit(hash_lock);
5633 
5634 	ARCSTAT_BUMP(arcstat_hits);
5635 	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr) && !HDR_PRESCIENT_PREFETCH(hdr),
5636 	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5637 }
5638 
5639 /* a generic arc_read_done_func_t which you can use */
5640 void
5641 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5642     arc_buf_t *buf, void *arg)
5643 {
5644 	(void) zio, (void) zb, (void) bp;
5645 
5646 	if (buf == NULL)
5647 		return;
5648 
5649 	memcpy(arg, buf->b_data, arc_buf_size(buf));
5650 	arc_buf_destroy(buf, arg);
5651 }
5652 
5653 /* a generic arc_read_done_func_t */
5654 void
5655 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5656     arc_buf_t *buf, void *arg)
5657 {
5658 	(void) zb, (void) bp;
5659 	arc_buf_t **bufp = arg;
5660 
5661 	if (buf == NULL) {
5662 		ASSERT(zio == NULL || zio->io_error != 0);
5663 		*bufp = NULL;
5664 	} else {
5665 		ASSERT(zio == NULL || zio->io_error == 0);
5666 		*bufp = buf;
5667 		ASSERT(buf->b_data != NULL);
5668 	}
5669 }
5670 
5671 static void
5672 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5673 {
5674 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5675 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5676 		ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
5677 	} else {
5678 		if (HDR_COMPRESSION_ENABLED(hdr)) {
5679 			ASSERT3U(arc_hdr_get_compress(hdr), ==,
5680 			    BP_GET_COMPRESS(bp));
5681 		}
5682 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5683 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5684 		ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
5685 	}
5686 }
5687 
5688 static void
5689 arc_read_done(zio_t *zio)
5690 {
5691 	blkptr_t 	*bp = zio->io_bp;
5692 	arc_buf_hdr_t	*hdr = zio->io_private;
5693 	kmutex_t	*hash_lock = NULL;
5694 	arc_callback_t	*callback_list;
5695 	arc_callback_t	*acb;
5696 	boolean_t	freeable = B_FALSE;
5697 
5698 	/*
5699 	 * The hdr was inserted into hash-table and removed from lists
5700 	 * prior to starting I/O.  We should find this header, since
5701 	 * it's in the hash table, and it should be legit since it's
5702 	 * not possible to evict it during the I/O.  The only possible
5703 	 * reason for it not to be found is if we were freed during the
5704 	 * read.
5705 	 */
5706 	if (HDR_IN_HASH_TABLE(hdr)) {
5707 		arc_buf_hdr_t *found;
5708 
5709 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5710 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
5711 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
5712 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
5713 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
5714 
5715 		found = buf_hash_find(hdr->b_spa, zio->io_bp, &hash_lock);
5716 
5717 		ASSERT((found == hdr &&
5718 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5719 		    (found == hdr && HDR_L2_READING(hdr)));
5720 		ASSERT3P(hash_lock, !=, NULL);
5721 	}
5722 
5723 	if (BP_IS_PROTECTED(bp)) {
5724 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5725 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5726 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5727 		    hdr->b_crypt_hdr.b_iv);
5728 
5729 		if (zio->io_error == 0) {
5730 			if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5731 				void *tmpbuf;
5732 
5733 				tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5734 				    sizeof (zil_chain_t));
5735 				zio_crypt_decode_mac_zil(tmpbuf,
5736 				    hdr->b_crypt_hdr.b_mac);
5737 				abd_return_buf(zio->io_abd, tmpbuf,
5738 				    sizeof (zil_chain_t));
5739 			} else {
5740 				zio_crypt_decode_mac_bp(bp,
5741 				    hdr->b_crypt_hdr.b_mac);
5742 			}
5743 		}
5744 	}
5745 
5746 	if (zio->io_error == 0) {
5747 		/* byteswap if necessary */
5748 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5749 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
5750 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5751 			} else {
5752 				hdr->b_l1hdr.b_byteswap =
5753 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5754 			}
5755 		} else {
5756 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5757 		}
5758 		if (!HDR_L2_READING(hdr)) {
5759 			hdr->b_complevel = zio->io_prop.zp_complevel;
5760 		}
5761 	}
5762 
5763 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5764 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5765 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5766 
5767 	callback_list = hdr->b_l1hdr.b_acb;
5768 	ASSERT3P(callback_list, !=, NULL);
5769 
5770 	if (hash_lock && zio->io_error == 0 &&
5771 	    hdr->b_l1hdr.b_state == arc_anon) {
5772 		/*
5773 		 * Only call arc_access on anonymous buffers.  This is because
5774 		 * if we've issued an I/O for an evicted buffer, we've already
5775 		 * called arc_access (to prevent any simultaneous readers from
5776 		 * getting confused).
5777 		 */
5778 		arc_access(hdr, hash_lock);
5779 	}
5780 
5781 	/*
5782 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
5783 	 * make a buf containing the data according to the parameters which were
5784 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5785 	 * aren't needlessly decompressing the data multiple times.
5786 	 */
5787 	int callback_cnt = 0;
5788 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5789 		if (!acb->acb_done || acb->acb_nobuf)
5790 			continue;
5791 
5792 		callback_cnt++;
5793 
5794 		if (zio->io_error != 0)
5795 			continue;
5796 
5797 		int error = arc_buf_alloc_impl(hdr, zio->io_spa,
5798 		    &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
5799 		    acb->acb_compressed, acb->acb_noauth, B_TRUE,
5800 		    &acb->acb_buf);
5801 
5802 		/*
5803 		 * Assert non-speculative zios didn't fail because an
5804 		 * encryption key wasn't loaded
5805 		 */
5806 		ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
5807 		    error != EACCES);
5808 
5809 		/*
5810 		 * If we failed to decrypt, report an error now (as the zio
5811 		 * layer would have done if it had done the transforms).
5812 		 */
5813 		if (error == ECKSUM) {
5814 			ASSERT(BP_IS_PROTECTED(bp));
5815 			error = SET_ERROR(EIO);
5816 			if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5817 				spa_log_error(zio->io_spa, &acb->acb_zb);
5818 				(void) zfs_ereport_post(
5819 				    FM_EREPORT_ZFS_AUTHENTICATION,
5820 				    zio->io_spa, NULL, &acb->acb_zb, zio, 0);
5821 			}
5822 		}
5823 
5824 		if (error != 0) {
5825 			/*
5826 			 * Decompression or decryption failed.  Set
5827 			 * io_error so that when we call acb_done
5828 			 * (below), we will indicate that the read
5829 			 * failed. Note that in the unusual case
5830 			 * where one callback is compressed and another
5831 			 * uncompressed, we will mark all of them
5832 			 * as failed, even though the uncompressed
5833 			 * one can't actually fail.  In this case,
5834 			 * the hdr will not be anonymous, because
5835 			 * if there are multiple callbacks, it's
5836 			 * because multiple threads found the same
5837 			 * arc buf in the hash table.
5838 			 */
5839 			zio->io_error = error;
5840 		}
5841 	}
5842 
5843 	/*
5844 	 * If there are multiple callbacks, we must have the hash lock,
5845 	 * because the only way for multiple threads to find this hdr is
5846 	 * in the hash table.  This ensures that if there are multiple
5847 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
5848 	 * we couldn't use arc_buf_destroy() in the error case below.
5849 	 */
5850 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
5851 
5852 	hdr->b_l1hdr.b_acb = NULL;
5853 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5854 	if (callback_cnt == 0)
5855 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
5856 
5857 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5858 	    callback_list != NULL);
5859 
5860 	if (zio->io_error == 0) {
5861 		arc_hdr_verify(hdr, zio->io_bp);
5862 	} else {
5863 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5864 		if (hdr->b_l1hdr.b_state != arc_anon)
5865 			arc_change_state(arc_anon, hdr, hash_lock);
5866 		if (HDR_IN_HASH_TABLE(hdr))
5867 			buf_hash_remove(hdr);
5868 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5869 	}
5870 
5871 	/*
5872 	 * Broadcast before we drop the hash_lock to avoid the possibility
5873 	 * that the hdr (and hence the cv) might be freed before we get to
5874 	 * the cv_broadcast().
5875 	 */
5876 	cv_broadcast(&hdr->b_l1hdr.b_cv);
5877 
5878 	if (hash_lock != NULL) {
5879 		mutex_exit(hash_lock);
5880 	} else {
5881 		/*
5882 		 * This block was freed while we waited for the read to
5883 		 * complete.  It has been removed from the hash table and
5884 		 * moved to the anonymous state (so that it won't show up
5885 		 * in the cache).
5886 		 */
5887 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5888 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5889 	}
5890 
5891 	/* execute each callback and free its structure */
5892 	while ((acb = callback_list) != NULL) {
5893 		if (acb->acb_done != NULL) {
5894 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
5895 				/*
5896 				 * If arc_buf_alloc_impl() fails during
5897 				 * decompression, the buf will still be
5898 				 * allocated, and needs to be freed here.
5899 				 */
5900 				arc_buf_destroy(acb->acb_buf,
5901 				    acb->acb_private);
5902 				acb->acb_buf = NULL;
5903 			}
5904 			acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5905 			    acb->acb_buf, acb->acb_private);
5906 		}
5907 
5908 		if (acb->acb_zio_dummy != NULL) {
5909 			acb->acb_zio_dummy->io_error = zio->io_error;
5910 			zio_nowait(acb->acb_zio_dummy);
5911 		}
5912 
5913 		callback_list = acb->acb_next;
5914 		kmem_free(acb, sizeof (arc_callback_t));
5915 	}
5916 
5917 	if (freeable)
5918 		arc_hdr_destroy(hdr);
5919 }
5920 
5921 /*
5922  * "Read" the block at the specified DVA (in bp) via the
5923  * cache.  If the block is found in the cache, invoke the provided
5924  * callback immediately and return.  Note that the `zio' parameter
5925  * in the callback will be NULL in this case, since no IO was
5926  * required.  If the block is not in the cache pass the read request
5927  * on to the spa with a substitute callback function, so that the
5928  * requested block will be added to the cache.
5929  *
5930  * If a read request arrives for a block that has a read in-progress,
5931  * either wait for the in-progress read to complete (and return the
5932  * results); or, if this is a read with a "done" func, add a record
5933  * to the read to invoke the "done" func when the read completes,
5934  * and return; or just return.
5935  *
5936  * arc_read_done() will invoke all the requested "done" functions
5937  * for readers of this block.
5938  */
5939 int
5940 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
5941     arc_read_done_func_t *done, void *private, zio_priority_t priority,
5942     int zio_flags, arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5943 {
5944 	arc_buf_hdr_t *hdr = NULL;
5945 	kmutex_t *hash_lock = NULL;
5946 	zio_t *rzio;
5947 	uint64_t guid = spa_load_guid(spa);
5948 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5949 	boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5950 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5951 	boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5952 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5953 	boolean_t embedded_bp = !!BP_IS_EMBEDDED(bp);
5954 	boolean_t no_buf = *arc_flags & ARC_FLAG_NO_BUF;
5955 	int rc = 0;
5956 
5957 	ASSERT(!embedded_bp ||
5958 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5959 	ASSERT(!BP_IS_HOLE(bp));
5960 	ASSERT(!BP_IS_REDACTED(bp));
5961 
5962 	/*
5963 	 * Normally SPL_FSTRANS will already be set since kernel threads which
5964 	 * expect to call the DMU interfaces will set it when created.  System
5965 	 * calls are similarly handled by setting/cleaning the bit in the
5966 	 * registered callback (module/os/.../zfs/zpl_*).
5967 	 *
5968 	 * External consumers such as Lustre which call the exported DMU
5969 	 * interfaces may not have set SPL_FSTRANS.  To avoid a deadlock
5970 	 * on the hash_lock always set and clear the bit.
5971 	 */
5972 	fstrans_cookie_t cookie = spl_fstrans_mark();
5973 top:
5974 	/*
5975 	 * Verify the block pointer contents are reasonable.  This should
5976 	 * always be the case since the blkptr is protected by a checksum.
5977 	 * However, if there is damage it's desirable to detect this early
5978 	 * and treat it as a checksum error.  This allows an alternate blkptr
5979 	 * to be tried when one is available (e.g. ditto blocks).
5980 	 */
5981 	if (!zfs_blkptr_verify(spa, bp, zio_flags & ZIO_FLAG_CONFIG_WRITER,
5982 	    BLK_VERIFY_LOG)) {
5983 		rc = SET_ERROR(ECKSUM);
5984 		goto out;
5985 	}
5986 
5987 	if (!embedded_bp) {
5988 		/*
5989 		 * Embedded BP's have no DVA and require no I/O to "read".
5990 		 * Create an anonymous arc buf to back it.
5991 		 */
5992 		hdr = buf_hash_find(guid, bp, &hash_lock);
5993 	}
5994 
5995 	/*
5996 	 * Determine if we have an L1 cache hit or a cache miss. For simplicity
5997 	 * we maintain encrypted data separately from compressed / uncompressed
5998 	 * data. If the user is requesting raw encrypted data and we don't have
5999 	 * that in the header we will read from disk to guarantee that we can
6000 	 * get it even if the encryption keys aren't loaded.
6001 	 */
6002 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
6003 	    (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
6004 		arc_buf_t *buf = NULL;
6005 		*arc_flags |= ARC_FLAG_CACHED;
6006 
6007 		if (HDR_IO_IN_PROGRESS(hdr)) {
6008 			zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
6009 
6010 			if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
6011 				mutex_exit(hash_lock);
6012 				ARCSTAT_BUMP(arcstat_cached_only_in_progress);
6013 				rc = SET_ERROR(ENOENT);
6014 				goto out;
6015 			}
6016 
6017 			ASSERT3P(head_zio, !=, NULL);
6018 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
6019 			    priority == ZIO_PRIORITY_SYNC_READ) {
6020 				/*
6021 				 * This is a sync read that needs to wait for
6022 				 * an in-flight async read. Request that the
6023 				 * zio have its priority upgraded.
6024 				 */
6025 				zio_change_priority(head_zio, priority);
6026 				DTRACE_PROBE1(arc__async__upgrade__sync,
6027 				    arc_buf_hdr_t *, hdr);
6028 				ARCSTAT_BUMP(arcstat_async_upgrade_sync);
6029 			}
6030 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
6031 				arc_hdr_clear_flags(hdr,
6032 				    ARC_FLAG_PREDICTIVE_PREFETCH);
6033 			}
6034 
6035 			/*
6036 			 * If there are multiple threads reading the same block
6037 			 * and that block is not yet in the ARC, then only one
6038 			 * thread will do the physical I/O and all other
6039 			 * threads will wait until that I/O completes.
6040 			 * Synchronous reads use the b_cv whereas nowait reads
6041 			 * register a callback. Both are signalled/called in
6042 			 * arc_read_done.
6043 			 *
6044 			 * Errors of the physical I/O may need to be propagated
6045 			 * to the pio. For synchronous reads, we simply restart
6046 			 * this function and it will reassess.  Nowait reads
6047 			 * attach the acb_zio_dummy zio to pio and
6048 			 * arc_read_done propagates the physical I/O's io_error
6049 			 * to acb_zio_dummy, and thereby to pio.
6050 			 */
6051 
6052 			if (*arc_flags & ARC_FLAG_WAIT) {
6053 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
6054 				mutex_exit(hash_lock);
6055 				goto top;
6056 			}
6057 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6058 
6059 			if (done) {
6060 				arc_callback_t *acb = NULL;
6061 
6062 				acb = kmem_zalloc(sizeof (arc_callback_t),
6063 				    KM_SLEEP);
6064 				acb->acb_done = done;
6065 				acb->acb_private = private;
6066 				acb->acb_compressed = compressed_read;
6067 				acb->acb_encrypted = encrypted_read;
6068 				acb->acb_noauth = noauth_read;
6069 				acb->acb_nobuf = no_buf;
6070 				acb->acb_zb = *zb;
6071 				if (pio != NULL)
6072 					acb->acb_zio_dummy = zio_null(pio,
6073 					    spa, NULL, NULL, NULL, zio_flags);
6074 
6075 				ASSERT3P(acb->acb_done, !=, NULL);
6076 				acb->acb_zio_head = head_zio;
6077 				acb->acb_next = hdr->b_l1hdr.b_acb;
6078 				hdr->b_l1hdr.b_acb = acb;
6079 			}
6080 			mutex_exit(hash_lock);
6081 			goto out;
6082 		}
6083 
6084 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
6085 		    hdr->b_l1hdr.b_state == arc_mfu);
6086 
6087 		if (done && !no_buf) {
6088 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
6089 				/*
6090 				 * This is a demand read which does not have to
6091 				 * wait for i/o because we did a predictive
6092 				 * prefetch i/o for it, which has completed.
6093 				 */
6094 				DTRACE_PROBE1(
6095 				    arc__demand__hit__predictive__prefetch,
6096 				    arc_buf_hdr_t *, hdr);
6097 				ARCSTAT_BUMP(
6098 				    arcstat_demand_hit_predictive_prefetch);
6099 				arc_hdr_clear_flags(hdr,
6100 				    ARC_FLAG_PREDICTIVE_PREFETCH);
6101 			}
6102 
6103 			if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
6104 				ARCSTAT_BUMP(
6105 				    arcstat_demand_hit_prescient_prefetch);
6106 				arc_hdr_clear_flags(hdr,
6107 				    ARC_FLAG_PRESCIENT_PREFETCH);
6108 			}
6109 
6110 			ASSERT(!embedded_bp || !BP_IS_HOLE(bp));
6111 
6112 			/* Get a buf with the desired data in it. */
6113 			rc = arc_buf_alloc_impl(hdr, spa, zb, private,
6114 			    encrypted_read, compressed_read, noauth_read,
6115 			    B_TRUE, &buf);
6116 			if (rc == ECKSUM) {
6117 				/*
6118 				 * Convert authentication and decryption errors
6119 				 * to EIO (and generate an ereport if needed)
6120 				 * before leaving the ARC.
6121 				 */
6122 				rc = SET_ERROR(EIO);
6123 				if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
6124 					spa_log_error(spa, zb);
6125 					(void) zfs_ereport_post(
6126 					    FM_EREPORT_ZFS_AUTHENTICATION,
6127 					    spa, NULL, zb, NULL, 0);
6128 				}
6129 			}
6130 			if (rc != 0) {
6131 				(void) remove_reference(hdr, hash_lock,
6132 				    private);
6133 				arc_buf_destroy_impl(buf);
6134 				buf = NULL;
6135 			}
6136 
6137 			/* assert any errors weren't due to unloaded keys */
6138 			ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
6139 			    rc != EACCES);
6140 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
6141 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6142 			if (HDR_HAS_L2HDR(hdr))
6143 				l2arc_hdr_arcstats_decrement_state(hdr);
6144 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6145 			if (HDR_HAS_L2HDR(hdr))
6146 				l2arc_hdr_arcstats_increment_state(hdr);
6147 		}
6148 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
6149 		arc_access(hdr, hash_lock);
6150 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6151 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
6152 		if (*arc_flags & ARC_FLAG_L2CACHE)
6153 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6154 		mutex_exit(hash_lock);
6155 		ARCSTAT_BUMP(arcstat_hits);
6156 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
6157 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
6158 		    data, metadata, hits);
6159 
6160 		if (done)
6161 			done(NULL, zb, bp, buf, private);
6162 	} else {
6163 		uint64_t lsize = BP_GET_LSIZE(bp);
6164 		uint64_t psize = BP_GET_PSIZE(bp);
6165 		arc_callback_t *acb;
6166 		vdev_t *vd = NULL;
6167 		uint64_t addr = 0;
6168 		boolean_t devw = B_FALSE;
6169 		uint64_t size;
6170 		abd_t *hdr_abd;
6171 		int alloc_flags = encrypted_read ? ARC_HDR_ALLOC_RDATA : 0;
6172 
6173 		if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
6174 			rc = SET_ERROR(ENOENT);
6175 			if (hash_lock != NULL)
6176 				mutex_exit(hash_lock);
6177 			goto out;
6178 		}
6179 
6180 		if (hdr == NULL) {
6181 			/*
6182 			 * This block is not in the cache or it has
6183 			 * embedded data.
6184 			 */
6185 			arc_buf_hdr_t *exists = NULL;
6186 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
6187 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
6188 			    BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), 0, type);
6189 
6190 			if (!embedded_bp) {
6191 				hdr->b_dva = *BP_IDENTITY(bp);
6192 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
6193 				exists = buf_hash_insert(hdr, &hash_lock);
6194 			}
6195 			if (exists != NULL) {
6196 				/* somebody beat us to the hash insert */
6197 				mutex_exit(hash_lock);
6198 				buf_discard_identity(hdr);
6199 				arc_hdr_destroy(hdr);
6200 				goto top; /* restart the IO request */
6201 			}
6202 			alloc_flags |= ARC_HDR_DO_ADAPT;
6203 		} else {
6204 			/*
6205 			 * This block is in the ghost cache or encrypted data
6206 			 * was requested and we didn't have it. If it was
6207 			 * L2-only (and thus didn't have an L1 hdr),
6208 			 * we realloc the header to add an L1 hdr.
6209 			 */
6210 			if (!HDR_HAS_L1HDR(hdr)) {
6211 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
6212 				    hdr_full_cache);
6213 			}
6214 
6215 			if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
6216 				ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6217 				ASSERT(!HDR_HAS_RABD(hdr));
6218 				ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6219 				ASSERT0(zfs_refcount_count(
6220 				    &hdr->b_l1hdr.b_refcnt));
6221 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
6222 				ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
6223 			} else if (HDR_IO_IN_PROGRESS(hdr)) {
6224 				/*
6225 				 * If this header already had an IO in progress
6226 				 * and we are performing another IO to fetch
6227 				 * encrypted data we must wait until the first
6228 				 * IO completes so as not to confuse
6229 				 * arc_read_done(). This should be very rare
6230 				 * and so the performance impact shouldn't
6231 				 * matter.
6232 				 */
6233 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
6234 				mutex_exit(hash_lock);
6235 				goto top;
6236 			}
6237 
6238 			/*
6239 			 * This is a delicate dance that we play here.
6240 			 * This hdr might be in the ghost list so we access
6241 			 * it to move it out of the ghost list before we
6242 			 * initiate the read. If it's a prefetch then
6243 			 * it won't have a callback so we'll remove the
6244 			 * reference that arc_buf_alloc_impl() created. We
6245 			 * do this after we've called arc_access() to
6246 			 * avoid hitting an assert in remove_reference().
6247 			 */
6248 			arc_adapt(arc_hdr_size(hdr), hdr->b_l1hdr.b_state);
6249 			arc_access(hdr, hash_lock);
6250 		}
6251 
6252 		arc_hdr_alloc_abd(hdr, alloc_flags);
6253 		if (encrypted_read) {
6254 			ASSERT(HDR_HAS_RABD(hdr));
6255 			size = HDR_GET_PSIZE(hdr);
6256 			hdr_abd = hdr->b_crypt_hdr.b_rabd;
6257 			zio_flags |= ZIO_FLAG_RAW;
6258 		} else {
6259 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6260 			size = arc_hdr_size(hdr);
6261 			hdr_abd = hdr->b_l1hdr.b_pabd;
6262 
6263 			if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
6264 				zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6265 			}
6266 
6267 			/*
6268 			 * For authenticated bp's, we do not ask the ZIO layer
6269 			 * to authenticate them since this will cause the entire
6270 			 * IO to fail if the key isn't loaded. Instead, we
6271 			 * defer authentication until arc_buf_fill(), which will
6272 			 * verify the data when the key is available.
6273 			 */
6274 			if (BP_IS_AUTHENTICATED(bp))
6275 				zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
6276 		}
6277 
6278 		if (*arc_flags & ARC_FLAG_PREFETCH &&
6279 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6280 			if (HDR_HAS_L2HDR(hdr))
6281 				l2arc_hdr_arcstats_decrement_state(hdr);
6282 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6283 			if (HDR_HAS_L2HDR(hdr))
6284 				l2arc_hdr_arcstats_increment_state(hdr);
6285 		}
6286 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6287 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
6288 		if (*arc_flags & ARC_FLAG_L2CACHE)
6289 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6290 		if (BP_IS_AUTHENTICATED(bp))
6291 			arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6292 		if (BP_GET_LEVEL(bp) > 0)
6293 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
6294 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
6295 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
6296 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
6297 
6298 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
6299 		acb->acb_done = done;
6300 		acb->acb_private = private;
6301 		acb->acb_compressed = compressed_read;
6302 		acb->acb_encrypted = encrypted_read;
6303 		acb->acb_noauth = noauth_read;
6304 		acb->acb_zb = *zb;
6305 
6306 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6307 		hdr->b_l1hdr.b_acb = acb;
6308 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6309 
6310 		if (HDR_HAS_L2HDR(hdr) &&
6311 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
6312 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
6313 			addr = hdr->b_l2hdr.b_daddr;
6314 			/*
6315 			 * Lock out L2ARC device removal.
6316 			 */
6317 			if (vdev_is_dead(vd) ||
6318 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6319 				vd = NULL;
6320 		}
6321 
6322 		/*
6323 		 * We count both async reads and scrub IOs as asynchronous so
6324 		 * that both can be upgraded in the event of a cache hit while
6325 		 * the read IO is still in-flight.
6326 		 */
6327 		if (priority == ZIO_PRIORITY_ASYNC_READ ||
6328 		    priority == ZIO_PRIORITY_SCRUB)
6329 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6330 		else
6331 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6332 
6333 		/*
6334 		 * At this point, we have a level 1 cache miss or a blkptr
6335 		 * with embedded data.  Try again in L2ARC if possible.
6336 		 */
6337 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6338 
6339 		/*
6340 		 * Skip ARC stat bump for block pointers with embedded
6341 		 * data. The data are read from the blkptr itself via
6342 		 * decode_embedded_bp_compressed().
6343 		 */
6344 		if (!embedded_bp) {
6345 			DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr,
6346 			    blkptr_t *, bp, uint64_t, lsize,
6347 			    zbookmark_phys_t *, zb);
6348 			ARCSTAT_BUMP(arcstat_misses);
6349 			ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
6350 			    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data,
6351 			    metadata, misses);
6352 			zfs_racct_read(size, 1);
6353 		}
6354 
6355 		/* Check if the spa even has l2 configured */
6356 		const boolean_t spa_has_l2 = l2arc_ndev != 0 &&
6357 		    spa->spa_l2cache.sav_count > 0;
6358 
6359 		if (vd != NULL && spa_has_l2 && !(l2arc_norw && devw)) {
6360 			/*
6361 			 * Read from the L2ARC if the following are true:
6362 			 * 1. The L2ARC vdev was previously cached.
6363 			 * 2. This buffer still has L2ARC metadata.
6364 			 * 3. This buffer isn't currently writing to the L2ARC.
6365 			 * 4. The L2ARC entry wasn't evicted, which may
6366 			 *    also have invalidated the vdev.
6367 			 * 5. This isn't prefetch or l2arc_noprefetch is 0.
6368 			 */
6369 			if (HDR_HAS_L2HDR(hdr) &&
6370 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
6371 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
6372 				l2arc_read_callback_t *cb;
6373 				abd_t *abd;
6374 				uint64_t asize;
6375 
6376 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6377 				ARCSTAT_BUMP(arcstat_l2_hits);
6378 				hdr->b_l2hdr.b_hits++;
6379 
6380 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6381 				    KM_SLEEP);
6382 				cb->l2rcb_hdr = hdr;
6383 				cb->l2rcb_bp = *bp;
6384 				cb->l2rcb_zb = *zb;
6385 				cb->l2rcb_flags = zio_flags;
6386 
6387 				/*
6388 				 * When Compressed ARC is disabled, but the
6389 				 * L2ARC block is compressed, arc_hdr_size()
6390 				 * will have returned LSIZE rather than PSIZE.
6391 				 */
6392 				if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
6393 				    !HDR_COMPRESSION_ENABLED(hdr) &&
6394 				    HDR_GET_PSIZE(hdr) != 0) {
6395 					size = HDR_GET_PSIZE(hdr);
6396 				}
6397 
6398 				asize = vdev_psize_to_asize(vd, size);
6399 				if (asize != size) {
6400 					abd = abd_alloc_for_io(asize,
6401 					    HDR_ISTYPE_METADATA(hdr));
6402 					cb->l2rcb_abd = abd;
6403 				} else {
6404 					abd = hdr_abd;
6405 				}
6406 
6407 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6408 				    addr + asize <= vd->vdev_psize -
6409 				    VDEV_LABEL_END_SIZE);
6410 
6411 				/*
6412 				 * l2arc read.  The SCL_L2ARC lock will be
6413 				 * released by l2arc_read_done().
6414 				 * Issue a null zio if the underlying buffer
6415 				 * was squashed to zero size by compression.
6416 				 */
6417 				ASSERT3U(arc_hdr_get_compress(hdr), !=,
6418 				    ZIO_COMPRESS_EMPTY);
6419 				rzio = zio_read_phys(pio, vd, addr,
6420 				    asize, abd,
6421 				    ZIO_CHECKSUM_OFF,
6422 				    l2arc_read_done, cb, priority,
6423 				    zio_flags | ZIO_FLAG_DONT_CACHE |
6424 				    ZIO_FLAG_CANFAIL |
6425 				    ZIO_FLAG_DONT_PROPAGATE |
6426 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
6427 				acb->acb_zio_head = rzio;
6428 
6429 				if (hash_lock != NULL)
6430 					mutex_exit(hash_lock);
6431 
6432 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6433 				    zio_t *, rzio);
6434 				ARCSTAT_INCR(arcstat_l2_read_bytes,
6435 				    HDR_GET_PSIZE(hdr));
6436 
6437 				if (*arc_flags & ARC_FLAG_NOWAIT) {
6438 					zio_nowait(rzio);
6439 					goto out;
6440 				}
6441 
6442 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
6443 				if (zio_wait(rzio) == 0)
6444 					goto out;
6445 
6446 				/* l2arc read error; goto zio_read() */
6447 				if (hash_lock != NULL)
6448 					mutex_enter(hash_lock);
6449 			} else {
6450 				DTRACE_PROBE1(l2arc__miss,
6451 				    arc_buf_hdr_t *, hdr);
6452 				ARCSTAT_BUMP(arcstat_l2_misses);
6453 				if (HDR_L2_WRITING(hdr))
6454 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
6455 				spa_config_exit(spa, SCL_L2ARC, vd);
6456 			}
6457 		} else {
6458 			if (vd != NULL)
6459 				spa_config_exit(spa, SCL_L2ARC, vd);
6460 
6461 			/*
6462 			 * Only a spa with l2 should contribute to l2
6463 			 * miss stats.  (Including the case of having a
6464 			 * faulted cache device - that's also a miss.)
6465 			 */
6466 			if (spa_has_l2) {
6467 				/*
6468 				 * Skip ARC stat bump for block pointers with
6469 				 * embedded data. The data are read from the
6470 				 * blkptr itself via
6471 				 * decode_embedded_bp_compressed().
6472 				 */
6473 				if (!embedded_bp) {
6474 					DTRACE_PROBE1(l2arc__miss,
6475 					    arc_buf_hdr_t *, hdr);
6476 					ARCSTAT_BUMP(arcstat_l2_misses);
6477 				}
6478 			}
6479 		}
6480 
6481 		rzio = zio_read(pio, spa, bp, hdr_abd, size,
6482 		    arc_read_done, hdr, priority, zio_flags, zb);
6483 		acb->acb_zio_head = rzio;
6484 
6485 		if (hash_lock != NULL)
6486 			mutex_exit(hash_lock);
6487 
6488 		if (*arc_flags & ARC_FLAG_WAIT) {
6489 			rc = zio_wait(rzio);
6490 			goto out;
6491 		}
6492 
6493 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6494 		zio_nowait(rzio);
6495 	}
6496 
6497 out:
6498 	/* embedded bps don't actually go to disk */
6499 	if (!embedded_bp)
6500 		spa_read_history_add(spa, zb, *arc_flags);
6501 	spl_fstrans_unmark(cookie);
6502 	return (rc);
6503 }
6504 
6505 arc_prune_t *
6506 arc_add_prune_callback(arc_prune_func_t *func, void *private)
6507 {
6508 	arc_prune_t *p;
6509 
6510 	p = kmem_alloc(sizeof (*p), KM_SLEEP);
6511 	p->p_pfunc = func;
6512 	p->p_private = private;
6513 	list_link_init(&p->p_node);
6514 	zfs_refcount_create(&p->p_refcnt);
6515 
6516 	mutex_enter(&arc_prune_mtx);
6517 	zfs_refcount_add(&p->p_refcnt, &arc_prune_list);
6518 	list_insert_head(&arc_prune_list, p);
6519 	mutex_exit(&arc_prune_mtx);
6520 
6521 	return (p);
6522 }
6523 
6524 void
6525 arc_remove_prune_callback(arc_prune_t *p)
6526 {
6527 	boolean_t wait = B_FALSE;
6528 	mutex_enter(&arc_prune_mtx);
6529 	list_remove(&arc_prune_list, p);
6530 	if (zfs_refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
6531 		wait = B_TRUE;
6532 	mutex_exit(&arc_prune_mtx);
6533 
6534 	/* wait for arc_prune_task to finish */
6535 	if (wait)
6536 		taskq_wait_outstanding(arc_prune_taskq, 0);
6537 	ASSERT0(zfs_refcount_count(&p->p_refcnt));
6538 	zfs_refcount_destroy(&p->p_refcnt);
6539 	kmem_free(p, sizeof (*p));
6540 }
6541 
6542 /*
6543  * Notify the arc that a block was freed, and thus will never be used again.
6544  */
6545 void
6546 arc_freed(spa_t *spa, const blkptr_t *bp)
6547 {
6548 	arc_buf_hdr_t *hdr;
6549 	kmutex_t *hash_lock;
6550 	uint64_t guid = spa_load_guid(spa);
6551 
6552 	ASSERT(!BP_IS_EMBEDDED(bp));
6553 
6554 	hdr = buf_hash_find(guid, bp, &hash_lock);
6555 	if (hdr == NULL)
6556 		return;
6557 
6558 	/*
6559 	 * We might be trying to free a block that is still doing I/O
6560 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6561 	 * dmu_sync-ed block). If this block is being prefetched, then it
6562 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6563 	 * until the I/O completes. A block may also have a reference if it is
6564 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6565 	 * have written the new block to its final resting place on disk but
6566 	 * without the dedup flag set. This would have left the hdr in the MRU
6567 	 * state and discoverable. When the txg finally syncs it detects that
6568 	 * the block was overridden in open context and issues an override I/O.
6569 	 * Since this is a dedup block, the override I/O will determine if the
6570 	 * block is already in the DDT. If so, then it will replace the io_bp
6571 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
6572 	 * reaches the done callback, dbuf_write_override_done, it will
6573 	 * check to see if the io_bp and io_bp_override are identical.
6574 	 * If they are not, then it indicates that the bp was replaced with
6575 	 * the bp in the DDT and the override bp is freed. This allows
6576 	 * us to arrive here with a reference on a block that is being
6577 	 * freed. So if we have an I/O in progress, or a reference to
6578 	 * this hdr, then we don't destroy the hdr.
6579 	 */
6580 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6581 	    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6582 		arc_change_state(arc_anon, hdr, hash_lock);
6583 		arc_hdr_destroy(hdr);
6584 		mutex_exit(hash_lock);
6585 	} else {
6586 		mutex_exit(hash_lock);
6587 	}
6588 
6589 }
6590 
6591 /*
6592  * Release this buffer from the cache, making it an anonymous buffer.  This
6593  * must be done after a read and prior to modifying the buffer contents.
6594  * If the buffer has more than one reference, we must make
6595  * a new hdr for the buffer.
6596  */
6597 void
6598 arc_release(arc_buf_t *buf, const void *tag)
6599 {
6600 	arc_buf_hdr_t *hdr = buf->b_hdr;
6601 
6602 	/*
6603 	 * It would be nice to assert that if its DMU metadata (level >
6604 	 * 0 || it's the dnode file), then it must be syncing context.
6605 	 * But we don't know that information at this level.
6606 	 */
6607 
6608 	mutex_enter(&buf->b_evict_lock);
6609 
6610 	ASSERT(HDR_HAS_L1HDR(hdr));
6611 
6612 	/*
6613 	 * We don't grab the hash lock prior to this check, because if
6614 	 * the buffer's header is in the arc_anon state, it won't be
6615 	 * linked into the hash table.
6616 	 */
6617 	if (hdr->b_l1hdr.b_state == arc_anon) {
6618 		mutex_exit(&buf->b_evict_lock);
6619 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6620 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
6621 		ASSERT(!HDR_HAS_L2HDR(hdr));
6622 
6623 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6624 		ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6625 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6626 
6627 		hdr->b_l1hdr.b_arc_access = 0;
6628 
6629 		/*
6630 		 * If the buf is being overridden then it may already
6631 		 * have a hdr that is not empty.
6632 		 */
6633 		buf_discard_identity(hdr);
6634 		arc_buf_thaw(buf);
6635 
6636 		return;
6637 	}
6638 
6639 	kmutex_t *hash_lock = HDR_LOCK(hdr);
6640 	mutex_enter(hash_lock);
6641 
6642 	/*
6643 	 * This assignment is only valid as long as the hash_lock is
6644 	 * held, we must be careful not to reference state or the
6645 	 * b_state field after dropping the lock.
6646 	 */
6647 	arc_state_t *state = hdr->b_l1hdr.b_state;
6648 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6649 	ASSERT3P(state, !=, arc_anon);
6650 
6651 	/* this buffer is not on any list */
6652 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6653 
6654 	if (HDR_HAS_L2HDR(hdr)) {
6655 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6656 
6657 		/*
6658 		 * We have to recheck this conditional again now that
6659 		 * we're holding the l2ad_mtx to prevent a race with
6660 		 * another thread which might be concurrently calling
6661 		 * l2arc_evict(). In that case, l2arc_evict() might have
6662 		 * destroyed the header's L2 portion as we were waiting
6663 		 * to acquire the l2ad_mtx.
6664 		 */
6665 		if (HDR_HAS_L2HDR(hdr))
6666 			arc_hdr_l2hdr_destroy(hdr);
6667 
6668 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6669 	}
6670 
6671 	/*
6672 	 * Do we have more than one buf?
6673 	 */
6674 	if (hdr->b_l1hdr.b_bufcnt > 1) {
6675 		arc_buf_hdr_t *nhdr;
6676 		uint64_t spa = hdr->b_spa;
6677 		uint64_t psize = HDR_GET_PSIZE(hdr);
6678 		uint64_t lsize = HDR_GET_LSIZE(hdr);
6679 		boolean_t protected = HDR_PROTECTED(hdr);
6680 		enum zio_compress compress = arc_hdr_get_compress(hdr);
6681 		arc_buf_contents_t type = arc_buf_type(hdr);
6682 		VERIFY3U(hdr->b_type, ==, type);
6683 
6684 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6685 		(void) remove_reference(hdr, hash_lock, tag);
6686 
6687 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6688 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6689 			ASSERT(ARC_BUF_LAST(buf));
6690 		}
6691 
6692 		/*
6693 		 * Pull the data off of this hdr and attach it to
6694 		 * a new anonymous hdr. Also find the last buffer
6695 		 * in the hdr's buffer list.
6696 		 */
6697 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6698 		ASSERT3P(lastbuf, !=, NULL);
6699 
6700 		/*
6701 		 * If the current arc_buf_t and the hdr are sharing their data
6702 		 * buffer, then we must stop sharing that block.
6703 		 */
6704 		if (arc_buf_is_shared(buf)) {
6705 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6706 			VERIFY(!arc_buf_is_shared(lastbuf));
6707 
6708 			/*
6709 			 * First, sever the block sharing relationship between
6710 			 * buf and the arc_buf_hdr_t.
6711 			 */
6712 			arc_unshare_buf(hdr, buf);
6713 
6714 			/*
6715 			 * Now we need to recreate the hdr's b_pabd. Since we
6716 			 * have lastbuf handy, we try to share with it, but if
6717 			 * we can't then we allocate a new b_pabd and copy the
6718 			 * data from buf into it.
6719 			 */
6720 			if (arc_can_share(hdr, lastbuf)) {
6721 				arc_share_buf(hdr, lastbuf);
6722 			} else {
6723 				arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6724 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6725 				    buf->b_data, psize);
6726 			}
6727 			VERIFY3P(lastbuf->b_data, !=, NULL);
6728 		} else if (HDR_SHARED_DATA(hdr)) {
6729 			/*
6730 			 * Uncompressed shared buffers are always at the end
6731 			 * of the list. Compressed buffers don't have the
6732 			 * same requirements. This makes it hard to
6733 			 * simply assert that the lastbuf is shared so
6734 			 * we rely on the hdr's compression flags to determine
6735 			 * if we have a compressed, shared buffer.
6736 			 */
6737 			ASSERT(arc_buf_is_shared(lastbuf) ||
6738 			    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
6739 			ASSERT(!ARC_BUF_SHARED(buf));
6740 		}
6741 
6742 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
6743 		ASSERT3P(state, !=, arc_l2c_only);
6744 
6745 		(void) zfs_refcount_remove_many(&state->arcs_size,
6746 		    arc_buf_size(buf), buf);
6747 
6748 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6749 			ASSERT3P(state, !=, arc_l2c_only);
6750 			(void) zfs_refcount_remove_many(
6751 			    &state->arcs_esize[type],
6752 			    arc_buf_size(buf), buf);
6753 		}
6754 
6755 		hdr->b_l1hdr.b_bufcnt -= 1;
6756 		if (ARC_BUF_ENCRYPTED(buf))
6757 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
6758 
6759 		arc_cksum_verify(buf);
6760 		arc_buf_unwatch(buf);
6761 
6762 		/* if this is the last uncompressed buf free the checksum */
6763 		if (!arc_hdr_has_uncompressed_buf(hdr))
6764 			arc_cksum_free(hdr);
6765 
6766 		mutex_exit(hash_lock);
6767 
6768 		/*
6769 		 * Allocate a new hdr. The new hdr will contain a b_pabd
6770 		 * buffer which will be freed in arc_write().
6771 		 */
6772 		nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6773 		    compress, hdr->b_complevel, type);
6774 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6775 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6776 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6777 		VERIFY3U(nhdr->b_type, ==, type);
6778 		ASSERT(!HDR_SHARED_DATA(nhdr));
6779 
6780 		nhdr->b_l1hdr.b_buf = buf;
6781 		nhdr->b_l1hdr.b_bufcnt = 1;
6782 		if (ARC_BUF_ENCRYPTED(buf))
6783 			nhdr->b_crypt_hdr.b_ebufcnt = 1;
6784 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6785 		buf->b_hdr = nhdr;
6786 
6787 		mutex_exit(&buf->b_evict_lock);
6788 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
6789 		    arc_buf_size(buf), buf);
6790 	} else {
6791 		mutex_exit(&buf->b_evict_lock);
6792 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6793 		/* protected by hash lock, or hdr is on arc_anon */
6794 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6795 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6796 		hdr->b_l1hdr.b_mru_hits = 0;
6797 		hdr->b_l1hdr.b_mru_ghost_hits = 0;
6798 		hdr->b_l1hdr.b_mfu_hits = 0;
6799 		hdr->b_l1hdr.b_mfu_ghost_hits = 0;
6800 		arc_change_state(arc_anon, hdr, hash_lock);
6801 		hdr->b_l1hdr.b_arc_access = 0;
6802 
6803 		mutex_exit(hash_lock);
6804 		buf_discard_identity(hdr);
6805 		arc_buf_thaw(buf);
6806 	}
6807 }
6808 
6809 int
6810 arc_released(arc_buf_t *buf)
6811 {
6812 	int released;
6813 
6814 	mutex_enter(&buf->b_evict_lock);
6815 	released = (buf->b_data != NULL &&
6816 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
6817 	mutex_exit(&buf->b_evict_lock);
6818 	return (released);
6819 }
6820 
6821 #ifdef ZFS_DEBUG
6822 int
6823 arc_referenced(arc_buf_t *buf)
6824 {
6825 	int referenced;
6826 
6827 	mutex_enter(&buf->b_evict_lock);
6828 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6829 	mutex_exit(&buf->b_evict_lock);
6830 	return (referenced);
6831 }
6832 #endif
6833 
6834 static void
6835 arc_write_ready(zio_t *zio)
6836 {
6837 	arc_write_callback_t *callback = zio->io_private;
6838 	arc_buf_t *buf = callback->awcb_buf;
6839 	arc_buf_hdr_t *hdr = buf->b_hdr;
6840 	blkptr_t *bp = zio->io_bp;
6841 	uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6842 	fstrans_cookie_t cookie = spl_fstrans_mark();
6843 
6844 	ASSERT(HDR_HAS_L1HDR(hdr));
6845 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6846 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6847 
6848 	/*
6849 	 * If we're reexecuting this zio because the pool suspended, then
6850 	 * cleanup any state that was previously set the first time the
6851 	 * callback was invoked.
6852 	 */
6853 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6854 		arc_cksum_free(hdr);
6855 		arc_buf_unwatch(buf);
6856 		if (hdr->b_l1hdr.b_pabd != NULL) {
6857 			if (arc_buf_is_shared(buf)) {
6858 				arc_unshare_buf(hdr, buf);
6859 			} else {
6860 				arc_hdr_free_abd(hdr, B_FALSE);
6861 			}
6862 		}
6863 
6864 		if (HDR_HAS_RABD(hdr))
6865 			arc_hdr_free_abd(hdr, B_TRUE);
6866 	}
6867 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6868 	ASSERT(!HDR_HAS_RABD(hdr));
6869 	ASSERT(!HDR_SHARED_DATA(hdr));
6870 	ASSERT(!arc_buf_is_shared(buf));
6871 
6872 	callback->awcb_ready(zio, buf, callback->awcb_private);
6873 
6874 	if (HDR_IO_IN_PROGRESS(hdr))
6875 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6876 
6877 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6878 
6879 	if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6880 		hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6881 
6882 	if (BP_IS_PROTECTED(bp)) {
6883 		/* ZIL blocks are written through zio_rewrite */
6884 		ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6885 		ASSERT(HDR_PROTECTED(hdr));
6886 
6887 		if (BP_SHOULD_BYTESWAP(bp)) {
6888 			if (BP_GET_LEVEL(bp) > 0) {
6889 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6890 			} else {
6891 				hdr->b_l1hdr.b_byteswap =
6892 				    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6893 			}
6894 		} else {
6895 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6896 		}
6897 
6898 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6899 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6900 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6901 		    hdr->b_crypt_hdr.b_iv);
6902 		zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6903 	}
6904 
6905 	/*
6906 	 * If this block was written for raw encryption but the zio layer
6907 	 * ended up only authenticating it, adjust the buffer flags now.
6908 	 */
6909 	if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6910 		arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6911 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6912 		if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6913 			buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6914 	} else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6915 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6916 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6917 	}
6918 
6919 	/* this must be done after the buffer flags are adjusted */
6920 	arc_cksum_compute(buf);
6921 
6922 	enum zio_compress compress;
6923 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6924 		compress = ZIO_COMPRESS_OFF;
6925 	} else {
6926 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6927 		compress = BP_GET_COMPRESS(bp);
6928 	}
6929 	HDR_SET_PSIZE(hdr, psize);
6930 	arc_hdr_set_compress(hdr, compress);
6931 	hdr->b_complevel = zio->io_prop.zp_complevel;
6932 
6933 	if (zio->io_error != 0 || psize == 0)
6934 		goto out;
6935 
6936 	/*
6937 	 * Fill the hdr with data. If the buffer is encrypted we have no choice
6938 	 * but to copy the data into b_radb. If the hdr is compressed, the data
6939 	 * we want is available from the zio, otherwise we can take it from
6940 	 * the buf.
6941 	 *
6942 	 * We might be able to share the buf's data with the hdr here. However,
6943 	 * doing so would cause the ARC to be full of linear ABDs if we write a
6944 	 * lot of shareable data. As a compromise, we check whether scattered
6945 	 * ABDs are allowed, and assume that if they are then the user wants
6946 	 * the ARC to be primarily filled with them regardless of the data being
6947 	 * written. Therefore, if they're allowed then we allocate one and copy
6948 	 * the data into it; otherwise, we share the data directly if we can.
6949 	 */
6950 	if (ARC_BUF_ENCRYPTED(buf)) {
6951 		ASSERT3U(psize, >, 0);
6952 		ASSERT(ARC_BUF_COMPRESSED(buf));
6953 		arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT | ARC_HDR_ALLOC_RDATA |
6954 		    ARC_HDR_USE_RESERVE);
6955 		abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6956 	} else if (!abd_size_alloc_linear(arc_buf_size(buf)) ||
6957 	    !arc_can_share(hdr, buf)) {
6958 		/*
6959 		 * Ideally, we would always copy the io_abd into b_pabd, but the
6960 		 * user may have disabled compressed ARC, thus we must check the
6961 		 * hdr's compression setting rather than the io_bp's.
6962 		 */
6963 		if (BP_IS_ENCRYPTED(bp)) {
6964 			ASSERT3U(psize, >, 0);
6965 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT |
6966 			    ARC_HDR_ALLOC_RDATA | ARC_HDR_USE_RESERVE);
6967 			abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6968 		} else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6969 		    !ARC_BUF_COMPRESSED(buf)) {
6970 			ASSERT3U(psize, >, 0);
6971 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT |
6972 			    ARC_HDR_USE_RESERVE);
6973 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6974 		} else {
6975 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6976 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT |
6977 			    ARC_HDR_USE_RESERVE);
6978 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6979 			    arc_buf_size(buf));
6980 		}
6981 	} else {
6982 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6983 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6984 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6985 
6986 		arc_share_buf(hdr, buf);
6987 	}
6988 
6989 out:
6990 	arc_hdr_verify(hdr, bp);
6991 	spl_fstrans_unmark(cookie);
6992 }
6993 
6994 static void
6995 arc_write_children_ready(zio_t *zio)
6996 {
6997 	arc_write_callback_t *callback = zio->io_private;
6998 	arc_buf_t *buf = callback->awcb_buf;
6999 
7000 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
7001 }
7002 
7003 /*
7004  * The SPA calls this callback for each physical write that happens on behalf
7005  * of a logical write.  See the comment in dbuf_write_physdone() for details.
7006  */
7007 static void
7008 arc_write_physdone(zio_t *zio)
7009 {
7010 	arc_write_callback_t *cb = zio->io_private;
7011 	if (cb->awcb_physdone != NULL)
7012 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
7013 }
7014 
7015 static void
7016 arc_write_done(zio_t *zio)
7017 {
7018 	arc_write_callback_t *callback = zio->io_private;
7019 	arc_buf_t *buf = callback->awcb_buf;
7020 	arc_buf_hdr_t *hdr = buf->b_hdr;
7021 
7022 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
7023 
7024 	if (zio->io_error == 0) {
7025 		arc_hdr_verify(hdr, zio->io_bp);
7026 
7027 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
7028 			buf_discard_identity(hdr);
7029 		} else {
7030 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
7031 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
7032 		}
7033 	} else {
7034 		ASSERT(HDR_EMPTY(hdr));
7035 	}
7036 
7037 	/*
7038 	 * If the block to be written was all-zero or compressed enough to be
7039 	 * embedded in the BP, no write was performed so there will be no
7040 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
7041 	 * (and uncached).
7042 	 */
7043 	if (!HDR_EMPTY(hdr)) {
7044 		arc_buf_hdr_t *exists;
7045 		kmutex_t *hash_lock;
7046 
7047 		ASSERT3U(zio->io_error, ==, 0);
7048 
7049 		arc_cksum_verify(buf);
7050 
7051 		exists = buf_hash_insert(hdr, &hash_lock);
7052 		if (exists != NULL) {
7053 			/*
7054 			 * This can only happen if we overwrite for
7055 			 * sync-to-convergence, because we remove
7056 			 * buffers from the hash table when we arc_free().
7057 			 */
7058 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
7059 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
7060 					panic("bad overwrite, hdr=%p exists=%p",
7061 					    (void *)hdr, (void *)exists);
7062 				ASSERT(zfs_refcount_is_zero(
7063 				    &exists->b_l1hdr.b_refcnt));
7064 				arc_change_state(arc_anon, exists, hash_lock);
7065 				arc_hdr_destroy(exists);
7066 				mutex_exit(hash_lock);
7067 				exists = buf_hash_insert(hdr, &hash_lock);
7068 				ASSERT3P(exists, ==, NULL);
7069 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
7070 				/* nopwrite */
7071 				ASSERT(zio->io_prop.zp_nopwrite);
7072 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
7073 					panic("bad nopwrite, hdr=%p exists=%p",
7074 					    (void *)hdr, (void *)exists);
7075 			} else {
7076 				/* Dedup */
7077 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
7078 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
7079 				ASSERT(BP_GET_DEDUP(zio->io_bp));
7080 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
7081 			}
7082 		}
7083 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
7084 		/* if it's not anon, we are doing a scrub */
7085 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
7086 			arc_access(hdr, hash_lock);
7087 		mutex_exit(hash_lock);
7088 	} else {
7089 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
7090 	}
7091 
7092 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
7093 	callback->awcb_done(zio, buf, callback->awcb_private);
7094 
7095 	abd_free(zio->io_abd);
7096 	kmem_free(callback, sizeof (arc_write_callback_t));
7097 }
7098 
7099 zio_t *
7100 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
7101     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc,
7102     const zio_prop_t *zp, arc_write_done_func_t *ready,
7103     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
7104     arc_write_done_func_t *done, void *private, zio_priority_t priority,
7105     int zio_flags, const zbookmark_phys_t *zb)
7106 {
7107 	arc_buf_hdr_t *hdr = buf->b_hdr;
7108 	arc_write_callback_t *callback;
7109 	zio_t *zio;
7110 	zio_prop_t localprop = *zp;
7111 
7112 	ASSERT3P(ready, !=, NULL);
7113 	ASSERT3P(done, !=, NULL);
7114 	ASSERT(!HDR_IO_ERROR(hdr));
7115 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
7116 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
7117 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
7118 	if (l2arc)
7119 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
7120 
7121 	if (ARC_BUF_ENCRYPTED(buf)) {
7122 		ASSERT(ARC_BUF_COMPRESSED(buf));
7123 		localprop.zp_encrypt = B_TRUE;
7124 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
7125 		localprop.zp_complevel = hdr->b_complevel;
7126 		localprop.zp_byteorder =
7127 		    (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
7128 		    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
7129 		memcpy(localprop.zp_salt, hdr->b_crypt_hdr.b_salt,
7130 		    ZIO_DATA_SALT_LEN);
7131 		memcpy(localprop.zp_iv, hdr->b_crypt_hdr.b_iv,
7132 		    ZIO_DATA_IV_LEN);
7133 		memcpy(localprop.zp_mac, hdr->b_crypt_hdr.b_mac,
7134 		    ZIO_DATA_MAC_LEN);
7135 		if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
7136 			localprop.zp_nopwrite = B_FALSE;
7137 			localprop.zp_copies =
7138 			    MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
7139 		}
7140 		zio_flags |= ZIO_FLAG_RAW;
7141 	} else if (ARC_BUF_COMPRESSED(buf)) {
7142 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
7143 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
7144 		localprop.zp_complevel = hdr->b_complevel;
7145 		zio_flags |= ZIO_FLAG_RAW_COMPRESS;
7146 	}
7147 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
7148 	callback->awcb_ready = ready;
7149 	callback->awcb_children_ready = children_ready;
7150 	callback->awcb_physdone = physdone;
7151 	callback->awcb_done = done;
7152 	callback->awcb_private = private;
7153 	callback->awcb_buf = buf;
7154 
7155 	/*
7156 	 * The hdr's b_pabd is now stale, free it now. A new data block
7157 	 * will be allocated when the zio pipeline calls arc_write_ready().
7158 	 */
7159 	if (hdr->b_l1hdr.b_pabd != NULL) {
7160 		/*
7161 		 * If the buf is currently sharing the data block with
7162 		 * the hdr then we need to break that relationship here.
7163 		 * The hdr will remain with a NULL data pointer and the
7164 		 * buf will take sole ownership of the block.
7165 		 */
7166 		if (arc_buf_is_shared(buf)) {
7167 			arc_unshare_buf(hdr, buf);
7168 		} else {
7169 			arc_hdr_free_abd(hdr, B_FALSE);
7170 		}
7171 		VERIFY3P(buf->b_data, !=, NULL);
7172 	}
7173 
7174 	if (HDR_HAS_RABD(hdr))
7175 		arc_hdr_free_abd(hdr, B_TRUE);
7176 
7177 	if (!(zio_flags & ZIO_FLAG_RAW))
7178 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
7179 
7180 	ASSERT(!arc_buf_is_shared(buf));
7181 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
7182 
7183 	zio = zio_write(pio, spa, txg, bp,
7184 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
7185 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
7186 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
7187 	    arc_write_physdone, arc_write_done, callback,
7188 	    priority, zio_flags, zb);
7189 
7190 	return (zio);
7191 }
7192 
7193 void
7194 arc_tempreserve_clear(uint64_t reserve)
7195 {
7196 	atomic_add_64(&arc_tempreserve, -reserve);
7197 	ASSERT((int64_t)arc_tempreserve >= 0);
7198 }
7199 
7200 int
7201 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
7202 {
7203 	int error;
7204 	uint64_t anon_size;
7205 
7206 	if (!arc_no_grow &&
7207 	    reserve > arc_c/4 &&
7208 	    reserve * 4 > (2ULL << SPA_MAXBLOCKSHIFT))
7209 		arc_c = MIN(arc_c_max, reserve * 4);
7210 
7211 	/*
7212 	 * Throttle when the calculated memory footprint for the TXG
7213 	 * exceeds the target ARC size.
7214 	 */
7215 	if (reserve > arc_c) {
7216 		DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
7217 		return (SET_ERROR(ERESTART));
7218 	}
7219 
7220 	/*
7221 	 * Don't count loaned bufs as in flight dirty data to prevent long
7222 	 * network delays from blocking transactions that are ready to be
7223 	 * assigned to a txg.
7224 	 */
7225 
7226 	/* assert that it has not wrapped around */
7227 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
7228 
7229 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
7230 	    arc_loaned_bytes), 0);
7231 
7232 	/*
7233 	 * Writes will, almost always, require additional memory allocations
7234 	 * in order to compress/encrypt/etc the data.  We therefore need to
7235 	 * make sure that there is sufficient available memory for this.
7236 	 */
7237 	error = arc_memory_throttle(spa, reserve, txg);
7238 	if (error != 0)
7239 		return (error);
7240 
7241 	/*
7242 	 * Throttle writes when the amount of dirty data in the cache
7243 	 * gets too large.  We try to keep the cache less than half full
7244 	 * of dirty blocks so that our sync times don't grow too large.
7245 	 *
7246 	 * In the case of one pool being built on another pool, we want
7247 	 * to make sure we don't end up throttling the lower (backing)
7248 	 * pool when the upper pool is the majority contributor to dirty
7249 	 * data. To insure we make forward progress during throttling, we
7250 	 * also check the current pool's net dirty data and only throttle
7251 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
7252 	 * data in the cache.
7253 	 *
7254 	 * Note: if two requests come in concurrently, we might let them
7255 	 * both succeed, when one of them should fail.  Not a huge deal.
7256 	 */
7257 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
7258 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
7259 	uint64_t rarc_c = arc_warm ? arc_c : arc_c_max;
7260 	if (total_dirty > rarc_c * zfs_arc_dirty_limit_percent / 100 &&
7261 	    anon_size > rarc_c * zfs_arc_anon_limit_percent / 100 &&
7262 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
7263 #ifdef ZFS_DEBUG
7264 		uint64_t meta_esize = zfs_refcount_count(
7265 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7266 		uint64_t data_esize =
7267 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7268 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
7269 		    "anon_data=%lluK tempreserve=%lluK rarc_c=%lluK\n",
7270 		    (u_longlong_t)arc_tempreserve >> 10,
7271 		    (u_longlong_t)meta_esize >> 10,
7272 		    (u_longlong_t)data_esize >> 10,
7273 		    (u_longlong_t)reserve >> 10,
7274 		    (u_longlong_t)rarc_c >> 10);
7275 #endif
7276 		DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
7277 		return (SET_ERROR(ERESTART));
7278 	}
7279 	atomic_add_64(&arc_tempreserve, reserve);
7280 	return (0);
7281 }
7282 
7283 static void
7284 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
7285     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
7286 {
7287 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
7288 	evict_data->value.ui64 =
7289 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
7290 	evict_metadata->value.ui64 =
7291 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
7292 }
7293 
7294 static int
7295 arc_kstat_update(kstat_t *ksp, int rw)
7296 {
7297 	arc_stats_t *as = ksp->ks_data;
7298 
7299 	if (rw == KSTAT_WRITE)
7300 		return (SET_ERROR(EACCES));
7301 
7302 	as->arcstat_hits.value.ui64 =
7303 	    wmsum_value(&arc_sums.arcstat_hits);
7304 	as->arcstat_misses.value.ui64 =
7305 	    wmsum_value(&arc_sums.arcstat_misses);
7306 	as->arcstat_demand_data_hits.value.ui64 =
7307 	    wmsum_value(&arc_sums.arcstat_demand_data_hits);
7308 	as->arcstat_demand_data_misses.value.ui64 =
7309 	    wmsum_value(&arc_sums.arcstat_demand_data_misses);
7310 	as->arcstat_demand_metadata_hits.value.ui64 =
7311 	    wmsum_value(&arc_sums.arcstat_demand_metadata_hits);
7312 	as->arcstat_demand_metadata_misses.value.ui64 =
7313 	    wmsum_value(&arc_sums.arcstat_demand_metadata_misses);
7314 	as->arcstat_prefetch_data_hits.value.ui64 =
7315 	    wmsum_value(&arc_sums.arcstat_prefetch_data_hits);
7316 	as->arcstat_prefetch_data_misses.value.ui64 =
7317 	    wmsum_value(&arc_sums.arcstat_prefetch_data_misses);
7318 	as->arcstat_prefetch_metadata_hits.value.ui64 =
7319 	    wmsum_value(&arc_sums.arcstat_prefetch_metadata_hits);
7320 	as->arcstat_prefetch_metadata_misses.value.ui64 =
7321 	    wmsum_value(&arc_sums.arcstat_prefetch_metadata_misses);
7322 	as->arcstat_mru_hits.value.ui64 =
7323 	    wmsum_value(&arc_sums.arcstat_mru_hits);
7324 	as->arcstat_mru_ghost_hits.value.ui64 =
7325 	    wmsum_value(&arc_sums.arcstat_mru_ghost_hits);
7326 	as->arcstat_mfu_hits.value.ui64 =
7327 	    wmsum_value(&arc_sums.arcstat_mfu_hits);
7328 	as->arcstat_mfu_ghost_hits.value.ui64 =
7329 	    wmsum_value(&arc_sums.arcstat_mfu_ghost_hits);
7330 	as->arcstat_deleted.value.ui64 =
7331 	    wmsum_value(&arc_sums.arcstat_deleted);
7332 	as->arcstat_mutex_miss.value.ui64 =
7333 	    wmsum_value(&arc_sums.arcstat_mutex_miss);
7334 	as->arcstat_access_skip.value.ui64 =
7335 	    wmsum_value(&arc_sums.arcstat_access_skip);
7336 	as->arcstat_evict_skip.value.ui64 =
7337 	    wmsum_value(&arc_sums.arcstat_evict_skip);
7338 	as->arcstat_evict_not_enough.value.ui64 =
7339 	    wmsum_value(&arc_sums.arcstat_evict_not_enough);
7340 	as->arcstat_evict_l2_cached.value.ui64 =
7341 	    wmsum_value(&arc_sums.arcstat_evict_l2_cached);
7342 	as->arcstat_evict_l2_eligible.value.ui64 =
7343 	    wmsum_value(&arc_sums.arcstat_evict_l2_eligible);
7344 	as->arcstat_evict_l2_eligible_mfu.value.ui64 =
7345 	    wmsum_value(&arc_sums.arcstat_evict_l2_eligible_mfu);
7346 	as->arcstat_evict_l2_eligible_mru.value.ui64 =
7347 	    wmsum_value(&arc_sums.arcstat_evict_l2_eligible_mru);
7348 	as->arcstat_evict_l2_ineligible.value.ui64 =
7349 	    wmsum_value(&arc_sums.arcstat_evict_l2_ineligible);
7350 	as->arcstat_evict_l2_skip.value.ui64 =
7351 	    wmsum_value(&arc_sums.arcstat_evict_l2_skip);
7352 	as->arcstat_hash_collisions.value.ui64 =
7353 	    wmsum_value(&arc_sums.arcstat_hash_collisions);
7354 	as->arcstat_hash_chains.value.ui64 =
7355 	    wmsum_value(&arc_sums.arcstat_hash_chains);
7356 	as->arcstat_size.value.ui64 =
7357 	    aggsum_value(&arc_sums.arcstat_size);
7358 	as->arcstat_compressed_size.value.ui64 =
7359 	    wmsum_value(&arc_sums.arcstat_compressed_size);
7360 	as->arcstat_uncompressed_size.value.ui64 =
7361 	    wmsum_value(&arc_sums.arcstat_uncompressed_size);
7362 	as->arcstat_overhead_size.value.ui64 =
7363 	    wmsum_value(&arc_sums.arcstat_overhead_size);
7364 	as->arcstat_hdr_size.value.ui64 =
7365 	    wmsum_value(&arc_sums.arcstat_hdr_size);
7366 	as->arcstat_data_size.value.ui64 =
7367 	    wmsum_value(&arc_sums.arcstat_data_size);
7368 	as->arcstat_metadata_size.value.ui64 =
7369 	    wmsum_value(&arc_sums.arcstat_metadata_size);
7370 	as->arcstat_dbuf_size.value.ui64 =
7371 	    wmsum_value(&arc_sums.arcstat_dbuf_size);
7372 #if defined(COMPAT_FREEBSD11)
7373 	as->arcstat_other_size.value.ui64 =
7374 	    wmsum_value(&arc_sums.arcstat_bonus_size) +
7375 	    aggsum_value(&arc_sums.arcstat_dnode_size) +
7376 	    wmsum_value(&arc_sums.arcstat_dbuf_size);
7377 #endif
7378 
7379 	arc_kstat_update_state(arc_anon,
7380 	    &as->arcstat_anon_size,
7381 	    &as->arcstat_anon_evictable_data,
7382 	    &as->arcstat_anon_evictable_metadata);
7383 	arc_kstat_update_state(arc_mru,
7384 	    &as->arcstat_mru_size,
7385 	    &as->arcstat_mru_evictable_data,
7386 	    &as->arcstat_mru_evictable_metadata);
7387 	arc_kstat_update_state(arc_mru_ghost,
7388 	    &as->arcstat_mru_ghost_size,
7389 	    &as->arcstat_mru_ghost_evictable_data,
7390 	    &as->arcstat_mru_ghost_evictable_metadata);
7391 	arc_kstat_update_state(arc_mfu,
7392 	    &as->arcstat_mfu_size,
7393 	    &as->arcstat_mfu_evictable_data,
7394 	    &as->arcstat_mfu_evictable_metadata);
7395 	arc_kstat_update_state(arc_mfu_ghost,
7396 	    &as->arcstat_mfu_ghost_size,
7397 	    &as->arcstat_mfu_ghost_evictable_data,
7398 	    &as->arcstat_mfu_ghost_evictable_metadata);
7399 
7400 	as->arcstat_dnode_size.value.ui64 =
7401 	    aggsum_value(&arc_sums.arcstat_dnode_size);
7402 	as->arcstat_bonus_size.value.ui64 =
7403 	    wmsum_value(&arc_sums.arcstat_bonus_size);
7404 	as->arcstat_l2_hits.value.ui64 =
7405 	    wmsum_value(&arc_sums.arcstat_l2_hits);
7406 	as->arcstat_l2_misses.value.ui64 =
7407 	    wmsum_value(&arc_sums.arcstat_l2_misses);
7408 	as->arcstat_l2_prefetch_asize.value.ui64 =
7409 	    wmsum_value(&arc_sums.arcstat_l2_prefetch_asize);
7410 	as->arcstat_l2_mru_asize.value.ui64 =
7411 	    wmsum_value(&arc_sums.arcstat_l2_mru_asize);
7412 	as->arcstat_l2_mfu_asize.value.ui64 =
7413 	    wmsum_value(&arc_sums.arcstat_l2_mfu_asize);
7414 	as->arcstat_l2_bufc_data_asize.value.ui64 =
7415 	    wmsum_value(&arc_sums.arcstat_l2_bufc_data_asize);
7416 	as->arcstat_l2_bufc_metadata_asize.value.ui64 =
7417 	    wmsum_value(&arc_sums.arcstat_l2_bufc_metadata_asize);
7418 	as->arcstat_l2_feeds.value.ui64 =
7419 	    wmsum_value(&arc_sums.arcstat_l2_feeds);
7420 	as->arcstat_l2_rw_clash.value.ui64 =
7421 	    wmsum_value(&arc_sums.arcstat_l2_rw_clash);
7422 	as->arcstat_l2_read_bytes.value.ui64 =
7423 	    wmsum_value(&arc_sums.arcstat_l2_read_bytes);
7424 	as->arcstat_l2_write_bytes.value.ui64 =
7425 	    wmsum_value(&arc_sums.arcstat_l2_write_bytes);
7426 	as->arcstat_l2_writes_sent.value.ui64 =
7427 	    wmsum_value(&arc_sums.arcstat_l2_writes_sent);
7428 	as->arcstat_l2_writes_done.value.ui64 =
7429 	    wmsum_value(&arc_sums.arcstat_l2_writes_done);
7430 	as->arcstat_l2_writes_error.value.ui64 =
7431 	    wmsum_value(&arc_sums.arcstat_l2_writes_error);
7432 	as->arcstat_l2_writes_lock_retry.value.ui64 =
7433 	    wmsum_value(&arc_sums.arcstat_l2_writes_lock_retry);
7434 	as->arcstat_l2_evict_lock_retry.value.ui64 =
7435 	    wmsum_value(&arc_sums.arcstat_l2_evict_lock_retry);
7436 	as->arcstat_l2_evict_reading.value.ui64 =
7437 	    wmsum_value(&arc_sums.arcstat_l2_evict_reading);
7438 	as->arcstat_l2_evict_l1cached.value.ui64 =
7439 	    wmsum_value(&arc_sums.arcstat_l2_evict_l1cached);
7440 	as->arcstat_l2_free_on_write.value.ui64 =
7441 	    wmsum_value(&arc_sums.arcstat_l2_free_on_write);
7442 	as->arcstat_l2_abort_lowmem.value.ui64 =
7443 	    wmsum_value(&arc_sums.arcstat_l2_abort_lowmem);
7444 	as->arcstat_l2_cksum_bad.value.ui64 =
7445 	    wmsum_value(&arc_sums.arcstat_l2_cksum_bad);
7446 	as->arcstat_l2_io_error.value.ui64 =
7447 	    wmsum_value(&arc_sums.arcstat_l2_io_error);
7448 	as->arcstat_l2_lsize.value.ui64 =
7449 	    wmsum_value(&arc_sums.arcstat_l2_lsize);
7450 	as->arcstat_l2_psize.value.ui64 =
7451 	    wmsum_value(&arc_sums.arcstat_l2_psize);
7452 	as->arcstat_l2_hdr_size.value.ui64 =
7453 	    aggsum_value(&arc_sums.arcstat_l2_hdr_size);
7454 	as->arcstat_l2_log_blk_writes.value.ui64 =
7455 	    wmsum_value(&arc_sums.arcstat_l2_log_blk_writes);
7456 	as->arcstat_l2_log_blk_asize.value.ui64 =
7457 	    wmsum_value(&arc_sums.arcstat_l2_log_blk_asize);
7458 	as->arcstat_l2_log_blk_count.value.ui64 =
7459 	    wmsum_value(&arc_sums.arcstat_l2_log_blk_count);
7460 	as->arcstat_l2_rebuild_success.value.ui64 =
7461 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_success);
7462 	as->arcstat_l2_rebuild_abort_unsupported.value.ui64 =
7463 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_unsupported);
7464 	as->arcstat_l2_rebuild_abort_io_errors.value.ui64 =
7465 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_io_errors);
7466 	as->arcstat_l2_rebuild_abort_dh_errors.value.ui64 =
7467 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_dh_errors);
7468 	as->arcstat_l2_rebuild_abort_cksum_lb_errors.value.ui64 =
7469 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors);
7470 	as->arcstat_l2_rebuild_abort_lowmem.value.ui64 =
7471 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_abort_lowmem);
7472 	as->arcstat_l2_rebuild_size.value.ui64 =
7473 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_size);
7474 	as->arcstat_l2_rebuild_asize.value.ui64 =
7475 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_asize);
7476 	as->arcstat_l2_rebuild_bufs.value.ui64 =
7477 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_bufs);
7478 	as->arcstat_l2_rebuild_bufs_precached.value.ui64 =
7479 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_bufs_precached);
7480 	as->arcstat_l2_rebuild_log_blks.value.ui64 =
7481 	    wmsum_value(&arc_sums.arcstat_l2_rebuild_log_blks);
7482 	as->arcstat_memory_throttle_count.value.ui64 =
7483 	    wmsum_value(&arc_sums.arcstat_memory_throttle_count);
7484 	as->arcstat_memory_direct_count.value.ui64 =
7485 	    wmsum_value(&arc_sums.arcstat_memory_direct_count);
7486 	as->arcstat_memory_indirect_count.value.ui64 =
7487 	    wmsum_value(&arc_sums.arcstat_memory_indirect_count);
7488 
7489 	as->arcstat_memory_all_bytes.value.ui64 =
7490 	    arc_all_memory();
7491 	as->arcstat_memory_free_bytes.value.ui64 =
7492 	    arc_free_memory();
7493 	as->arcstat_memory_available_bytes.value.i64 =
7494 	    arc_available_memory();
7495 
7496 	as->arcstat_prune.value.ui64 =
7497 	    wmsum_value(&arc_sums.arcstat_prune);
7498 	as->arcstat_meta_used.value.ui64 =
7499 	    aggsum_value(&arc_sums.arcstat_meta_used);
7500 	as->arcstat_async_upgrade_sync.value.ui64 =
7501 	    wmsum_value(&arc_sums.arcstat_async_upgrade_sync);
7502 	as->arcstat_demand_hit_predictive_prefetch.value.ui64 =
7503 	    wmsum_value(&arc_sums.arcstat_demand_hit_predictive_prefetch);
7504 	as->arcstat_demand_hit_prescient_prefetch.value.ui64 =
7505 	    wmsum_value(&arc_sums.arcstat_demand_hit_prescient_prefetch);
7506 	as->arcstat_raw_size.value.ui64 =
7507 	    wmsum_value(&arc_sums.arcstat_raw_size);
7508 	as->arcstat_cached_only_in_progress.value.ui64 =
7509 	    wmsum_value(&arc_sums.arcstat_cached_only_in_progress);
7510 	as->arcstat_abd_chunk_waste_size.value.ui64 =
7511 	    wmsum_value(&arc_sums.arcstat_abd_chunk_waste_size);
7512 
7513 	return (0);
7514 }
7515 
7516 /*
7517  * This function *must* return indices evenly distributed between all
7518  * sublists of the multilist. This is needed due to how the ARC eviction
7519  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
7520  * distributed between all sublists and uses this assumption when
7521  * deciding which sublist to evict from and how much to evict from it.
7522  */
7523 static unsigned int
7524 arc_state_multilist_index_func(multilist_t *ml, void *obj)
7525 {
7526 	arc_buf_hdr_t *hdr = obj;
7527 
7528 	/*
7529 	 * We rely on b_dva to generate evenly distributed index
7530 	 * numbers using buf_hash below. So, as an added precaution,
7531 	 * let's make sure we never add empty buffers to the arc lists.
7532 	 */
7533 	ASSERT(!HDR_EMPTY(hdr));
7534 
7535 	/*
7536 	 * The assumption here, is the hash value for a given
7537 	 * arc_buf_hdr_t will remain constant throughout its lifetime
7538 	 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
7539 	 * Thus, we don't need to store the header's sublist index
7540 	 * on insertion, as this index can be recalculated on removal.
7541 	 *
7542 	 * Also, the low order bits of the hash value are thought to be
7543 	 * distributed evenly. Otherwise, in the case that the multilist
7544 	 * has a power of two number of sublists, each sublists' usage
7545 	 * would not be evenly distributed. In this context full 64bit
7546 	 * division would be a waste of time, so limit it to 32 bits.
7547 	 */
7548 	return ((unsigned int)buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
7549 	    multilist_get_num_sublists(ml));
7550 }
7551 
7552 static unsigned int
7553 arc_state_l2c_multilist_index_func(multilist_t *ml, void *obj)
7554 {
7555 	panic("Header %p insert into arc_l2c_only %p", obj, ml);
7556 }
7557 
7558 #define	WARN_IF_TUNING_IGNORED(tuning, value, do_warn) do {	\
7559 	if ((do_warn) && (tuning) && ((tuning) != (value))) {	\
7560 		cmn_err(CE_WARN,				\
7561 		    "ignoring tunable %s (using %llu instead)",	\
7562 		    (#tuning), (u_longlong_t)(value));	\
7563 	}							\
7564 } while (0)
7565 
7566 /*
7567  * Called during module initialization and periodically thereafter to
7568  * apply reasonable changes to the exposed performance tunings.  Can also be
7569  * called explicitly by param_set_arc_*() functions when ARC tunables are
7570  * updated manually.  Non-zero zfs_* values which differ from the currently set
7571  * values will be applied.
7572  */
7573 void
7574 arc_tuning_update(boolean_t verbose)
7575 {
7576 	uint64_t allmem = arc_all_memory();
7577 	unsigned long limit;
7578 
7579 	/* Valid range: 32M - <arc_c_max> */
7580 	if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
7581 	    (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
7582 	    (zfs_arc_min <= arc_c_max)) {
7583 		arc_c_min = zfs_arc_min;
7584 		arc_c = MAX(arc_c, arc_c_min);
7585 	}
7586 	WARN_IF_TUNING_IGNORED(zfs_arc_min, arc_c_min, verbose);
7587 
7588 	/* Valid range: 64M - <all physical memory> */
7589 	if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
7590 	    (zfs_arc_max >= MIN_ARC_MAX) && (zfs_arc_max < allmem) &&
7591 	    (zfs_arc_max > arc_c_min)) {
7592 		arc_c_max = zfs_arc_max;
7593 		arc_c = MIN(arc_c, arc_c_max);
7594 		arc_p = (arc_c >> 1);
7595 		if (arc_meta_limit > arc_c_max)
7596 			arc_meta_limit = arc_c_max;
7597 		if (arc_dnode_size_limit > arc_meta_limit)
7598 			arc_dnode_size_limit = arc_meta_limit;
7599 	}
7600 	WARN_IF_TUNING_IGNORED(zfs_arc_max, arc_c_max, verbose);
7601 
7602 	/* Valid range: 16M - <arc_c_max> */
7603 	if ((zfs_arc_meta_min) && (zfs_arc_meta_min != arc_meta_min) &&
7604 	    (zfs_arc_meta_min >= 1ULL << SPA_MAXBLOCKSHIFT) &&
7605 	    (zfs_arc_meta_min <= arc_c_max)) {
7606 		arc_meta_min = zfs_arc_meta_min;
7607 		if (arc_meta_limit < arc_meta_min)
7608 			arc_meta_limit = arc_meta_min;
7609 		if (arc_dnode_size_limit < arc_meta_min)
7610 			arc_dnode_size_limit = arc_meta_min;
7611 	}
7612 	WARN_IF_TUNING_IGNORED(zfs_arc_meta_min, arc_meta_min, verbose);
7613 
7614 	/* Valid range: <arc_meta_min> - <arc_c_max> */
7615 	limit = zfs_arc_meta_limit ? zfs_arc_meta_limit :
7616 	    MIN(zfs_arc_meta_limit_percent, 100) * arc_c_max / 100;
7617 	if ((limit != arc_meta_limit) &&
7618 	    (limit >= arc_meta_min) &&
7619 	    (limit <= arc_c_max))
7620 		arc_meta_limit = limit;
7621 	WARN_IF_TUNING_IGNORED(zfs_arc_meta_limit, arc_meta_limit, verbose);
7622 
7623 	/* Valid range: <arc_meta_min> - <arc_meta_limit> */
7624 	limit = zfs_arc_dnode_limit ? zfs_arc_dnode_limit :
7625 	    MIN(zfs_arc_dnode_limit_percent, 100) * arc_meta_limit / 100;
7626 	if ((limit != arc_dnode_size_limit) &&
7627 	    (limit >= arc_meta_min) &&
7628 	    (limit <= arc_meta_limit))
7629 		arc_dnode_size_limit = limit;
7630 	WARN_IF_TUNING_IGNORED(zfs_arc_dnode_limit, arc_dnode_size_limit,
7631 	    verbose);
7632 
7633 	/* Valid range: 1 - N */
7634 	if (zfs_arc_grow_retry)
7635 		arc_grow_retry = zfs_arc_grow_retry;
7636 
7637 	/* Valid range: 1 - N */
7638 	if (zfs_arc_shrink_shift) {
7639 		arc_shrink_shift = zfs_arc_shrink_shift;
7640 		arc_no_grow_shift = MIN(arc_no_grow_shift, arc_shrink_shift -1);
7641 	}
7642 
7643 	/* Valid range: 1 - N */
7644 	if (zfs_arc_p_min_shift)
7645 		arc_p_min_shift = zfs_arc_p_min_shift;
7646 
7647 	/* Valid range: 1 - N ms */
7648 	if (zfs_arc_min_prefetch_ms)
7649 		arc_min_prefetch_ms = zfs_arc_min_prefetch_ms;
7650 
7651 	/* Valid range: 1 - N ms */
7652 	if (zfs_arc_min_prescient_prefetch_ms) {
7653 		arc_min_prescient_prefetch_ms =
7654 		    zfs_arc_min_prescient_prefetch_ms;
7655 	}
7656 
7657 	/* Valid range: 0 - 100 */
7658 	if ((zfs_arc_lotsfree_percent >= 0) &&
7659 	    (zfs_arc_lotsfree_percent <= 100))
7660 		arc_lotsfree_percent = zfs_arc_lotsfree_percent;
7661 	WARN_IF_TUNING_IGNORED(zfs_arc_lotsfree_percent, arc_lotsfree_percent,
7662 	    verbose);
7663 
7664 	/* Valid range: 0 - <all physical memory> */
7665 	if ((zfs_arc_sys_free) && (zfs_arc_sys_free != arc_sys_free))
7666 		arc_sys_free = MIN(MAX(zfs_arc_sys_free, 0), allmem);
7667 	WARN_IF_TUNING_IGNORED(zfs_arc_sys_free, arc_sys_free, verbose);
7668 }
7669 
7670 static void
7671 arc_state_multilist_init(multilist_t *ml,
7672     multilist_sublist_index_func_t *index_func, int *maxcountp)
7673 {
7674 	multilist_create(ml, sizeof (arc_buf_hdr_t),
7675 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node), index_func);
7676 	*maxcountp = MAX(*maxcountp, multilist_get_num_sublists(ml));
7677 }
7678 
7679 static void
7680 arc_state_init(void)
7681 {
7682 	int num_sublists = 0;
7683 
7684 	arc_state_multilist_init(&arc_mru->arcs_list[ARC_BUFC_METADATA],
7685 	    arc_state_multilist_index_func, &num_sublists);
7686 	arc_state_multilist_init(&arc_mru->arcs_list[ARC_BUFC_DATA],
7687 	    arc_state_multilist_index_func, &num_sublists);
7688 	arc_state_multilist_init(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
7689 	    arc_state_multilist_index_func, &num_sublists);
7690 	arc_state_multilist_init(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
7691 	    arc_state_multilist_index_func, &num_sublists);
7692 	arc_state_multilist_init(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
7693 	    arc_state_multilist_index_func, &num_sublists);
7694 	arc_state_multilist_init(&arc_mfu->arcs_list[ARC_BUFC_DATA],
7695 	    arc_state_multilist_index_func, &num_sublists);
7696 	arc_state_multilist_init(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
7697 	    arc_state_multilist_index_func, &num_sublists);
7698 	arc_state_multilist_init(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
7699 	    arc_state_multilist_index_func, &num_sublists);
7700 
7701 	/*
7702 	 * L2 headers should never be on the L2 state list since they don't
7703 	 * have L1 headers allocated.  Special index function asserts that.
7704 	 */
7705 	arc_state_multilist_init(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
7706 	    arc_state_l2c_multilist_index_func, &num_sublists);
7707 	arc_state_multilist_init(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
7708 	    arc_state_l2c_multilist_index_func, &num_sublists);
7709 
7710 	/*
7711 	 * Keep track of the number of markers needed to reclaim buffers from
7712 	 * any ARC state.  The markers will be pre-allocated so as to minimize
7713 	 * the number of memory allocations performed by the eviction thread.
7714 	 */
7715 	arc_state_evict_marker_count = num_sublists;
7716 
7717 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7718 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7719 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7720 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7721 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7722 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7723 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7724 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7725 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7726 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7727 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7728 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7729 
7730 	zfs_refcount_create(&arc_anon->arcs_size);
7731 	zfs_refcount_create(&arc_mru->arcs_size);
7732 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
7733 	zfs_refcount_create(&arc_mfu->arcs_size);
7734 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7735 	zfs_refcount_create(&arc_l2c_only->arcs_size);
7736 
7737 	wmsum_init(&arc_sums.arcstat_hits, 0);
7738 	wmsum_init(&arc_sums.arcstat_misses, 0);
7739 	wmsum_init(&arc_sums.arcstat_demand_data_hits, 0);
7740 	wmsum_init(&arc_sums.arcstat_demand_data_misses, 0);
7741 	wmsum_init(&arc_sums.arcstat_demand_metadata_hits, 0);
7742 	wmsum_init(&arc_sums.arcstat_demand_metadata_misses, 0);
7743 	wmsum_init(&arc_sums.arcstat_prefetch_data_hits, 0);
7744 	wmsum_init(&arc_sums.arcstat_prefetch_data_misses, 0);
7745 	wmsum_init(&arc_sums.arcstat_prefetch_metadata_hits, 0);
7746 	wmsum_init(&arc_sums.arcstat_prefetch_metadata_misses, 0);
7747 	wmsum_init(&arc_sums.arcstat_mru_hits, 0);
7748 	wmsum_init(&arc_sums.arcstat_mru_ghost_hits, 0);
7749 	wmsum_init(&arc_sums.arcstat_mfu_hits, 0);
7750 	wmsum_init(&arc_sums.arcstat_mfu_ghost_hits, 0);
7751 	wmsum_init(&arc_sums.arcstat_deleted, 0);
7752 	wmsum_init(&arc_sums.arcstat_mutex_miss, 0);
7753 	wmsum_init(&arc_sums.arcstat_access_skip, 0);
7754 	wmsum_init(&arc_sums.arcstat_evict_skip, 0);
7755 	wmsum_init(&arc_sums.arcstat_evict_not_enough, 0);
7756 	wmsum_init(&arc_sums.arcstat_evict_l2_cached, 0);
7757 	wmsum_init(&arc_sums.arcstat_evict_l2_eligible, 0);
7758 	wmsum_init(&arc_sums.arcstat_evict_l2_eligible_mfu, 0);
7759 	wmsum_init(&arc_sums.arcstat_evict_l2_eligible_mru, 0);
7760 	wmsum_init(&arc_sums.arcstat_evict_l2_ineligible, 0);
7761 	wmsum_init(&arc_sums.arcstat_evict_l2_skip, 0);
7762 	wmsum_init(&arc_sums.arcstat_hash_collisions, 0);
7763 	wmsum_init(&arc_sums.arcstat_hash_chains, 0);
7764 	aggsum_init(&arc_sums.arcstat_size, 0);
7765 	wmsum_init(&arc_sums.arcstat_compressed_size, 0);
7766 	wmsum_init(&arc_sums.arcstat_uncompressed_size, 0);
7767 	wmsum_init(&arc_sums.arcstat_overhead_size, 0);
7768 	wmsum_init(&arc_sums.arcstat_hdr_size, 0);
7769 	wmsum_init(&arc_sums.arcstat_data_size, 0);
7770 	wmsum_init(&arc_sums.arcstat_metadata_size, 0);
7771 	wmsum_init(&arc_sums.arcstat_dbuf_size, 0);
7772 	aggsum_init(&arc_sums.arcstat_dnode_size, 0);
7773 	wmsum_init(&arc_sums.arcstat_bonus_size, 0);
7774 	wmsum_init(&arc_sums.arcstat_l2_hits, 0);
7775 	wmsum_init(&arc_sums.arcstat_l2_misses, 0);
7776 	wmsum_init(&arc_sums.arcstat_l2_prefetch_asize, 0);
7777 	wmsum_init(&arc_sums.arcstat_l2_mru_asize, 0);
7778 	wmsum_init(&arc_sums.arcstat_l2_mfu_asize, 0);
7779 	wmsum_init(&arc_sums.arcstat_l2_bufc_data_asize, 0);
7780 	wmsum_init(&arc_sums.arcstat_l2_bufc_metadata_asize, 0);
7781 	wmsum_init(&arc_sums.arcstat_l2_feeds, 0);
7782 	wmsum_init(&arc_sums.arcstat_l2_rw_clash, 0);
7783 	wmsum_init(&arc_sums.arcstat_l2_read_bytes, 0);
7784 	wmsum_init(&arc_sums.arcstat_l2_write_bytes, 0);
7785 	wmsum_init(&arc_sums.arcstat_l2_writes_sent, 0);
7786 	wmsum_init(&arc_sums.arcstat_l2_writes_done, 0);
7787 	wmsum_init(&arc_sums.arcstat_l2_writes_error, 0);
7788 	wmsum_init(&arc_sums.arcstat_l2_writes_lock_retry, 0);
7789 	wmsum_init(&arc_sums.arcstat_l2_evict_lock_retry, 0);
7790 	wmsum_init(&arc_sums.arcstat_l2_evict_reading, 0);
7791 	wmsum_init(&arc_sums.arcstat_l2_evict_l1cached, 0);
7792 	wmsum_init(&arc_sums.arcstat_l2_free_on_write, 0);
7793 	wmsum_init(&arc_sums.arcstat_l2_abort_lowmem, 0);
7794 	wmsum_init(&arc_sums.arcstat_l2_cksum_bad, 0);
7795 	wmsum_init(&arc_sums.arcstat_l2_io_error, 0);
7796 	wmsum_init(&arc_sums.arcstat_l2_lsize, 0);
7797 	wmsum_init(&arc_sums.arcstat_l2_psize, 0);
7798 	aggsum_init(&arc_sums.arcstat_l2_hdr_size, 0);
7799 	wmsum_init(&arc_sums.arcstat_l2_log_blk_writes, 0);
7800 	wmsum_init(&arc_sums.arcstat_l2_log_blk_asize, 0);
7801 	wmsum_init(&arc_sums.arcstat_l2_log_blk_count, 0);
7802 	wmsum_init(&arc_sums.arcstat_l2_rebuild_success, 0);
7803 	wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_unsupported, 0);
7804 	wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_io_errors, 0);
7805 	wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_dh_errors, 0);
7806 	wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors, 0);
7807 	wmsum_init(&arc_sums.arcstat_l2_rebuild_abort_lowmem, 0);
7808 	wmsum_init(&arc_sums.arcstat_l2_rebuild_size, 0);
7809 	wmsum_init(&arc_sums.arcstat_l2_rebuild_asize, 0);
7810 	wmsum_init(&arc_sums.arcstat_l2_rebuild_bufs, 0);
7811 	wmsum_init(&arc_sums.arcstat_l2_rebuild_bufs_precached, 0);
7812 	wmsum_init(&arc_sums.arcstat_l2_rebuild_log_blks, 0);
7813 	wmsum_init(&arc_sums.arcstat_memory_throttle_count, 0);
7814 	wmsum_init(&arc_sums.arcstat_memory_direct_count, 0);
7815 	wmsum_init(&arc_sums.arcstat_memory_indirect_count, 0);
7816 	wmsum_init(&arc_sums.arcstat_prune, 0);
7817 	aggsum_init(&arc_sums.arcstat_meta_used, 0);
7818 	wmsum_init(&arc_sums.arcstat_async_upgrade_sync, 0);
7819 	wmsum_init(&arc_sums.arcstat_demand_hit_predictive_prefetch, 0);
7820 	wmsum_init(&arc_sums.arcstat_demand_hit_prescient_prefetch, 0);
7821 	wmsum_init(&arc_sums.arcstat_raw_size, 0);
7822 	wmsum_init(&arc_sums.arcstat_cached_only_in_progress, 0);
7823 	wmsum_init(&arc_sums.arcstat_abd_chunk_waste_size, 0);
7824 
7825 	arc_anon->arcs_state = ARC_STATE_ANON;
7826 	arc_mru->arcs_state = ARC_STATE_MRU;
7827 	arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7828 	arc_mfu->arcs_state = ARC_STATE_MFU;
7829 	arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7830 	arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
7831 }
7832 
7833 static void
7834 arc_state_fini(void)
7835 {
7836 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7837 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7838 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7839 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7840 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7841 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7842 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7843 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7844 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7845 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7846 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7847 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7848 
7849 	zfs_refcount_destroy(&arc_anon->arcs_size);
7850 	zfs_refcount_destroy(&arc_mru->arcs_size);
7851 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7852 	zfs_refcount_destroy(&arc_mfu->arcs_size);
7853 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7854 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7855 
7856 	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
7857 	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7858 	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7859 	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7860 	multilist_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
7861 	multilist_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7862 	multilist_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
7863 	multilist_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7864 	multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7865 	multilist_destroy(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
7866 
7867 	wmsum_fini(&arc_sums.arcstat_hits);
7868 	wmsum_fini(&arc_sums.arcstat_misses);
7869 	wmsum_fini(&arc_sums.arcstat_demand_data_hits);
7870 	wmsum_fini(&arc_sums.arcstat_demand_data_misses);
7871 	wmsum_fini(&arc_sums.arcstat_demand_metadata_hits);
7872 	wmsum_fini(&arc_sums.arcstat_demand_metadata_misses);
7873 	wmsum_fini(&arc_sums.arcstat_prefetch_data_hits);
7874 	wmsum_fini(&arc_sums.arcstat_prefetch_data_misses);
7875 	wmsum_fini(&arc_sums.arcstat_prefetch_metadata_hits);
7876 	wmsum_fini(&arc_sums.arcstat_prefetch_metadata_misses);
7877 	wmsum_fini(&arc_sums.arcstat_mru_hits);
7878 	wmsum_fini(&arc_sums.arcstat_mru_ghost_hits);
7879 	wmsum_fini(&arc_sums.arcstat_mfu_hits);
7880 	wmsum_fini(&arc_sums.arcstat_mfu_ghost_hits);
7881 	wmsum_fini(&arc_sums.arcstat_deleted);
7882 	wmsum_fini(&arc_sums.arcstat_mutex_miss);
7883 	wmsum_fini(&arc_sums.arcstat_access_skip);
7884 	wmsum_fini(&arc_sums.arcstat_evict_skip);
7885 	wmsum_fini(&arc_sums.arcstat_evict_not_enough);
7886 	wmsum_fini(&arc_sums.arcstat_evict_l2_cached);
7887 	wmsum_fini(&arc_sums.arcstat_evict_l2_eligible);
7888 	wmsum_fini(&arc_sums.arcstat_evict_l2_eligible_mfu);
7889 	wmsum_fini(&arc_sums.arcstat_evict_l2_eligible_mru);
7890 	wmsum_fini(&arc_sums.arcstat_evict_l2_ineligible);
7891 	wmsum_fini(&arc_sums.arcstat_evict_l2_skip);
7892 	wmsum_fini(&arc_sums.arcstat_hash_collisions);
7893 	wmsum_fini(&arc_sums.arcstat_hash_chains);
7894 	aggsum_fini(&arc_sums.arcstat_size);
7895 	wmsum_fini(&arc_sums.arcstat_compressed_size);
7896 	wmsum_fini(&arc_sums.arcstat_uncompressed_size);
7897 	wmsum_fini(&arc_sums.arcstat_overhead_size);
7898 	wmsum_fini(&arc_sums.arcstat_hdr_size);
7899 	wmsum_fini(&arc_sums.arcstat_data_size);
7900 	wmsum_fini(&arc_sums.arcstat_metadata_size);
7901 	wmsum_fini(&arc_sums.arcstat_dbuf_size);
7902 	aggsum_fini(&arc_sums.arcstat_dnode_size);
7903 	wmsum_fini(&arc_sums.arcstat_bonus_size);
7904 	wmsum_fini(&arc_sums.arcstat_l2_hits);
7905 	wmsum_fini(&arc_sums.arcstat_l2_misses);
7906 	wmsum_fini(&arc_sums.arcstat_l2_prefetch_asize);
7907 	wmsum_fini(&arc_sums.arcstat_l2_mru_asize);
7908 	wmsum_fini(&arc_sums.arcstat_l2_mfu_asize);
7909 	wmsum_fini(&arc_sums.arcstat_l2_bufc_data_asize);
7910 	wmsum_fini(&arc_sums.arcstat_l2_bufc_metadata_asize);
7911 	wmsum_fini(&arc_sums.arcstat_l2_feeds);
7912 	wmsum_fini(&arc_sums.arcstat_l2_rw_clash);
7913 	wmsum_fini(&arc_sums.arcstat_l2_read_bytes);
7914 	wmsum_fini(&arc_sums.arcstat_l2_write_bytes);
7915 	wmsum_fini(&arc_sums.arcstat_l2_writes_sent);
7916 	wmsum_fini(&arc_sums.arcstat_l2_writes_done);
7917 	wmsum_fini(&arc_sums.arcstat_l2_writes_error);
7918 	wmsum_fini(&arc_sums.arcstat_l2_writes_lock_retry);
7919 	wmsum_fini(&arc_sums.arcstat_l2_evict_lock_retry);
7920 	wmsum_fini(&arc_sums.arcstat_l2_evict_reading);
7921 	wmsum_fini(&arc_sums.arcstat_l2_evict_l1cached);
7922 	wmsum_fini(&arc_sums.arcstat_l2_free_on_write);
7923 	wmsum_fini(&arc_sums.arcstat_l2_abort_lowmem);
7924 	wmsum_fini(&arc_sums.arcstat_l2_cksum_bad);
7925 	wmsum_fini(&arc_sums.arcstat_l2_io_error);
7926 	wmsum_fini(&arc_sums.arcstat_l2_lsize);
7927 	wmsum_fini(&arc_sums.arcstat_l2_psize);
7928 	aggsum_fini(&arc_sums.arcstat_l2_hdr_size);
7929 	wmsum_fini(&arc_sums.arcstat_l2_log_blk_writes);
7930 	wmsum_fini(&arc_sums.arcstat_l2_log_blk_asize);
7931 	wmsum_fini(&arc_sums.arcstat_l2_log_blk_count);
7932 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_success);
7933 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_unsupported);
7934 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_io_errors);
7935 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_dh_errors);
7936 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_cksum_lb_errors);
7937 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_abort_lowmem);
7938 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_size);
7939 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_asize);
7940 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_bufs);
7941 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_bufs_precached);
7942 	wmsum_fini(&arc_sums.arcstat_l2_rebuild_log_blks);
7943 	wmsum_fini(&arc_sums.arcstat_memory_throttle_count);
7944 	wmsum_fini(&arc_sums.arcstat_memory_direct_count);
7945 	wmsum_fini(&arc_sums.arcstat_memory_indirect_count);
7946 	wmsum_fini(&arc_sums.arcstat_prune);
7947 	aggsum_fini(&arc_sums.arcstat_meta_used);
7948 	wmsum_fini(&arc_sums.arcstat_async_upgrade_sync);
7949 	wmsum_fini(&arc_sums.arcstat_demand_hit_predictive_prefetch);
7950 	wmsum_fini(&arc_sums.arcstat_demand_hit_prescient_prefetch);
7951 	wmsum_fini(&arc_sums.arcstat_raw_size);
7952 	wmsum_fini(&arc_sums.arcstat_cached_only_in_progress);
7953 	wmsum_fini(&arc_sums.arcstat_abd_chunk_waste_size);
7954 }
7955 
7956 uint64_t
7957 arc_target_bytes(void)
7958 {
7959 	return (arc_c);
7960 }
7961 
7962 void
7963 arc_set_limits(uint64_t allmem)
7964 {
7965 	/* Set min cache to 1/32 of all memory, or 32MB, whichever is more. */
7966 	arc_c_min = MAX(allmem / 32, 2ULL << SPA_MAXBLOCKSHIFT);
7967 
7968 	/* How to set default max varies by platform. */
7969 	arc_c_max = arc_default_max(arc_c_min, allmem);
7970 }
7971 void
7972 arc_init(void)
7973 {
7974 	uint64_t percent, allmem = arc_all_memory();
7975 	mutex_init(&arc_evict_lock, NULL, MUTEX_DEFAULT, NULL);
7976 	list_create(&arc_evict_waiters, sizeof (arc_evict_waiter_t),
7977 	    offsetof(arc_evict_waiter_t, aew_node));
7978 
7979 	arc_min_prefetch_ms = 1000;
7980 	arc_min_prescient_prefetch_ms = 6000;
7981 
7982 #if defined(_KERNEL)
7983 	arc_lowmem_init();
7984 #endif
7985 
7986 	arc_set_limits(allmem);
7987 
7988 #ifdef _KERNEL
7989 	/*
7990 	 * If zfs_arc_max is non-zero at init, meaning it was set in the kernel
7991 	 * environment before the module was loaded, don't block setting the
7992 	 * maximum because it is less than arc_c_min, instead, reset arc_c_min
7993 	 * to a lower value.
7994 	 * zfs_arc_min will be handled by arc_tuning_update().
7995 	 */
7996 	if (zfs_arc_max != 0 && zfs_arc_max >= MIN_ARC_MAX &&
7997 	    zfs_arc_max < allmem) {
7998 		arc_c_max = zfs_arc_max;
7999 		if (arc_c_min >= arc_c_max) {
8000 			arc_c_min = MAX(zfs_arc_max / 2,
8001 			    2ULL << SPA_MAXBLOCKSHIFT);
8002 		}
8003 	}
8004 #else
8005 	/*
8006 	 * In userland, there's only the memory pressure that we artificially
8007 	 * create (see arc_available_memory()).  Don't let arc_c get too
8008 	 * small, because it can cause transactions to be larger than
8009 	 * arc_c, causing arc_tempreserve_space() to fail.
8010 	 */
8011 	arc_c_min = MAX(arc_c_max / 2, 2ULL << SPA_MAXBLOCKSHIFT);
8012 #endif
8013 
8014 	arc_c = arc_c_min;
8015 	arc_p = (arc_c >> 1);
8016 
8017 	/* Set min to 1/2 of arc_c_min */
8018 	arc_meta_min = 1ULL << SPA_MAXBLOCKSHIFT;
8019 	/*
8020 	 * Set arc_meta_limit to a percent of arc_c_max with a floor of
8021 	 * arc_meta_min, and a ceiling of arc_c_max.
8022 	 */
8023 	percent = MIN(zfs_arc_meta_limit_percent, 100);
8024 	arc_meta_limit = MAX(arc_meta_min, (percent * arc_c_max) / 100);
8025 	percent = MIN(zfs_arc_dnode_limit_percent, 100);
8026 	arc_dnode_size_limit = (percent * arc_meta_limit) / 100;
8027 
8028 	/* Apply user specified tunings */
8029 	arc_tuning_update(B_TRUE);
8030 
8031 	/* if kmem_flags are set, lets try to use less memory */
8032 	if (kmem_debugging())
8033 		arc_c = arc_c / 2;
8034 	if (arc_c < arc_c_min)
8035 		arc_c = arc_c_min;
8036 
8037 	arc_register_hotplug();
8038 
8039 	arc_state_init();
8040 
8041 	buf_init();
8042 
8043 	list_create(&arc_prune_list, sizeof (arc_prune_t),
8044 	    offsetof(arc_prune_t, p_node));
8045 	mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
8046 
8047 	arc_prune_taskq = taskq_create("arc_prune", zfs_arc_prune_task_threads,
8048 	    defclsyspri, 100, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
8049 
8050 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
8051 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
8052 
8053 	if (arc_ksp != NULL) {
8054 		arc_ksp->ks_data = &arc_stats;
8055 		arc_ksp->ks_update = arc_kstat_update;
8056 		kstat_install(arc_ksp);
8057 	}
8058 
8059 	arc_state_evict_markers =
8060 	    arc_state_alloc_markers(arc_state_evict_marker_count);
8061 	arc_evict_zthr = zthr_create("arc_evict",
8062 	    arc_evict_cb_check, arc_evict_cb, NULL, defclsyspri);
8063 	arc_reap_zthr = zthr_create_timer("arc_reap",
8064 	    arc_reap_cb_check, arc_reap_cb, NULL, SEC2NSEC(1), minclsyspri);
8065 
8066 	arc_warm = B_FALSE;
8067 
8068 	/*
8069 	 * Calculate maximum amount of dirty data per pool.
8070 	 *
8071 	 * If it has been set by a module parameter, take that.
8072 	 * Otherwise, use a percentage of physical memory defined by
8073 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
8074 	 * zfs_dirty_data_max_max (default 4G or 25% of physical memory).
8075 	 */
8076 #ifdef __LP64__
8077 	if (zfs_dirty_data_max_max == 0)
8078 		zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
8079 		    allmem * zfs_dirty_data_max_max_percent / 100);
8080 #else
8081 	if (zfs_dirty_data_max_max == 0)
8082 		zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
8083 		    allmem * zfs_dirty_data_max_max_percent / 100);
8084 #endif
8085 
8086 	if (zfs_dirty_data_max == 0) {
8087 		zfs_dirty_data_max = allmem *
8088 		    zfs_dirty_data_max_percent / 100;
8089 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
8090 		    zfs_dirty_data_max_max);
8091 	}
8092 
8093 	if (zfs_wrlog_data_max == 0) {
8094 
8095 		/*
8096 		 * dp_wrlog_total is reduced for each txg at the end of
8097 		 * spa_sync(). However, dp_dirty_total is reduced every time
8098 		 * a block is written out. Thus under normal operation,
8099 		 * dp_wrlog_total could grow 2 times as big as
8100 		 * zfs_dirty_data_max.
8101 		 */
8102 		zfs_wrlog_data_max = zfs_dirty_data_max * 2;
8103 	}
8104 }
8105 
8106 void
8107 arc_fini(void)
8108 {
8109 	arc_prune_t *p;
8110 
8111 #ifdef _KERNEL
8112 	arc_lowmem_fini();
8113 #endif /* _KERNEL */
8114 
8115 	/* Use B_TRUE to ensure *all* buffers are evicted */
8116 	arc_flush(NULL, B_TRUE);
8117 
8118 	if (arc_ksp != NULL) {
8119 		kstat_delete(arc_ksp);
8120 		arc_ksp = NULL;
8121 	}
8122 
8123 	taskq_wait(arc_prune_taskq);
8124 	taskq_destroy(arc_prune_taskq);
8125 
8126 	mutex_enter(&arc_prune_mtx);
8127 	while ((p = list_head(&arc_prune_list)) != NULL) {
8128 		list_remove(&arc_prune_list, p);
8129 		zfs_refcount_remove(&p->p_refcnt, &arc_prune_list);
8130 		zfs_refcount_destroy(&p->p_refcnt);
8131 		kmem_free(p, sizeof (*p));
8132 	}
8133 	mutex_exit(&arc_prune_mtx);
8134 
8135 	list_destroy(&arc_prune_list);
8136 	mutex_destroy(&arc_prune_mtx);
8137 
8138 	(void) zthr_cancel(arc_evict_zthr);
8139 	(void) zthr_cancel(arc_reap_zthr);
8140 	arc_state_free_markers(arc_state_evict_markers,
8141 	    arc_state_evict_marker_count);
8142 
8143 	mutex_destroy(&arc_evict_lock);
8144 	list_destroy(&arc_evict_waiters);
8145 
8146 	/*
8147 	 * Free any buffers that were tagged for destruction.  This needs
8148 	 * to occur before arc_state_fini() runs and destroys the aggsum
8149 	 * values which are updated when freeing scatter ABDs.
8150 	 */
8151 	l2arc_do_free_on_write();
8152 
8153 	/*
8154 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
8155 	 * trigger the release of kmem magazines, which can callback to
8156 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
8157 	 */
8158 	buf_fini();
8159 	arc_state_fini();
8160 
8161 	arc_unregister_hotplug();
8162 
8163 	/*
8164 	 * We destroy the zthrs after all the ARC state has been
8165 	 * torn down to avoid the case of them receiving any
8166 	 * wakeup() signals after they are destroyed.
8167 	 */
8168 	zthr_destroy(arc_evict_zthr);
8169 	zthr_destroy(arc_reap_zthr);
8170 
8171 	ASSERT0(arc_loaned_bytes);
8172 }
8173 
8174 /*
8175  * Level 2 ARC
8176  *
8177  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
8178  * It uses dedicated storage devices to hold cached data, which are populated
8179  * using large infrequent writes.  The main role of this cache is to boost
8180  * the performance of random read workloads.  The intended L2ARC devices
8181  * include short-stroked disks, solid state disks, and other media with
8182  * substantially faster read latency than disk.
8183  *
8184  *                 +-----------------------+
8185  *                 |         ARC           |
8186  *                 +-----------------------+
8187  *                    |         ^     ^
8188  *                    |         |     |
8189  *      l2arc_feed_thread()    arc_read()
8190  *                    |         |     |
8191  *                    |  l2arc read   |
8192  *                    V         |     |
8193  *               +---------------+    |
8194  *               |     L2ARC     |    |
8195  *               +---------------+    |
8196  *                   |    ^           |
8197  *          l2arc_write() |           |
8198  *                   |    |           |
8199  *                   V    |           |
8200  *                 +-------+      +-------+
8201  *                 | vdev  |      | vdev  |
8202  *                 | cache |      | cache |
8203  *                 +-------+      +-------+
8204  *                 +=========+     .-----.
8205  *                 :  L2ARC  :    |-_____-|
8206  *                 : devices :    | Disks |
8207  *                 +=========+    `-_____-'
8208  *
8209  * Read requests are satisfied from the following sources, in order:
8210  *
8211  *	1) ARC
8212  *	2) vdev cache of L2ARC devices
8213  *	3) L2ARC devices
8214  *	4) vdev cache of disks
8215  *	5) disks
8216  *
8217  * Some L2ARC device types exhibit extremely slow write performance.
8218  * To accommodate for this there are some significant differences between
8219  * the L2ARC and traditional cache design:
8220  *
8221  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
8222  * the ARC behave as usual, freeing buffers and placing headers on ghost
8223  * lists.  The ARC does not send buffers to the L2ARC during eviction as
8224  * this would add inflated write latencies for all ARC memory pressure.
8225  *
8226  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
8227  * It does this by periodically scanning buffers from the eviction-end of
8228  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
8229  * not already there. It scans until a headroom of buffers is satisfied,
8230  * which itself is a buffer for ARC eviction. If a compressible buffer is
8231  * found during scanning and selected for writing to an L2ARC device, we
8232  * temporarily boost scanning headroom during the next scan cycle to make
8233  * sure we adapt to compression effects (which might significantly reduce
8234  * the data volume we write to L2ARC). The thread that does this is
8235  * l2arc_feed_thread(), illustrated below; example sizes are included to
8236  * provide a better sense of ratio than this diagram:
8237  *
8238  *	       head -->                        tail
8239  *	        +---------------------+----------+
8240  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
8241  *	        +---------------------+----------+   |   o L2ARC eligible
8242  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
8243  *	        +---------------------+----------+   |
8244  *	             15.9 Gbytes      ^ 32 Mbytes    |
8245  *	                           headroom          |
8246  *	                                      l2arc_feed_thread()
8247  *	                                             |
8248  *	                 l2arc write hand <--[oooo]--'
8249  *	                         |           8 Mbyte
8250  *	                         |          write max
8251  *	                         V
8252  *		  +==============================+
8253  *	L2ARC dev |####|#|###|###|    |####| ... |
8254  *	          +==============================+
8255  *	                     32 Gbytes
8256  *
8257  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
8258  * evicted, then the L2ARC has cached a buffer much sooner than it probably
8259  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
8260  * safe to say that this is an uncommon case, since buffers at the end of
8261  * the ARC lists have moved there due to inactivity.
8262  *
8263  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
8264  * then the L2ARC simply misses copying some buffers.  This serves as a
8265  * pressure valve to prevent heavy read workloads from both stalling the ARC
8266  * with waits and clogging the L2ARC with writes.  This also helps prevent
8267  * the potential for the L2ARC to churn if it attempts to cache content too
8268  * quickly, such as during backups of the entire pool.
8269  *
8270  * 5. After system boot and before the ARC has filled main memory, there are
8271  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
8272  * lists can remain mostly static.  Instead of searching from tail of these
8273  * lists as pictured, the l2arc_feed_thread() will search from the list heads
8274  * for eligible buffers, greatly increasing its chance of finding them.
8275  *
8276  * The L2ARC device write speed is also boosted during this time so that
8277  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
8278  * there are no L2ARC reads, and no fear of degrading read performance
8279  * through increased writes.
8280  *
8281  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
8282  * the vdev queue can aggregate them into larger and fewer writes.  Each
8283  * device is written to in a rotor fashion, sweeping writes through
8284  * available space then repeating.
8285  *
8286  * 7. The L2ARC does not store dirty content.  It never needs to flush
8287  * write buffers back to disk based storage.
8288  *
8289  * 8. If an ARC buffer is written (and dirtied) which also exists in the
8290  * L2ARC, the now stale L2ARC buffer is immediately dropped.
8291  *
8292  * The performance of the L2ARC can be tweaked by a number of tunables, which
8293  * may be necessary for different workloads:
8294  *
8295  *	l2arc_write_max		max write bytes per interval
8296  *	l2arc_write_boost	extra write bytes during device warmup
8297  *	l2arc_noprefetch	skip caching prefetched buffers
8298  *	l2arc_headroom		number of max device writes to precache
8299  *	l2arc_headroom_boost	when we find compressed buffers during ARC
8300  *				scanning, we multiply headroom by this
8301  *				percentage factor for the next scan cycle,
8302  *				since more compressed buffers are likely to
8303  *				be present
8304  *	l2arc_feed_secs		seconds between L2ARC writing
8305  *
8306  * Tunables may be removed or added as future performance improvements are
8307  * integrated, and also may become zpool properties.
8308  *
8309  * There are three key functions that control how the L2ARC warms up:
8310  *
8311  *	l2arc_write_eligible()	check if a buffer is eligible to cache
8312  *	l2arc_write_size()	calculate how much to write
8313  *	l2arc_write_interval()	calculate sleep delay between writes
8314  *
8315  * These three functions determine what to write, how much, and how quickly
8316  * to send writes.
8317  *
8318  * L2ARC persistence:
8319  *
8320  * When writing buffers to L2ARC, we periodically add some metadata to
8321  * make sure we can pick them up after reboot, thus dramatically reducing
8322  * the impact that any downtime has on the performance of storage systems
8323  * with large caches.
8324  *
8325  * The implementation works fairly simply by integrating the following two
8326  * modifications:
8327  *
8328  * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
8329  *    which is an additional piece of metadata which describes what's been
8330  *    written. This allows us to rebuild the arc_buf_hdr_t structures of the
8331  *    main ARC buffers. There are 2 linked-lists of log blocks headed by
8332  *    dh_start_lbps[2]. We alternate which chain we append to, so they are
8333  *    time-wise and offset-wise interleaved, but that is an optimization rather
8334  *    than for correctness. The log block also includes a pointer to the
8335  *    previous block in its chain.
8336  *
8337  * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
8338  *    for our header bookkeeping purposes. This contains a device header,
8339  *    which contains our top-level reference structures. We update it each
8340  *    time we write a new log block, so that we're able to locate it in the
8341  *    L2ARC device. If this write results in an inconsistent device header
8342  *    (e.g. due to power failure), we detect this by verifying the header's
8343  *    checksum and simply fail to reconstruct the L2ARC after reboot.
8344  *
8345  * Implementation diagram:
8346  *
8347  * +=== L2ARC device (not to scale) ======================================+
8348  * |       ___two newest log block pointers__.__________                  |
8349  * |      /                                   \dh_start_lbps[1]           |
8350  * |	 /				       \         \dh_start_lbps[0]|
8351  * |.___/__.                                    V         V               |
8352  * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
8353  * ||   hdr|      ^         /^       /^        /         /                |
8354  * |+------+  ...--\-------/  \-----/--\------/         /                 |
8355  * |                \--------------/    \--------------/                  |
8356  * +======================================================================+
8357  *
8358  * As can be seen on the diagram, rather than using a simple linked list,
8359  * we use a pair of linked lists with alternating elements. This is a
8360  * performance enhancement due to the fact that we only find out the
8361  * address of the next log block access once the current block has been
8362  * completely read in. Obviously, this hurts performance, because we'd be
8363  * keeping the device's I/O queue at only a 1 operation deep, thus
8364  * incurring a large amount of I/O round-trip latency. Having two lists
8365  * allows us to fetch two log blocks ahead of where we are currently
8366  * rebuilding L2ARC buffers.
8367  *
8368  * On-device data structures:
8369  *
8370  * L2ARC device header:	l2arc_dev_hdr_phys_t
8371  * L2ARC log block:	l2arc_log_blk_phys_t
8372  *
8373  * L2ARC reconstruction:
8374  *
8375  * When writing data, we simply write in the standard rotary fashion,
8376  * evicting buffers as we go and simply writing new data over them (writing
8377  * a new log block every now and then). This obviously means that once we
8378  * loop around the end of the device, we will start cutting into an already
8379  * committed log block (and its referenced data buffers), like so:
8380  *
8381  *    current write head__       __old tail
8382  *                        \     /
8383  *                        V    V
8384  * <--|bufs |lb |bufs |lb |    |bufs |lb |bufs |lb |-->
8385  *                         ^    ^^^^^^^^^___________________________________
8386  *                         |                                                \
8387  *                   <<nextwrite>> may overwrite this blk and/or its bufs --'
8388  *
8389  * When importing the pool, we detect this situation and use it to stop
8390  * our scanning process (see l2arc_rebuild).
8391  *
8392  * There is one significant caveat to consider when rebuilding ARC contents
8393  * from an L2ARC device: what about invalidated buffers? Given the above
8394  * construction, we cannot update blocks which we've already written to amend
8395  * them to remove buffers which were invalidated. Thus, during reconstruction,
8396  * we might be populating the cache with buffers for data that's not on the
8397  * main pool anymore, or may have been overwritten!
8398  *
8399  * As it turns out, this isn't a problem. Every arc_read request includes
8400  * both the DVA and, crucially, the birth TXG of the BP the caller is
8401  * looking for. So even if the cache were populated by completely rotten
8402  * blocks for data that had been long deleted and/or overwritten, we'll
8403  * never actually return bad data from the cache, since the DVA with the
8404  * birth TXG uniquely identify a block in space and time - once created,
8405  * a block is immutable on disk. The worst thing we have done is wasted
8406  * some time and memory at l2arc rebuild to reconstruct outdated ARC
8407  * entries that will get dropped from the l2arc as it is being updated
8408  * with new blocks.
8409  *
8410  * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
8411  * hand are not restored. This is done by saving the offset (in bytes)
8412  * l2arc_evict() has evicted to in the L2ARC device header and taking it
8413  * into account when restoring buffers.
8414  */
8415 
8416 static boolean_t
8417 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
8418 {
8419 	/*
8420 	 * A buffer is *not* eligible for the L2ARC if it:
8421 	 * 1. belongs to a different spa.
8422 	 * 2. is already cached on the L2ARC.
8423 	 * 3. has an I/O in progress (it may be an incomplete read).
8424 	 * 4. is flagged not eligible (zfs property).
8425 	 */
8426 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
8427 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
8428 		return (B_FALSE);
8429 
8430 	return (B_TRUE);
8431 }
8432 
8433 static uint64_t
8434 l2arc_write_size(l2arc_dev_t *dev)
8435 {
8436 	uint64_t size, dev_size, tsize;
8437 
8438 	/*
8439 	 * Make sure our globals have meaningful values in case the user
8440 	 * altered them.
8441 	 */
8442 	size = l2arc_write_max;
8443 	if (size == 0) {
8444 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
8445 		    "be greater than zero, resetting it to the default (%d)",
8446 		    L2ARC_WRITE_SIZE);
8447 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
8448 	}
8449 
8450 	if (arc_warm == B_FALSE)
8451 		size += l2arc_write_boost;
8452 
8453 	/*
8454 	 * Make sure the write size does not exceed the size of the cache
8455 	 * device. This is important in l2arc_evict(), otherwise infinite
8456 	 * iteration can occur.
8457 	 */
8458 	dev_size = dev->l2ad_end - dev->l2ad_start;
8459 	tsize = size + l2arc_log_blk_overhead(size, dev);
8460 	if (dev->l2ad_vdev->vdev_has_trim && l2arc_trim_ahead > 0)
8461 		tsize += MAX(64 * 1024 * 1024,
8462 		    (tsize * l2arc_trim_ahead) / 100);
8463 
8464 	if (tsize >= dev_size) {
8465 		cmn_err(CE_NOTE, "l2arc_write_max or l2arc_write_boost "
8466 		    "plus the overhead of log blocks (persistent L2ARC, "
8467 		    "%llu bytes) exceeds the size of the cache device "
8468 		    "(guid %llu), resetting them to the default (%d)",
8469 		    (u_longlong_t)l2arc_log_blk_overhead(size, dev),
8470 		    (u_longlong_t)dev->l2ad_vdev->vdev_guid, L2ARC_WRITE_SIZE);
8471 		size = l2arc_write_max = l2arc_write_boost = L2ARC_WRITE_SIZE;
8472 
8473 		if (arc_warm == B_FALSE)
8474 			size += l2arc_write_boost;
8475 	}
8476 
8477 	return (size);
8478 
8479 }
8480 
8481 static clock_t
8482 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
8483 {
8484 	clock_t interval, next, now;
8485 
8486 	/*
8487 	 * If the ARC lists are busy, increase our write rate; if the
8488 	 * lists are stale, idle back.  This is achieved by checking
8489 	 * how much we previously wrote - if it was more than half of
8490 	 * what we wanted, schedule the next write much sooner.
8491 	 */
8492 	if (l2arc_feed_again && wrote > (wanted / 2))
8493 		interval = (hz * l2arc_feed_min_ms) / 1000;
8494 	else
8495 		interval = hz * l2arc_feed_secs;
8496 
8497 	now = ddi_get_lbolt();
8498 	next = MAX(now, MIN(now + interval, began + interval));
8499 
8500 	return (next);
8501 }
8502 
8503 /*
8504  * Cycle through L2ARC devices.  This is how L2ARC load balances.
8505  * If a device is returned, this also returns holding the spa config lock.
8506  */
8507 static l2arc_dev_t *
8508 l2arc_dev_get_next(void)
8509 {
8510 	l2arc_dev_t *first, *next = NULL;
8511 
8512 	/*
8513 	 * Lock out the removal of spas (spa_namespace_lock), then removal
8514 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
8515 	 * both locks will be dropped and a spa config lock held instead.
8516 	 */
8517 	mutex_enter(&spa_namespace_lock);
8518 	mutex_enter(&l2arc_dev_mtx);
8519 
8520 	/* if there are no vdevs, there is nothing to do */
8521 	if (l2arc_ndev == 0)
8522 		goto out;
8523 
8524 	first = NULL;
8525 	next = l2arc_dev_last;
8526 	do {
8527 		/* loop around the list looking for a non-faulted vdev */
8528 		if (next == NULL) {
8529 			next = list_head(l2arc_dev_list);
8530 		} else {
8531 			next = list_next(l2arc_dev_list, next);
8532 			if (next == NULL)
8533 				next = list_head(l2arc_dev_list);
8534 		}
8535 
8536 		/* if we have come back to the start, bail out */
8537 		if (first == NULL)
8538 			first = next;
8539 		else if (next == first)
8540 			break;
8541 
8542 	} while (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
8543 	    next->l2ad_trim_all);
8544 
8545 	/* if we were unable to find any usable vdevs, return NULL */
8546 	if (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
8547 	    next->l2ad_trim_all)
8548 		next = NULL;
8549 
8550 	l2arc_dev_last = next;
8551 
8552 out:
8553 	mutex_exit(&l2arc_dev_mtx);
8554 
8555 	/*
8556 	 * Grab the config lock to prevent the 'next' device from being
8557 	 * removed while we are writing to it.
8558 	 */
8559 	if (next != NULL)
8560 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
8561 	mutex_exit(&spa_namespace_lock);
8562 
8563 	return (next);
8564 }
8565 
8566 /*
8567  * Free buffers that were tagged for destruction.
8568  */
8569 static void
8570 l2arc_do_free_on_write(void)
8571 {
8572 	list_t *buflist;
8573 	l2arc_data_free_t *df, *df_prev;
8574 
8575 	mutex_enter(&l2arc_free_on_write_mtx);
8576 	buflist = l2arc_free_on_write;
8577 
8578 	for (df = list_tail(buflist); df; df = df_prev) {
8579 		df_prev = list_prev(buflist, df);
8580 		ASSERT3P(df->l2df_abd, !=, NULL);
8581 		abd_free(df->l2df_abd);
8582 		list_remove(buflist, df);
8583 		kmem_free(df, sizeof (l2arc_data_free_t));
8584 	}
8585 
8586 	mutex_exit(&l2arc_free_on_write_mtx);
8587 }
8588 
8589 /*
8590  * A write to a cache device has completed.  Update all headers to allow
8591  * reads from these buffers to begin.
8592  */
8593 static void
8594 l2arc_write_done(zio_t *zio)
8595 {
8596 	l2arc_write_callback_t	*cb;
8597 	l2arc_lb_abd_buf_t	*abd_buf;
8598 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
8599 	l2arc_dev_t		*dev;
8600 	l2arc_dev_hdr_phys_t	*l2dhdr;
8601 	list_t			*buflist;
8602 	arc_buf_hdr_t		*head, *hdr, *hdr_prev;
8603 	kmutex_t		*hash_lock;
8604 	int64_t			bytes_dropped = 0;
8605 
8606 	cb = zio->io_private;
8607 	ASSERT3P(cb, !=, NULL);
8608 	dev = cb->l2wcb_dev;
8609 	l2dhdr = dev->l2ad_dev_hdr;
8610 	ASSERT3P(dev, !=, NULL);
8611 	head = cb->l2wcb_head;
8612 	ASSERT3P(head, !=, NULL);
8613 	buflist = &dev->l2ad_buflist;
8614 	ASSERT3P(buflist, !=, NULL);
8615 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
8616 	    l2arc_write_callback_t *, cb);
8617 
8618 	/*
8619 	 * All writes completed, or an error was hit.
8620 	 */
8621 top:
8622 	mutex_enter(&dev->l2ad_mtx);
8623 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
8624 		hdr_prev = list_prev(buflist, hdr);
8625 
8626 		hash_lock = HDR_LOCK(hdr);
8627 
8628 		/*
8629 		 * We cannot use mutex_enter or else we can deadlock
8630 		 * with l2arc_write_buffers (due to swapping the order
8631 		 * the hash lock and l2ad_mtx are taken).
8632 		 */
8633 		if (!mutex_tryenter(hash_lock)) {
8634 			/*
8635 			 * Missed the hash lock. We must retry so we
8636 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
8637 			 */
8638 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
8639 
8640 			/*
8641 			 * We don't want to rescan the headers we've
8642 			 * already marked as having been written out, so
8643 			 * we reinsert the head node so we can pick up
8644 			 * where we left off.
8645 			 */
8646 			list_remove(buflist, head);
8647 			list_insert_after(buflist, hdr, head);
8648 
8649 			mutex_exit(&dev->l2ad_mtx);
8650 
8651 			/*
8652 			 * We wait for the hash lock to become available
8653 			 * to try and prevent busy waiting, and increase
8654 			 * the chance we'll be able to acquire the lock
8655 			 * the next time around.
8656 			 */
8657 			mutex_enter(hash_lock);
8658 			mutex_exit(hash_lock);
8659 			goto top;
8660 		}
8661 
8662 		/*
8663 		 * We could not have been moved into the arc_l2c_only
8664 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
8665 		 * bit being set. Let's just ensure that's being enforced.
8666 		 */
8667 		ASSERT(HDR_HAS_L1HDR(hdr));
8668 
8669 		/*
8670 		 * Skipped - drop L2ARC entry and mark the header as no
8671 		 * longer L2 eligibile.
8672 		 */
8673 		if (zio->io_error != 0) {
8674 			/*
8675 			 * Error - drop L2ARC entry.
8676 			 */
8677 			list_remove(buflist, hdr);
8678 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
8679 
8680 			uint64_t psize = HDR_GET_PSIZE(hdr);
8681 			l2arc_hdr_arcstats_decrement(hdr);
8682 
8683 			bytes_dropped +=
8684 			    vdev_psize_to_asize(dev->l2ad_vdev, psize);
8685 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
8686 			    arc_hdr_size(hdr), hdr);
8687 		}
8688 
8689 		/*
8690 		 * Allow ARC to begin reads and ghost list evictions to
8691 		 * this L2ARC entry.
8692 		 */
8693 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
8694 
8695 		mutex_exit(hash_lock);
8696 	}
8697 
8698 	/*
8699 	 * Free the allocated abd buffers for writing the log blocks.
8700 	 * If the zio failed reclaim the allocated space and remove the
8701 	 * pointers to these log blocks from the log block pointer list
8702 	 * of the L2ARC device.
8703 	 */
8704 	while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
8705 		abd_free(abd_buf->abd);
8706 		zio_buf_free(abd_buf, sizeof (*abd_buf));
8707 		if (zio->io_error != 0) {
8708 			lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
8709 			/*
8710 			 * L2BLK_GET_PSIZE returns aligned size for log
8711 			 * blocks.
8712 			 */
8713 			uint64_t asize =
8714 			    L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
8715 			bytes_dropped += asize;
8716 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8717 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8718 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8719 			    lb_ptr_buf);
8720 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8721 			kmem_free(lb_ptr_buf->lb_ptr,
8722 			    sizeof (l2arc_log_blkptr_t));
8723 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8724 		}
8725 	}
8726 	list_destroy(&cb->l2wcb_abd_list);
8727 
8728 	if (zio->io_error != 0) {
8729 		ARCSTAT_BUMP(arcstat_l2_writes_error);
8730 
8731 		/*
8732 		 * Restore the lbps array in the header to its previous state.
8733 		 * If the list of log block pointers is empty, zero out the
8734 		 * log block pointers in the device header.
8735 		 */
8736 		lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
8737 		for (int i = 0; i < 2; i++) {
8738 			if (lb_ptr_buf == NULL) {
8739 				/*
8740 				 * If the list is empty zero out the device
8741 				 * header. Otherwise zero out the second log
8742 				 * block pointer in the header.
8743 				 */
8744 				if (i == 0) {
8745 					memset(l2dhdr, 0,
8746 					    dev->l2ad_dev_hdr_asize);
8747 				} else {
8748 					memset(&l2dhdr->dh_start_lbps[i], 0,
8749 					    sizeof (l2arc_log_blkptr_t));
8750 				}
8751 				break;
8752 			}
8753 			memcpy(&l2dhdr->dh_start_lbps[i], lb_ptr_buf->lb_ptr,
8754 			    sizeof (l2arc_log_blkptr_t));
8755 			lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
8756 			    lb_ptr_buf);
8757 		}
8758 	}
8759 
8760 	ARCSTAT_BUMP(arcstat_l2_writes_done);
8761 	list_remove(buflist, head);
8762 	ASSERT(!HDR_HAS_L1HDR(head));
8763 	kmem_cache_free(hdr_l2only_cache, head);
8764 	mutex_exit(&dev->l2ad_mtx);
8765 
8766 	ASSERT(dev->l2ad_vdev != NULL);
8767 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
8768 
8769 	l2arc_do_free_on_write();
8770 
8771 	kmem_free(cb, sizeof (l2arc_write_callback_t));
8772 }
8773 
8774 static int
8775 l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
8776 {
8777 	int ret;
8778 	spa_t *spa = zio->io_spa;
8779 	arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
8780 	blkptr_t *bp = zio->io_bp;
8781 	uint8_t salt[ZIO_DATA_SALT_LEN];
8782 	uint8_t iv[ZIO_DATA_IV_LEN];
8783 	uint8_t mac[ZIO_DATA_MAC_LEN];
8784 	boolean_t no_crypt = B_FALSE;
8785 
8786 	/*
8787 	 * ZIL data is never be written to the L2ARC, so we don't need
8788 	 * special handling for its unique MAC storage.
8789 	 */
8790 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
8791 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
8792 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8793 
8794 	/*
8795 	 * If the data was encrypted, decrypt it now. Note that
8796 	 * we must check the bp here and not the hdr, since the
8797 	 * hdr does not have its encryption parameters updated
8798 	 * until arc_read_done().
8799 	 */
8800 	if (BP_IS_ENCRYPTED(bp)) {
8801 		abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8802 		    ARC_HDR_DO_ADAPT | ARC_HDR_USE_RESERVE);
8803 
8804 		zio_crypt_decode_params_bp(bp, salt, iv);
8805 		zio_crypt_decode_mac_bp(bp, mac);
8806 
8807 		ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
8808 		    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
8809 		    salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
8810 		    hdr->b_l1hdr.b_pabd, &no_crypt);
8811 		if (ret != 0) {
8812 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8813 			goto error;
8814 		}
8815 
8816 		/*
8817 		 * If we actually performed decryption, replace b_pabd
8818 		 * with the decrypted data. Otherwise we can just throw
8819 		 * our decryption buffer away.
8820 		 */
8821 		if (!no_crypt) {
8822 			arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8823 			    arc_hdr_size(hdr), hdr);
8824 			hdr->b_l1hdr.b_pabd = eabd;
8825 			zio->io_abd = eabd;
8826 		} else {
8827 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8828 		}
8829 	}
8830 
8831 	/*
8832 	 * If the L2ARC block was compressed, but ARC compression
8833 	 * is disabled we decompress the data into a new buffer and
8834 	 * replace the existing data.
8835 	 */
8836 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8837 	    !HDR_COMPRESSION_ENABLED(hdr)) {
8838 		abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8839 		    ARC_HDR_DO_ADAPT | ARC_HDR_USE_RESERVE);
8840 		void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
8841 
8842 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
8843 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
8844 		    HDR_GET_LSIZE(hdr), &hdr->b_complevel);
8845 		if (ret != 0) {
8846 			abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8847 			arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
8848 			goto error;
8849 		}
8850 
8851 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8852 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8853 		    arc_hdr_size(hdr), hdr);
8854 		hdr->b_l1hdr.b_pabd = cabd;
8855 		zio->io_abd = cabd;
8856 		zio->io_size = HDR_GET_LSIZE(hdr);
8857 	}
8858 
8859 	return (0);
8860 
8861 error:
8862 	return (ret);
8863 }
8864 
8865 
8866 /*
8867  * A read to a cache device completed.  Validate buffer contents before
8868  * handing over to the regular ARC routines.
8869  */
8870 static void
8871 l2arc_read_done(zio_t *zio)
8872 {
8873 	int tfm_error = 0;
8874 	l2arc_read_callback_t *cb = zio->io_private;
8875 	arc_buf_hdr_t *hdr;
8876 	kmutex_t *hash_lock;
8877 	boolean_t valid_cksum;
8878 	boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
8879 	    (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
8880 
8881 	ASSERT3P(zio->io_vd, !=, NULL);
8882 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
8883 
8884 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
8885 
8886 	ASSERT3P(cb, !=, NULL);
8887 	hdr = cb->l2rcb_hdr;
8888 	ASSERT3P(hdr, !=, NULL);
8889 
8890 	hash_lock = HDR_LOCK(hdr);
8891 	mutex_enter(hash_lock);
8892 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
8893 
8894 	/*
8895 	 * If the data was read into a temporary buffer,
8896 	 * move it and free the buffer.
8897 	 */
8898 	if (cb->l2rcb_abd != NULL) {
8899 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
8900 		if (zio->io_error == 0) {
8901 			if (using_rdata) {
8902 				abd_copy(hdr->b_crypt_hdr.b_rabd,
8903 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8904 			} else {
8905 				abd_copy(hdr->b_l1hdr.b_pabd,
8906 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8907 			}
8908 		}
8909 
8910 		/*
8911 		 * The following must be done regardless of whether
8912 		 * there was an error:
8913 		 * - free the temporary buffer
8914 		 * - point zio to the real ARC buffer
8915 		 * - set zio size accordingly
8916 		 * These are required because zio is either re-used for
8917 		 * an I/O of the block in the case of the error
8918 		 * or the zio is passed to arc_read_done() and it
8919 		 * needs real data.
8920 		 */
8921 		abd_free(cb->l2rcb_abd);
8922 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
8923 
8924 		if (using_rdata) {
8925 			ASSERT(HDR_HAS_RABD(hdr));
8926 			zio->io_abd = zio->io_orig_abd =
8927 			    hdr->b_crypt_hdr.b_rabd;
8928 		} else {
8929 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8930 			zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8931 		}
8932 	}
8933 
8934 	ASSERT3P(zio->io_abd, !=, NULL);
8935 
8936 	/*
8937 	 * Check this survived the L2ARC journey.
8938 	 */
8939 	ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8940 	    (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8941 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
8942 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
8943 	zio->io_prop.zp_complevel = hdr->b_complevel;
8944 
8945 	valid_cksum = arc_cksum_is_equal(hdr, zio);
8946 
8947 	/*
8948 	 * b_rabd will always match the data as it exists on disk if it is
8949 	 * being used. Therefore if we are reading into b_rabd we do not
8950 	 * attempt to untransform the data.
8951 	 */
8952 	if (valid_cksum && !using_rdata)
8953 		tfm_error = l2arc_untransform(zio, cb);
8954 
8955 	if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8956 	    !HDR_L2_EVICTED(hdr)) {
8957 		mutex_exit(hash_lock);
8958 		zio->io_private = hdr;
8959 		arc_read_done(zio);
8960 	} else {
8961 		/*
8962 		 * Buffer didn't survive caching.  Increment stats and
8963 		 * reissue to the original storage device.
8964 		 */
8965 		if (zio->io_error != 0) {
8966 			ARCSTAT_BUMP(arcstat_l2_io_error);
8967 		} else {
8968 			zio->io_error = SET_ERROR(EIO);
8969 		}
8970 		if (!valid_cksum || tfm_error != 0)
8971 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8972 
8973 		/*
8974 		 * If there's no waiter, issue an async i/o to the primary
8975 		 * storage now.  If there *is* a waiter, the caller must
8976 		 * issue the i/o in a context where it's OK to block.
8977 		 */
8978 		if (zio->io_waiter == NULL) {
8979 			zio_t *pio = zio_unique_parent(zio);
8980 			void *abd = (using_rdata) ?
8981 			    hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
8982 
8983 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8984 
8985 			zio = zio_read(pio, zio->io_spa, zio->io_bp,
8986 			    abd, zio->io_size, arc_read_done,
8987 			    hdr, zio->io_priority, cb->l2rcb_flags,
8988 			    &cb->l2rcb_zb);
8989 
8990 			/*
8991 			 * Original ZIO will be freed, so we need to update
8992 			 * ARC header with the new ZIO pointer to be used
8993 			 * by zio_change_priority() in arc_read().
8994 			 */
8995 			for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
8996 			    acb != NULL; acb = acb->acb_next)
8997 				acb->acb_zio_head = zio;
8998 
8999 			mutex_exit(hash_lock);
9000 			zio_nowait(zio);
9001 		} else {
9002 			mutex_exit(hash_lock);
9003 		}
9004 	}
9005 
9006 	kmem_free(cb, sizeof (l2arc_read_callback_t));
9007 }
9008 
9009 /*
9010  * This is the list priority from which the L2ARC will search for pages to
9011  * cache.  This is used within loops (0..3) to cycle through lists in the
9012  * desired order.  This order can have a significant effect on cache
9013  * performance.
9014  *
9015  * Currently the metadata lists are hit first, MFU then MRU, followed by
9016  * the data lists.  This function returns a locked list, and also returns
9017  * the lock pointer.
9018  */
9019 static multilist_sublist_t *
9020 l2arc_sublist_lock(int list_num)
9021 {
9022 	multilist_t *ml = NULL;
9023 	unsigned int idx;
9024 
9025 	ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
9026 
9027 	switch (list_num) {
9028 	case 0:
9029 		ml = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
9030 		break;
9031 	case 1:
9032 		ml = &arc_mru->arcs_list[ARC_BUFC_METADATA];
9033 		break;
9034 	case 2:
9035 		ml = &arc_mfu->arcs_list[ARC_BUFC_DATA];
9036 		break;
9037 	case 3:
9038 		ml = &arc_mru->arcs_list[ARC_BUFC_DATA];
9039 		break;
9040 	default:
9041 		return (NULL);
9042 	}
9043 
9044 	/*
9045 	 * Return a randomly-selected sublist. This is acceptable
9046 	 * because the caller feeds only a little bit of data for each
9047 	 * call (8MB). Subsequent calls will result in different
9048 	 * sublists being selected.
9049 	 */
9050 	idx = multilist_get_random_index(ml);
9051 	return (multilist_sublist_lock(ml, idx));
9052 }
9053 
9054 /*
9055  * Calculates the maximum overhead of L2ARC metadata log blocks for a given
9056  * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
9057  * overhead in processing to make sure there is enough headroom available
9058  * when writing buffers.
9059  */
9060 static inline uint64_t
9061 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
9062 {
9063 	if (dev->l2ad_log_entries == 0) {
9064 		return (0);
9065 	} else {
9066 		uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
9067 
9068 		uint64_t log_blocks = (log_entries +
9069 		    dev->l2ad_log_entries - 1) /
9070 		    dev->l2ad_log_entries;
9071 
9072 		return (vdev_psize_to_asize(dev->l2ad_vdev,
9073 		    sizeof (l2arc_log_blk_phys_t)) * log_blocks);
9074 	}
9075 }
9076 
9077 /*
9078  * Evict buffers from the device write hand to the distance specified in
9079  * bytes. This distance may span populated buffers, it may span nothing.
9080  * This is clearing a region on the L2ARC device ready for writing.
9081  * If the 'all' boolean is set, every buffer is evicted.
9082  */
9083 static void
9084 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
9085 {
9086 	list_t *buflist;
9087 	arc_buf_hdr_t *hdr, *hdr_prev;
9088 	kmutex_t *hash_lock;
9089 	uint64_t taddr;
9090 	l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
9091 	vdev_t *vd = dev->l2ad_vdev;
9092 	boolean_t rerun;
9093 
9094 	buflist = &dev->l2ad_buflist;
9095 
9096 	/*
9097 	 * We need to add in the worst case scenario of log block overhead.
9098 	 */
9099 	distance += l2arc_log_blk_overhead(distance, dev);
9100 	if (vd->vdev_has_trim && l2arc_trim_ahead > 0) {
9101 		/*
9102 		 * Trim ahead of the write size 64MB or (l2arc_trim_ahead/100)
9103 		 * times the write size, whichever is greater.
9104 		 */
9105 		distance += MAX(64 * 1024 * 1024,
9106 		    (distance * l2arc_trim_ahead) / 100);
9107 	}
9108 
9109 top:
9110 	rerun = B_FALSE;
9111 	if (dev->l2ad_hand >= (dev->l2ad_end - distance)) {
9112 		/*
9113 		 * When there is no space to accommodate upcoming writes,
9114 		 * evict to the end. Then bump the write and evict hands
9115 		 * to the start and iterate. This iteration does not
9116 		 * happen indefinitely as we make sure in
9117 		 * l2arc_write_size() that when the write hand is reset,
9118 		 * the write size does not exceed the end of the device.
9119 		 */
9120 		rerun = B_TRUE;
9121 		taddr = dev->l2ad_end;
9122 	} else {
9123 		taddr = dev->l2ad_hand + distance;
9124 	}
9125 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
9126 	    uint64_t, taddr, boolean_t, all);
9127 
9128 	if (!all) {
9129 		/*
9130 		 * This check has to be placed after deciding whether to
9131 		 * iterate (rerun).
9132 		 */
9133 		if (dev->l2ad_first) {
9134 			/*
9135 			 * This is the first sweep through the device. There is
9136 			 * nothing to evict. We have already trimmmed the
9137 			 * whole device.
9138 			 */
9139 			goto out;
9140 		} else {
9141 			/*
9142 			 * Trim the space to be evicted.
9143 			 */
9144 			if (vd->vdev_has_trim && dev->l2ad_evict < taddr &&
9145 			    l2arc_trim_ahead > 0) {
9146 				/*
9147 				 * We have to drop the spa_config lock because
9148 				 * vdev_trim_range() will acquire it.
9149 				 * l2ad_evict already accounts for the label
9150 				 * size. To prevent vdev_trim_ranges() from
9151 				 * adding it again, we subtract it from
9152 				 * l2ad_evict.
9153 				 */
9154 				spa_config_exit(dev->l2ad_spa, SCL_L2ARC, dev);
9155 				vdev_trim_simple(vd,
9156 				    dev->l2ad_evict - VDEV_LABEL_START_SIZE,
9157 				    taddr - dev->l2ad_evict);
9158 				spa_config_enter(dev->l2ad_spa, SCL_L2ARC, dev,
9159 				    RW_READER);
9160 			}
9161 
9162 			/*
9163 			 * When rebuilding L2ARC we retrieve the evict hand
9164 			 * from the header of the device. Of note, l2arc_evict()
9165 			 * does not actually delete buffers from the cache
9166 			 * device, but trimming may do so depending on the
9167 			 * hardware implementation. Thus keeping track of the
9168 			 * evict hand is useful.
9169 			 */
9170 			dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
9171 		}
9172 	}
9173 
9174 retry:
9175 	mutex_enter(&dev->l2ad_mtx);
9176 	/*
9177 	 * We have to account for evicted log blocks. Run vdev_space_update()
9178 	 * on log blocks whose offset (in bytes) is before the evicted offset
9179 	 * (in bytes) by searching in the list of pointers to log blocks
9180 	 * present in the L2ARC device.
9181 	 */
9182 	for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
9183 	    lb_ptr_buf = lb_ptr_buf_prev) {
9184 
9185 		lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
9186 
9187 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
9188 		uint64_t asize = L2BLK_GET_PSIZE(
9189 		    (lb_ptr_buf->lb_ptr)->lbp_prop);
9190 
9191 		/*
9192 		 * We don't worry about log blocks left behind (ie
9193 		 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
9194 		 * will never write more than l2arc_evict() evicts.
9195 		 */
9196 		if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
9197 			break;
9198 		} else {
9199 			vdev_space_update(vd, -asize, 0, 0);
9200 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
9201 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
9202 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
9203 			    lb_ptr_buf);
9204 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
9205 			list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
9206 			kmem_free(lb_ptr_buf->lb_ptr,
9207 			    sizeof (l2arc_log_blkptr_t));
9208 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
9209 		}
9210 	}
9211 
9212 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
9213 		hdr_prev = list_prev(buflist, hdr);
9214 
9215 		ASSERT(!HDR_EMPTY(hdr));
9216 		hash_lock = HDR_LOCK(hdr);
9217 
9218 		/*
9219 		 * We cannot use mutex_enter or else we can deadlock
9220 		 * with l2arc_write_buffers (due to swapping the order
9221 		 * the hash lock and l2ad_mtx are taken).
9222 		 */
9223 		if (!mutex_tryenter(hash_lock)) {
9224 			/*
9225 			 * Missed the hash lock.  Retry.
9226 			 */
9227 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
9228 			mutex_exit(&dev->l2ad_mtx);
9229 			mutex_enter(hash_lock);
9230 			mutex_exit(hash_lock);
9231 			goto retry;
9232 		}
9233 
9234 		/*
9235 		 * A header can't be on this list if it doesn't have L2 header.
9236 		 */
9237 		ASSERT(HDR_HAS_L2HDR(hdr));
9238 
9239 		/* Ensure this header has finished being written. */
9240 		ASSERT(!HDR_L2_WRITING(hdr));
9241 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
9242 
9243 		if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
9244 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
9245 			/*
9246 			 * We've evicted to the target address,
9247 			 * or the end of the device.
9248 			 */
9249 			mutex_exit(hash_lock);
9250 			break;
9251 		}
9252 
9253 		if (!HDR_HAS_L1HDR(hdr)) {
9254 			ASSERT(!HDR_L2_READING(hdr));
9255 			/*
9256 			 * This doesn't exist in the ARC.  Destroy.
9257 			 * arc_hdr_destroy() will call list_remove()
9258 			 * and decrement arcstat_l2_lsize.
9259 			 */
9260 			arc_change_state(arc_anon, hdr, hash_lock);
9261 			arc_hdr_destroy(hdr);
9262 		} else {
9263 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
9264 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
9265 			/*
9266 			 * Invalidate issued or about to be issued
9267 			 * reads, since we may be about to write
9268 			 * over this location.
9269 			 */
9270 			if (HDR_L2_READING(hdr)) {
9271 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
9272 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
9273 			}
9274 
9275 			arc_hdr_l2hdr_destroy(hdr);
9276 		}
9277 		mutex_exit(hash_lock);
9278 	}
9279 	mutex_exit(&dev->l2ad_mtx);
9280 
9281 out:
9282 	/*
9283 	 * We need to check if we evict all buffers, otherwise we may iterate
9284 	 * unnecessarily.
9285 	 */
9286 	if (!all && rerun) {
9287 		/*
9288 		 * Bump device hand to the device start if it is approaching the
9289 		 * end. l2arc_evict() has already evicted ahead for this case.
9290 		 */
9291 		dev->l2ad_hand = dev->l2ad_start;
9292 		dev->l2ad_evict = dev->l2ad_start;
9293 		dev->l2ad_first = B_FALSE;
9294 		goto top;
9295 	}
9296 
9297 	if (!all) {
9298 		/*
9299 		 * In case of cache device removal (all) the following
9300 		 * assertions may be violated without functional consequences
9301 		 * as the device is about to be removed.
9302 		 */
9303 		ASSERT3U(dev->l2ad_hand + distance, <, dev->l2ad_end);
9304 		if (!dev->l2ad_first)
9305 			ASSERT3U(dev->l2ad_hand, <, dev->l2ad_evict);
9306 	}
9307 }
9308 
9309 /*
9310  * Handle any abd transforms that might be required for writing to the L2ARC.
9311  * If successful, this function will always return an abd with the data
9312  * transformed as it is on disk in a new abd of asize bytes.
9313  */
9314 static int
9315 l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
9316     abd_t **abd_out)
9317 {
9318 	int ret;
9319 	void *tmp = NULL;
9320 	abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
9321 	enum zio_compress compress = HDR_GET_COMPRESS(hdr);
9322 	uint64_t psize = HDR_GET_PSIZE(hdr);
9323 	uint64_t size = arc_hdr_size(hdr);
9324 	boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
9325 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
9326 	dsl_crypto_key_t *dck = NULL;
9327 	uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
9328 	boolean_t no_crypt = B_FALSE;
9329 
9330 	ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
9331 	    !HDR_COMPRESSION_ENABLED(hdr)) ||
9332 	    HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
9333 	ASSERT3U(psize, <=, asize);
9334 
9335 	/*
9336 	 * If this data simply needs its own buffer, we simply allocate it
9337 	 * and copy the data. This may be done to eliminate a dependency on a
9338 	 * shared buffer or to reallocate the buffer to match asize.
9339 	 */
9340 	if (HDR_HAS_RABD(hdr) && asize != psize) {
9341 		ASSERT3U(asize, >=, psize);
9342 		to_write = abd_alloc_for_io(asize, ismd);
9343 		abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
9344 		if (psize != asize)
9345 			abd_zero_off(to_write, psize, asize - psize);
9346 		goto out;
9347 	}
9348 
9349 	if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
9350 	    !HDR_ENCRYPTED(hdr)) {
9351 		ASSERT3U(size, ==, psize);
9352 		to_write = abd_alloc_for_io(asize, ismd);
9353 		abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
9354 		if (size != asize)
9355 			abd_zero_off(to_write, size, asize - size);
9356 		goto out;
9357 	}
9358 
9359 	if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
9360 		/*
9361 		 * In some cases, we can wind up with size > asize, so
9362 		 * we need to opt for the larger allocation option here.
9363 		 *
9364 		 * (We also need abd_return_buf_copy in all cases because
9365 		 * it's an ASSERT() to modify the buffer before returning it
9366 		 * with arc_return_buf(), and all the compressors
9367 		 * write things before deciding to fail compression in nearly
9368 		 * every case.)
9369 		 */
9370 		cabd = abd_alloc_for_io(size, ismd);
9371 		tmp = abd_borrow_buf(cabd, size);
9372 
9373 		psize = zio_compress_data(compress, to_write, tmp, size,
9374 		    hdr->b_complevel);
9375 
9376 		if (psize >= asize) {
9377 			psize = HDR_GET_PSIZE(hdr);
9378 			abd_return_buf_copy(cabd, tmp, size);
9379 			HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
9380 			to_write = cabd;
9381 			abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
9382 			if (psize != asize)
9383 				abd_zero_off(to_write, psize, asize - psize);
9384 			goto encrypt;
9385 		}
9386 		ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
9387 		if (psize < asize)
9388 			memset((char *)tmp + psize, 0, asize - psize);
9389 		psize = HDR_GET_PSIZE(hdr);
9390 		abd_return_buf_copy(cabd, tmp, size);
9391 		to_write = cabd;
9392 	}
9393 
9394 encrypt:
9395 	if (HDR_ENCRYPTED(hdr)) {
9396 		eabd = abd_alloc_for_io(asize, ismd);
9397 
9398 		/*
9399 		 * If the dataset was disowned before the buffer
9400 		 * made it to this point, the key to re-encrypt
9401 		 * it won't be available. In this case we simply
9402 		 * won't write the buffer to the L2ARC.
9403 		 */
9404 		ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
9405 		    FTAG, &dck);
9406 		if (ret != 0)
9407 			goto error;
9408 
9409 		ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
9410 		    hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
9411 		    hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
9412 		    &no_crypt);
9413 		if (ret != 0)
9414 			goto error;
9415 
9416 		if (no_crypt)
9417 			abd_copy(eabd, to_write, psize);
9418 
9419 		if (psize != asize)
9420 			abd_zero_off(eabd, psize, asize - psize);
9421 
9422 		/* assert that the MAC we got here matches the one we saved */
9423 		ASSERT0(memcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
9424 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
9425 
9426 		if (to_write == cabd)
9427 			abd_free(cabd);
9428 
9429 		to_write = eabd;
9430 	}
9431 
9432 out:
9433 	ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
9434 	*abd_out = to_write;
9435 	return (0);
9436 
9437 error:
9438 	if (dck != NULL)
9439 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
9440 	if (cabd != NULL)
9441 		abd_free(cabd);
9442 	if (eabd != NULL)
9443 		abd_free(eabd);
9444 
9445 	*abd_out = NULL;
9446 	return (ret);
9447 }
9448 
9449 static void
9450 l2arc_blk_fetch_done(zio_t *zio)
9451 {
9452 	l2arc_read_callback_t *cb;
9453 
9454 	cb = zio->io_private;
9455 	if (cb->l2rcb_abd != NULL)
9456 		abd_free(cb->l2rcb_abd);
9457 	kmem_free(cb, sizeof (l2arc_read_callback_t));
9458 }
9459 
9460 /*
9461  * Find and write ARC buffers to the L2ARC device.
9462  *
9463  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
9464  * for reading until they have completed writing.
9465  * The headroom_boost is an in-out parameter used to maintain headroom boost
9466  * state between calls to this function.
9467  *
9468  * Returns the number of bytes actually written (which may be smaller than
9469  * the delta by which the device hand has changed due to alignment and the
9470  * writing of log blocks).
9471  */
9472 static uint64_t
9473 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
9474 {
9475 	arc_buf_hdr_t 		*hdr, *hdr_prev, *head;
9476 	uint64_t 		write_asize, write_psize, write_lsize, headroom;
9477 	boolean_t		full;
9478 	l2arc_write_callback_t	*cb = NULL;
9479 	zio_t 			*pio, *wzio;
9480 	uint64_t 		guid = spa_load_guid(spa);
9481 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9482 
9483 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
9484 
9485 	pio = NULL;
9486 	write_lsize = write_asize = write_psize = 0;
9487 	full = B_FALSE;
9488 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
9489 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
9490 
9491 	/*
9492 	 * Copy buffers for L2ARC writing.
9493 	 */
9494 	for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++) {
9495 		/*
9496 		 * If pass == 1 or 3, we cache MRU metadata and data
9497 		 * respectively.
9498 		 */
9499 		if (l2arc_mfuonly) {
9500 			if (pass == 1 || pass == 3)
9501 				continue;
9502 		}
9503 
9504 		multilist_sublist_t *mls = l2arc_sublist_lock(pass);
9505 		uint64_t passed_sz = 0;
9506 
9507 		VERIFY3P(mls, !=, NULL);
9508 
9509 		/*
9510 		 * L2ARC fast warmup.
9511 		 *
9512 		 * Until the ARC is warm and starts to evict, read from the
9513 		 * head of the ARC lists rather than the tail.
9514 		 */
9515 		if (arc_warm == B_FALSE)
9516 			hdr = multilist_sublist_head(mls);
9517 		else
9518 			hdr = multilist_sublist_tail(mls);
9519 
9520 		headroom = target_sz * l2arc_headroom;
9521 		if (zfs_compressed_arc_enabled)
9522 			headroom = (headroom * l2arc_headroom_boost) / 100;
9523 
9524 		for (; hdr; hdr = hdr_prev) {
9525 			kmutex_t *hash_lock;
9526 			abd_t *to_write = NULL;
9527 
9528 			if (arc_warm == B_FALSE)
9529 				hdr_prev = multilist_sublist_next(mls, hdr);
9530 			else
9531 				hdr_prev = multilist_sublist_prev(mls, hdr);
9532 
9533 			hash_lock = HDR_LOCK(hdr);
9534 			if (!mutex_tryenter(hash_lock)) {
9535 				/*
9536 				 * Skip this buffer rather than waiting.
9537 				 */
9538 				continue;
9539 			}
9540 
9541 			passed_sz += HDR_GET_LSIZE(hdr);
9542 			if (l2arc_headroom != 0 && passed_sz > headroom) {
9543 				/*
9544 				 * Searched too far.
9545 				 */
9546 				mutex_exit(hash_lock);
9547 				break;
9548 			}
9549 
9550 			if (!l2arc_write_eligible(guid, hdr)) {
9551 				mutex_exit(hash_lock);
9552 				continue;
9553 			}
9554 
9555 			ASSERT(HDR_HAS_L1HDR(hdr));
9556 
9557 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
9558 			ASSERT3U(arc_hdr_size(hdr), >, 0);
9559 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
9560 			    HDR_HAS_RABD(hdr));
9561 			uint64_t psize = HDR_GET_PSIZE(hdr);
9562 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
9563 			    psize);
9564 
9565 			if ((write_asize + asize) > target_sz) {
9566 				full = B_TRUE;
9567 				mutex_exit(hash_lock);
9568 				break;
9569 			}
9570 
9571 			/*
9572 			 * We rely on the L1 portion of the header below, so
9573 			 * it's invalid for this header to have been evicted out
9574 			 * of the ghost cache, prior to being written out. The
9575 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
9576 			 */
9577 			arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
9578 
9579 			/*
9580 			 * If this header has b_rabd, we can use this since it
9581 			 * must always match the data exactly as it exists on
9582 			 * disk. Otherwise, the L2ARC can normally use the
9583 			 * hdr's data, but if we're sharing data between the
9584 			 * hdr and one of its bufs, L2ARC needs its own copy of
9585 			 * the data so that the ZIO below can't race with the
9586 			 * buf consumer. To ensure that this copy will be
9587 			 * available for the lifetime of the ZIO and be cleaned
9588 			 * up afterwards, we add it to the l2arc_free_on_write
9589 			 * queue. If we need to apply any transforms to the
9590 			 * data (compression, encryption) we will also need the
9591 			 * extra buffer.
9592 			 */
9593 			if (HDR_HAS_RABD(hdr) && psize == asize) {
9594 				to_write = hdr->b_crypt_hdr.b_rabd;
9595 			} else if ((HDR_COMPRESSION_ENABLED(hdr) ||
9596 			    HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
9597 			    !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
9598 			    psize == asize) {
9599 				to_write = hdr->b_l1hdr.b_pabd;
9600 			} else {
9601 				int ret;
9602 				arc_buf_contents_t type = arc_buf_type(hdr);
9603 
9604 				ret = l2arc_apply_transforms(spa, hdr, asize,
9605 				    &to_write);
9606 				if (ret != 0) {
9607 					arc_hdr_clear_flags(hdr,
9608 					    ARC_FLAG_L2_WRITING);
9609 					mutex_exit(hash_lock);
9610 					continue;
9611 				}
9612 
9613 				l2arc_free_abd_on_write(to_write, asize, type);
9614 			}
9615 
9616 			if (pio == NULL) {
9617 				/*
9618 				 * Insert a dummy header on the buflist so
9619 				 * l2arc_write_done() can find where the
9620 				 * write buffers begin without searching.
9621 				 */
9622 				mutex_enter(&dev->l2ad_mtx);
9623 				list_insert_head(&dev->l2ad_buflist, head);
9624 				mutex_exit(&dev->l2ad_mtx);
9625 
9626 				cb = kmem_alloc(
9627 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
9628 				cb->l2wcb_dev = dev;
9629 				cb->l2wcb_head = head;
9630 				/*
9631 				 * Create a list to save allocated abd buffers
9632 				 * for l2arc_log_blk_commit().
9633 				 */
9634 				list_create(&cb->l2wcb_abd_list,
9635 				    sizeof (l2arc_lb_abd_buf_t),
9636 				    offsetof(l2arc_lb_abd_buf_t, node));
9637 				pio = zio_root(spa, l2arc_write_done, cb,
9638 				    ZIO_FLAG_CANFAIL);
9639 			}
9640 
9641 			hdr->b_l2hdr.b_dev = dev;
9642 			hdr->b_l2hdr.b_hits = 0;
9643 
9644 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
9645 			hdr->b_l2hdr.b_arcs_state =
9646 			    hdr->b_l1hdr.b_state->arcs_state;
9647 			arc_hdr_set_flags(hdr, ARC_FLAG_HAS_L2HDR);
9648 
9649 			mutex_enter(&dev->l2ad_mtx);
9650 			list_insert_head(&dev->l2ad_buflist, hdr);
9651 			mutex_exit(&dev->l2ad_mtx);
9652 
9653 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
9654 			    arc_hdr_size(hdr), hdr);
9655 
9656 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
9657 			    hdr->b_l2hdr.b_daddr, asize, to_write,
9658 			    ZIO_CHECKSUM_OFF, NULL, hdr,
9659 			    ZIO_PRIORITY_ASYNC_WRITE,
9660 			    ZIO_FLAG_CANFAIL, B_FALSE);
9661 
9662 			write_lsize += HDR_GET_LSIZE(hdr);
9663 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
9664 			    zio_t *, wzio);
9665 
9666 			write_psize += psize;
9667 			write_asize += asize;
9668 			dev->l2ad_hand += asize;
9669 			l2arc_hdr_arcstats_increment(hdr);
9670 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9671 
9672 			mutex_exit(hash_lock);
9673 
9674 			/*
9675 			 * Append buf info to current log and commit if full.
9676 			 * arcstat_l2_{size,asize} kstats are updated
9677 			 * internally.
9678 			 */
9679 			if (l2arc_log_blk_insert(dev, hdr))
9680 				l2arc_log_blk_commit(dev, pio, cb);
9681 
9682 			zio_nowait(wzio);
9683 		}
9684 
9685 		multilist_sublist_unlock(mls);
9686 
9687 		if (full == B_TRUE)
9688 			break;
9689 	}
9690 
9691 	/* No buffers selected for writing? */
9692 	if (pio == NULL) {
9693 		ASSERT0(write_lsize);
9694 		ASSERT(!HDR_HAS_L1HDR(head));
9695 		kmem_cache_free(hdr_l2only_cache, head);
9696 
9697 		/*
9698 		 * Although we did not write any buffers l2ad_evict may
9699 		 * have advanced.
9700 		 */
9701 		if (dev->l2ad_evict != l2dhdr->dh_evict)
9702 			l2arc_dev_hdr_update(dev);
9703 
9704 		return (0);
9705 	}
9706 
9707 	if (!dev->l2ad_first)
9708 		ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
9709 
9710 	ASSERT3U(write_asize, <=, target_sz);
9711 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
9712 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
9713 
9714 	dev->l2ad_writing = B_TRUE;
9715 	(void) zio_wait(pio);
9716 	dev->l2ad_writing = B_FALSE;
9717 
9718 	/*
9719 	 * Update the device header after the zio completes as
9720 	 * l2arc_write_done() may have updated the memory holding the log block
9721 	 * pointers in the device header.
9722 	 */
9723 	l2arc_dev_hdr_update(dev);
9724 
9725 	return (write_asize);
9726 }
9727 
9728 static boolean_t
9729 l2arc_hdr_limit_reached(void)
9730 {
9731 	int64_t s = aggsum_upper_bound(&arc_sums.arcstat_l2_hdr_size);
9732 
9733 	return (arc_reclaim_needed() || (s > arc_meta_limit * 3 / 4) ||
9734 	    (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
9735 }
9736 
9737 /*
9738  * This thread feeds the L2ARC at regular intervals.  This is the beating
9739  * heart of the L2ARC.
9740  */
9741 static  __attribute__((noreturn)) void
9742 l2arc_feed_thread(void *unused)
9743 {
9744 	(void) unused;
9745 	callb_cpr_t cpr;
9746 	l2arc_dev_t *dev;
9747 	spa_t *spa;
9748 	uint64_t size, wrote;
9749 	clock_t begin, next = ddi_get_lbolt();
9750 	fstrans_cookie_t cookie;
9751 
9752 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
9753 
9754 	mutex_enter(&l2arc_feed_thr_lock);
9755 
9756 	cookie = spl_fstrans_mark();
9757 	while (l2arc_thread_exit == 0) {
9758 		CALLB_CPR_SAFE_BEGIN(&cpr);
9759 		(void) cv_timedwait_idle(&l2arc_feed_thr_cv,
9760 		    &l2arc_feed_thr_lock, next);
9761 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
9762 		next = ddi_get_lbolt() + hz;
9763 
9764 		/*
9765 		 * Quick check for L2ARC devices.
9766 		 */
9767 		mutex_enter(&l2arc_dev_mtx);
9768 		if (l2arc_ndev == 0) {
9769 			mutex_exit(&l2arc_dev_mtx);
9770 			continue;
9771 		}
9772 		mutex_exit(&l2arc_dev_mtx);
9773 		begin = ddi_get_lbolt();
9774 
9775 		/*
9776 		 * This selects the next l2arc device to write to, and in
9777 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
9778 		 * will return NULL if there are now no l2arc devices or if
9779 		 * they are all faulted.
9780 		 *
9781 		 * If a device is returned, its spa's config lock is also
9782 		 * held to prevent device removal.  l2arc_dev_get_next()
9783 		 * will grab and release l2arc_dev_mtx.
9784 		 */
9785 		if ((dev = l2arc_dev_get_next()) == NULL)
9786 			continue;
9787 
9788 		spa = dev->l2ad_spa;
9789 		ASSERT3P(spa, !=, NULL);
9790 
9791 		/*
9792 		 * If the pool is read-only then force the feed thread to
9793 		 * sleep a little longer.
9794 		 */
9795 		if (!spa_writeable(spa)) {
9796 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
9797 			spa_config_exit(spa, SCL_L2ARC, dev);
9798 			continue;
9799 		}
9800 
9801 		/*
9802 		 * Avoid contributing to memory pressure.
9803 		 */
9804 		if (l2arc_hdr_limit_reached()) {
9805 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
9806 			spa_config_exit(spa, SCL_L2ARC, dev);
9807 			continue;
9808 		}
9809 
9810 		ARCSTAT_BUMP(arcstat_l2_feeds);
9811 
9812 		size = l2arc_write_size(dev);
9813 
9814 		/*
9815 		 * Evict L2ARC buffers that will be overwritten.
9816 		 */
9817 		l2arc_evict(dev, size, B_FALSE);
9818 
9819 		/*
9820 		 * Write ARC buffers.
9821 		 */
9822 		wrote = l2arc_write_buffers(spa, dev, size);
9823 
9824 		/*
9825 		 * Calculate interval between writes.
9826 		 */
9827 		next = l2arc_write_interval(begin, size, wrote);
9828 		spa_config_exit(spa, SCL_L2ARC, dev);
9829 	}
9830 	spl_fstrans_unmark(cookie);
9831 
9832 	l2arc_thread_exit = 0;
9833 	cv_broadcast(&l2arc_feed_thr_cv);
9834 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
9835 	thread_exit();
9836 }
9837 
9838 boolean_t
9839 l2arc_vdev_present(vdev_t *vd)
9840 {
9841 	return (l2arc_vdev_get(vd) != NULL);
9842 }
9843 
9844 /*
9845  * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
9846  * the vdev_t isn't an L2ARC device.
9847  */
9848 l2arc_dev_t *
9849 l2arc_vdev_get(vdev_t *vd)
9850 {
9851 	l2arc_dev_t	*dev;
9852 
9853 	mutex_enter(&l2arc_dev_mtx);
9854 	for (dev = list_head(l2arc_dev_list); dev != NULL;
9855 	    dev = list_next(l2arc_dev_list, dev)) {
9856 		if (dev->l2ad_vdev == vd)
9857 			break;
9858 	}
9859 	mutex_exit(&l2arc_dev_mtx);
9860 
9861 	return (dev);
9862 }
9863 
9864 static void
9865 l2arc_rebuild_dev(l2arc_dev_t *dev, boolean_t reopen)
9866 {
9867 	l2arc_dev_hdr_phys_t *l2dhdr = dev->l2ad_dev_hdr;
9868 	uint64_t l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9869 	spa_t *spa = dev->l2ad_spa;
9870 
9871 	/*
9872 	 * The L2ARC has to hold at least the payload of one log block for
9873 	 * them to be restored (persistent L2ARC). The payload of a log block
9874 	 * depends on the amount of its log entries. We always write log blocks
9875 	 * with 1022 entries. How many of them are committed or restored depends
9876 	 * on the size of the L2ARC device. Thus the maximum payload of
9877 	 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
9878 	 * is less than that, we reduce the amount of committed and restored
9879 	 * log entries per block so as to enable persistence.
9880 	 */
9881 	if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
9882 		dev->l2ad_log_entries = 0;
9883 	} else {
9884 		dev->l2ad_log_entries = MIN((dev->l2ad_end -
9885 		    dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
9886 		    L2ARC_LOG_BLK_MAX_ENTRIES);
9887 	}
9888 
9889 	/*
9890 	 * Read the device header, if an error is returned do not rebuild L2ARC.
9891 	 */
9892 	if (l2arc_dev_hdr_read(dev) == 0 && dev->l2ad_log_entries > 0) {
9893 		/*
9894 		 * If we are onlining a cache device (vdev_reopen) that was
9895 		 * still present (l2arc_vdev_present()) and rebuild is enabled,
9896 		 * we should evict all ARC buffers and pointers to log blocks
9897 		 * and reclaim their space before restoring its contents to
9898 		 * L2ARC.
9899 		 */
9900 		if (reopen) {
9901 			if (!l2arc_rebuild_enabled) {
9902 				return;
9903 			} else {
9904 				l2arc_evict(dev, 0, B_TRUE);
9905 				/* start a new log block */
9906 				dev->l2ad_log_ent_idx = 0;
9907 				dev->l2ad_log_blk_payload_asize = 0;
9908 				dev->l2ad_log_blk_payload_start = 0;
9909 			}
9910 		}
9911 		/*
9912 		 * Just mark the device as pending for a rebuild. We won't
9913 		 * be starting a rebuild in line here as it would block pool
9914 		 * import. Instead spa_load_impl will hand that off to an
9915 		 * async task which will call l2arc_spa_rebuild_start.
9916 		 */
9917 		dev->l2ad_rebuild = B_TRUE;
9918 	} else if (spa_writeable(spa)) {
9919 		/*
9920 		 * In this case TRIM the whole device if l2arc_trim_ahead > 0,
9921 		 * otherwise create a new header. We zero out the memory holding
9922 		 * the header to reset dh_start_lbps. If we TRIM the whole
9923 		 * device the new header will be written by
9924 		 * vdev_trim_l2arc_thread() at the end of the TRIM to update the
9925 		 * trim_state in the header too. When reading the header, if
9926 		 * trim_state is not VDEV_TRIM_COMPLETE and l2arc_trim_ahead > 0
9927 		 * we opt to TRIM the whole device again.
9928 		 */
9929 		if (l2arc_trim_ahead > 0) {
9930 			dev->l2ad_trim_all = B_TRUE;
9931 		} else {
9932 			memset(l2dhdr, 0, l2dhdr_asize);
9933 			l2arc_dev_hdr_update(dev);
9934 		}
9935 	}
9936 }
9937 
9938 /*
9939  * Add a vdev for use by the L2ARC.  By this point the spa has already
9940  * validated the vdev and opened it.
9941  */
9942 void
9943 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
9944 {
9945 	l2arc_dev_t		*adddev;
9946 	uint64_t		l2dhdr_asize;
9947 
9948 	ASSERT(!l2arc_vdev_present(vd));
9949 
9950 	/*
9951 	 * Create a new l2arc device entry.
9952 	 */
9953 	adddev = vmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
9954 	adddev->l2ad_spa = spa;
9955 	adddev->l2ad_vdev = vd;
9956 	/* leave extra size for an l2arc device header */
9957 	l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
9958 	    MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
9959 	adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
9960 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
9961 	ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
9962 	adddev->l2ad_hand = adddev->l2ad_start;
9963 	adddev->l2ad_evict = adddev->l2ad_start;
9964 	adddev->l2ad_first = B_TRUE;
9965 	adddev->l2ad_writing = B_FALSE;
9966 	adddev->l2ad_trim_all = B_FALSE;
9967 	list_link_init(&adddev->l2ad_node);
9968 	adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
9969 
9970 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
9971 	/*
9972 	 * This is a list of all ARC buffers that are still valid on the
9973 	 * device.
9974 	 */
9975 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
9976 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
9977 
9978 	/*
9979 	 * This is a list of pointers to log blocks that are still present
9980 	 * on the device.
9981 	 */
9982 	list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
9983 	    offsetof(l2arc_lb_ptr_buf_t, node));
9984 
9985 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
9986 	zfs_refcount_create(&adddev->l2ad_alloc);
9987 	zfs_refcount_create(&adddev->l2ad_lb_asize);
9988 	zfs_refcount_create(&adddev->l2ad_lb_count);
9989 
9990 	/*
9991 	 * Decide if dev is eligible for L2ARC rebuild or whole device
9992 	 * trimming. This has to happen before the device is added in the
9993 	 * cache device list and l2arc_dev_mtx is released. Otherwise
9994 	 * l2arc_feed_thread() might already start writing on the
9995 	 * device.
9996 	 */
9997 	l2arc_rebuild_dev(adddev, B_FALSE);
9998 
9999 	/*
10000 	 * Add device to global list
10001 	 */
10002 	mutex_enter(&l2arc_dev_mtx);
10003 	list_insert_head(l2arc_dev_list, adddev);
10004 	atomic_inc_64(&l2arc_ndev);
10005 	mutex_exit(&l2arc_dev_mtx);
10006 }
10007 
10008 /*
10009  * Decide if a vdev is eligible for L2ARC rebuild, called from vdev_reopen()
10010  * in case of onlining a cache device.
10011  */
10012 void
10013 l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
10014 {
10015 	l2arc_dev_t		*dev = NULL;
10016 
10017 	dev = l2arc_vdev_get(vd);
10018 	ASSERT3P(dev, !=, NULL);
10019 
10020 	/*
10021 	 * In contrast to l2arc_add_vdev() we do not have to worry about
10022 	 * l2arc_feed_thread() invalidating previous content when onlining a
10023 	 * cache device. The device parameters (l2ad*) are not cleared when
10024 	 * offlining the device and writing new buffers will not invalidate
10025 	 * all previous content. In worst case only buffers that have not had
10026 	 * their log block written to the device will be lost.
10027 	 * When onlining the cache device (ie offline->online without exporting
10028 	 * the pool in between) this happens:
10029 	 * vdev_reopen() -> vdev_open() -> l2arc_rebuild_vdev()
10030 	 * 			|			|
10031 	 * 		vdev_is_dead() = B_FALSE	l2ad_rebuild = B_TRUE
10032 	 * During the time where vdev_is_dead = B_FALSE and until l2ad_rebuild
10033 	 * is set to B_TRUE we might write additional buffers to the device.
10034 	 */
10035 	l2arc_rebuild_dev(dev, reopen);
10036 }
10037 
10038 /*
10039  * Remove a vdev from the L2ARC.
10040  */
10041 void
10042 l2arc_remove_vdev(vdev_t *vd)
10043 {
10044 	l2arc_dev_t *remdev = NULL;
10045 
10046 	/*
10047 	 * Find the device by vdev
10048 	 */
10049 	remdev = l2arc_vdev_get(vd);
10050 	ASSERT3P(remdev, !=, NULL);
10051 
10052 	/*
10053 	 * Cancel any ongoing or scheduled rebuild.
10054 	 */
10055 	mutex_enter(&l2arc_rebuild_thr_lock);
10056 	if (remdev->l2ad_rebuild_began == B_TRUE) {
10057 		remdev->l2ad_rebuild_cancel = B_TRUE;
10058 		while (remdev->l2ad_rebuild == B_TRUE)
10059 			cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
10060 	}
10061 	mutex_exit(&l2arc_rebuild_thr_lock);
10062 
10063 	/*
10064 	 * Remove device from global list
10065 	 */
10066 	mutex_enter(&l2arc_dev_mtx);
10067 	list_remove(l2arc_dev_list, remdev);
10068 	l2arc_dev_last = NULL;		/* may have been invalidated */
10069 	atomic_dec_64(&l2arc_ndev);
10070 	mutex_exit(&l2arc_dev_mtx);
10071 
10072 	/*
10073 	 * Clear all buflists and ARC references.  L2ARC device flush.
10074 	 */
10075 	l2arc_evict(remdev, 0, B_TRUE);
10076 	list_destroy(&remdev->l2ad_buflist);
10077 	ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
10078 	list_destroy(&remdev->l2ad_lbptr_list);
10079 	mutex_destroy(&remdev->l2ad_mtx);
10080 	zfs_refcount_destroy(&remdev->l2ad_alloc);
10081 	zfs_refcount_destroy(&remdev->l2ad_lb_asize);
10082 	zfs_refcount_destroy(&remdev->l2ad_lb_count);
10083 	kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
10084 	vmem_free(remdev, sizeof (l2arc_dev_t));
10085 }
10086 
10087 void
10088 l2arc_init(void)
10089 {
10090 	l2arc_thread_exit = 0;
10091 	l2arc_ndev = 0;
10092 
10093 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
10094 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
10095 	mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
10096 	cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
10097 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
10098 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
10099 
10100 	l2arc_dev_list = &L2ARC_dev_list;
10101 	l2arc_free_on_write = &L2ARC_free_on_write;
10102 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
10103 	    offsetof(l2arc_dev_t, l2ad_node));
10104 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
10105 	    offsetof(l2arc_data_free_t, l2df_list_node));
10106 }
10107 
10108 void
10109 l2arc_fini(void)
10110 {
10111 	mutex_destroy(&l2arc_feed_thr_lock);
10112 	cv_destroy(&l2arc_feed_thr_cv);
10113 	mutex_destroy(&l2arc_rebuild_thr_lock);
10114 	cv_destroy(&l2arc_rebuild_thr_cv);
10115 	mutex_destroy(&l2arc_dev_mtx);
10116 	mutex_destroy(&l2arc_free_on_write_mtx);
10117 
10118 	list_destroy(l2arc_dev_list);
10119 	list_destroy(l2arc_free_on_write);
10120 }
10121 
10122 void
10123 l2arc_start(void)
10124 {
10125 	if (!(spa_mode_global & SPA_MODE_WRITE))
10126 		return;
10127 
10128 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
10129 	    TS_RUN, defclsyspri);
10130 }
10131 
10132 void
10133 l2arc_stop(void)
10134 {
10135 	if (!(spa_mode_global & SPA_MODE_WRITE))
10136 		return;
10137 
10138 	mutex_enter(&l2arc_feed_thr_lock);
10139 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
10140 	l2arc_thread_exit = 1;
10141 	while (l2arc_thread_exit != 0)
10142 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
10143 	mutex_exit(&l2arc_feed_thr_lock);
10144 }
10145 
10146 /*
10147  * Punches out rebuild threads for the L2ARC devices in a spa. This should
10148  * be called after pool import from the spa async thread, since starting
10149  * these threads directly from spa_import() will make them part of the
10150  * "zpool import" context and delay process exit (and thus pool import).
10151  */
10152 void
10153 l2arc_spa_rebuild_start(spa_t *spa)
10154 {
10155 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
10156 
10157 	/*
10158 	 * Locate the spa's l2arc devices and kick off rebuild threads.
10159 	 */
10160 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
10161 		l2arc_dev_t *dev =
10162 		    l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
10163 		if (dev == NULL) {
10164 			/* Don't attempt a rebuild if the vdev is UNAVAIL */
10165 			continue;
10166 		}
10167 		mutex_enter(&l2arc_rebuild_thr_lock);
10168 		if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
10169 			dev->l2ad_rebuild_began = B_TRUE;
10170 			(void) thread_create(NULL, 0, l2arc_dev_rebuild_thread,
10171 			    dev, 0, &p0, TS_RUN, minclsyspri);
10172 		}
10173 		mutex_exit(&l2arc_rebuild_thr_lock);
10174 	}
10175 }
10176 
10177 /*
10178  * Main entry point for L2ARC rebuilding.
10179  */
10180 static __attribute__((noreturn)) void
10181 l2arc_dev_rebuild_thread(void *arg)
10182 {
10183 	l2arc_dev_t *dev = arg;
10184 
10185 	VERIFY(!dev->l2ad_rebuild_cancel);
10186 	VERIFY(dev->l2ad_rebuild);
10187 	(void) l2arc_rebuild(dev);
10188 	mutex_enter(&l2arc_rebuild_thr_lock);
10189 	dev->l2ad_rebuild_began = B_FALSE;
10190 	dev->l2ad_rebuild = B_FALSE;
10191 	mutex_exit(&l2arc_rebuild_thr_lock);
10192 
10193 	thread_exit();
10194 }
10195 
10196 /*
10197  * This function implements the actual L2ARC metadata rebuild. It:
10198  * starts reading the log block chain and restores each block's contents
10199  * to memory (reconstructing arc_buf_hdr_t's).
10200  *
10201  * Operation stops under any of the following conditions:
10202  *
10203  * 1) We reach the end of the log block chain.
10204  * 2) We encounter *any* error condition (cksum errors, io errors)
10205  */
10206 static int
10207 l2arc_rebuild(l2arc_dev_t *dev)
10208 {
10209 	vdev_t			*vd = dev->l2ad_vdev;
10210 	spa_t			*spa = vd->vdev_spa;
10211 	int			err = 0;
10212 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10213 	l2arc_log_blk_phys_t	*this_lb, *next_lb;
10214 	zio_t			*this_io = NULL, *next_io = NULL;
10215 	l2arc_log_blkptr_t	lbps[2];
10216 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
10217 	boolean_t		lock_held;
10218 
10219 	this_lb = vmem_zalloc(sizeof (*this_lb), KM_SLEEP);
10220 	next_lb = vmem_zalloc(sizeof (*next_lb), KM_SLEEP);
10221 
10222 	/*
10223 	 * We prevent device removal while issuing reads to the device,
10224 	 * then during the rebuilding phases we drop this lock again so
10225 	 * that a spa_unload or device remove can be initiated - this is
10226 	 * safe, because the spa will signal us to stop before removing
10227 	 * our device and wait for us to stop.
10228 	 */
10229 	spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
10230 	lock_held = B_TRUE;
10231 
10232 	/*
10233 	 * Retrieve the persistent L2ARC device state.
10234 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10235 	 */
10236 	dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
10237 	dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
10238 	    L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
10239 	    dev->l2ad_start);
10240 	dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
10241 
10242 	vd->vdev_trim_action_time = l2dhdr->dh_trim_action_time;
10243 	vd->vdev_trim_state = l2dhdr->dh_trim_state;
10244 
10245 	/*
10246 	 * In case the zfs module parameter l2arc_rebuild_enabled is false
10247 	 * we do not start the rebuild process.
10248 	 */
10249 	if (!l2arc_rebuild_enabled)
10250 		goto out;
10251 
10252 	/* Prepare the rebuild process */
10253 	memcpy(lbps, l2dhdr->dh_start_lbps, sizeof (lbps));
10254 
10255 	/* Start the rebuild process */
10256 	for (;;) {
10257 		if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
10258 			break;
10259 
10260 		if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
10261 		    this_lb, next_lb, this_io, &next_io)) != 0)
10262 			goto out;
10263 
10264 		/*
10265 		 * Our memory pressure valve. If the system is running low
10266 		 * on memory, rather than swamping memory with new ARC buf
10267 		 * hdrs, we opt not to rebuild the L2ARC. At this point,
10268 		 * however, we have already set up our L2ARC dev to chain in
10269 		 * new metadata log blocks, so the user may choose to offline/
10270 		 * online the L2ARC dev at a later time (or re-import the pool)
10271 		 * to reconstruct it (when there's less memory pressure).
10272 		 */
10273 		if (l2arc_hdr_limit_reached()) {
10274 			ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
10275 			cmn_err(CE_NOTE, "System running low on memory, "
10276 			    "aborting L2ARC rebuild.");
10277 			err = SET_ERROR(ENOMEM);
10278 			goto out;
10279 		}
10280 
10281 		spa_config_exit(spa, SCL_L2ARC, vd);
10282 		lock_held = B_FALSE;
10283 
10284 		/*
10285 		 * Now that we know that the next_lb checks out alright, we
10286 		 * can start reconstruction from this log block.
10287 		 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10288 		 */
10289 		uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
10290 		l2arc_log_blk_restore(dev, this_lb, asize);
10291 
10292 		/*
10293 		 * log block restored, include its pointer in the list of
10294 		 * pointers to log blocks present in the L2ARC device.
10295 		 */
10296 		lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10297 		lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
10298 		    KM_SLEEP);
10299 		memcpy(lb_ptr_buf->lb_ptr, &lbps[0],
10300 		    sizeof (l2arc_log_blkptr_t));
10301 		mutex_enter(&dev->l2ad_mtx);
10302 		list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
10303 		ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10304 		ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10305 		zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10306 		zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
10307 		mutex_exit(&dev->l2ad_mtx);
10308 		vdev_space_update(vd, asize, 0, 0);
10309 
10310 		/*
10311 		 * Protection against loops of log blocks:
10312 		 *
10313 		 *				       l2ad_hand  l2ad_evict
10314 		 *                                         V	      V
10315 		 * l2ad_start |=======================================| l2ad_end
10316 		 *             -----|||----|||---|||----|||
10317 		 *                  (3)    (2)   (1)    (0)
10318 		 *             ---|||---|||----|||---|||
10319 		 *		  (7)   (6)    (5)   (4)
10320 		 *
10321 		 * In this situation the pointer of log block (4) passes
10322 		 * l2arc_log_blkptr_valid() but the log block should not be
10323 		 * restored as it is overwritten by the payload of log block
10324 		 * (0). Only log blocks (0)-(3) should be restored. We check
10325 		 * whether l2ad_evict lies in between the payload starting
10326 		 * offset of the next log block (lbps[1].lbp_payload_start)
10327 		 * and the payload starting offset of the present log block
10328 		 * (lbps[0].lbp_payload_start). If true and this isn't the
10329 		 * first pass, we are looping from the beginning and we should
10330 		 * stop.
10331 		 */
10332 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
10333 		    lbps[0].lbp_payload_start, dev->l2ad_evict) &&
10334 		    !dev->l2ad_first)
10335 			goto out;
10336 
10337 		cond_resched();
10338 		for (;;) {
10339 			mutex_enter(&l2arc_rebuild_thr_lock);
10340 			if (dev->l2ad_rebuild_cancel) {
10341 				dev->l2ad_rebuild = B_FALSE;
10342 				cv_signal(&l2arc_rebuild_thr_cv);
10343 				mutex_exit(&l2arc_rebuild_thr_lock);
10344 				err = SET_ERROR(ECANCELED);
10345 				goto out;
10346 			}
10347 			mutex_exit(&l2arc_rebuild_thr_lock);
10348 			if (spa_config_tryenter(spa, SCL_L2ARC, vd,
10349 			    RW_READER)) {
10350 				lock_held = B_TRUE;
10351 				break;
10352 			}
10353 			/*
10354 			 * L2ARC config lock held by somebody in writer,
10355 			 * possibly due to them trying to remove us. They'll
10356 			 * likely to want us to shut down, so after a little
10357 			 * delay, we check l2ad_rebuild_cancel and retry
10358 			 * the lock again.
10359 			 */
10360 			delay(1);
10361 		}
10362 
10363 		/*
10364 		 * Continue with the next log block.
10365 		 */
10366 		lbps[0] = lbps[1];
10367 		lbps[1] = this_lb->lb_prev_lbp;
10368 		PTR_SWAP(this_lb, next_lb);
10369 		this_io = next_io;
10370 		next_io = NULL;
10371 	}
10372 
10373 	if (this_io != NULL)
10374 		l2arc_log_blk_fetch_abort(this_io);
10375 out:
10376 	if (next_io != NULL)
10377 		l2arc_log_blk_fetch_abort(next_io);
10378 	vmem_free(this_lb, sizeof (*this_lb));
10379 	vmem_free(next_lb, sizeof (*next_lb));
10380 
10381 	if (!l2arc_rebuild_enabled) {
10382 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10383 		    "disabled");
10384 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
10385 		ARCSTAT_BUMP(arcstat_l2_rebuild_success);
10386 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10387 		    "successful, restored %llu blocks",
10388 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
10389 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
10390 		/*
10391 		 * No error but also nothing restored, meaning the lbps array
10392 		 * in the device header points to invalid/non-present log
10393 		 * blocks. Reset the header.
10394 		 */
10395 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10396 		    "no valid log blocks");
10397 		memset(l2dhdr, 0, dev->l2ad_dev_hdr_asize);
10398 		l2arc_dev_hdr_update(dev);
10399 	} else if (err == ECANCELED) {
10400 		/*
10401 		 * In case the rebuild was canceled do not log to spa history
10402 		 * log as the pool may be in the process of being removed.
10403 		 */
10404 		zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
10405 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
10406 	} else if (err != 0) {
10407 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
10408 		    "aborted, restored %llu blocks",
10409 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
10410 	}
10411 
10412 	if (lock_held)
10413 		spa_config_exit(spa, SCL_L2ARC, vd);
10414 
10415 	return (err);
10416 }
10417 
10418 /*
10419  * Attempts to read the device header on the provided L2ARC device and writes
10420  * it to `hdr'. On success, this function returns 0, otherwise the appropriate
10421  * error code is returned.
10422  */
10423 static int
10424 l2arc_dev_hdr_read(l2arc_dev_t *dev)
10425 {
10426 	int			err;
10427 	uint64_t		guid;
10428 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10429 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10430 	abd_t 			*abd;
10431 
10432 	guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10433 
10434 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10435 
10436 	err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
10437 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
10438 	    ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
10439 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10440 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
10441 	    ZIO_FLAG_SPECULATIVE, B_FALSE));
10442 
10443 	abd_free(abd);
10444 
10445 	if (err != 0) {
10446 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
10447 		zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
10448 		    "vdev guid: %llu", err,
10449 		    (u_longlong_t)dev->l2ad_vdev->vdev_guid);
10450 		return (err);
10451 	}
10452 
10453 	if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
10454 		byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
10455 
10456 	if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
10457 	    l2dhdr->dh_spa_guid != guid ||
10458 	    l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
10459 	    l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
10460 	    l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
10461 	    l2dhdr->dh_end != dev->l2ad_end ||
10462 	    !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
10463 	    l2dhdr->dh_evict) ||
10464 	    (l2dhdr->dh_trim_state != VDEV_TRIM_COMPLETE &&
10465 	    l2arc_trim_ahead > 0)) {
10466 		/*
10467 		 * Attempt to rebuild a device containing no actual dev hdr
10468 		 * or containing a header from some other pool or from another
10469 		 * version of persistent L2ARC.
10470 		 */
10471 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
10472 		return (SET_ERROR(ENOTSUP));
10473 	}
10474 
10475 	return (0);
10476 }
10477 
10478 /*
10479  * Reads L2ARC log blocks from storage and validates their contents.
10480  *
10481  * This function implements a simple fetcher to make sure that while
10482  * we're processing one buffer the L2ARC is already fetching the next
10483  * one in the chain.
10484  *
10485  * The arguments this_lp and next_lp point to the current and next log block
10486  * address in the block chain. Similarly, this_lb and next_lb hold the
10487  * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
10488  *
10489  * The `this_io' and `next_io' arguments are used for block fetching.
10490  * When issuing the first blk IO during rebuild, you should pass NULL for
10491  * `this_io'. This function will then issue a sync IO to read the block and
10492  * also issue an async IO to fetch the next block in the block chain. The
10493  * fetched IO is returned in `next_io'. On subsequent calls to this
10494  * function, pass the value returned in `next_io' from the previous call
10495  * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
10496  * Prior to the call, you should initialize your `next_io' pointer to be
10497  * NULL. If no fetch IO was issued, the pointer is left set at NULL.
10498  *
10499  * On success, this function returns 0, otherwise it returns an appropriate
10500  * error code. On error the fetching IO is aborted and cleared before
10501  * returning from this function. Therefore, if we return `success', the
10502  * caller can assume that we have taken care of cleanup of fetch IOs.
10503  */
10504 static int
10505 l2arc_log_blk_read(l2arc_dev_t *dev,
10506     const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
10507     l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
10508     zio_t *this_io, zio_t **next_io)
10509 {
10510 	int		err = 0;
10511 	zio_cksum_t	cksum;
10512 	abd_t		*abd = NULL;
10513 	uint64_t	asize;
10514 
10515 	ASSERT(this_lbp != NULL && next_lbp != NULL);
10516 	ASSERT(this_lb != NULL && next_lb != NULL);
10517 	ASSERT(next_io != NULL && *next_io == NULL);
10518 	ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
10519 
10520 	/*
10521 	 * Check to see if we have issued the IO for this log block in a
10522 	 * previous run. If not, this is the first call, so issue it now.
10523 	 */
10524 	if (this_io == NULL) {
10525 		this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
10526 		    this_lb);
10527 	}
10528 
10529 	/*
10530 	 * Peek to see if we can start issuing the next IO immediately.
10531 	 */
10532 	if (l2arc_log_blkptr_valid(dev, next_lbp)) {
10533 		/*
10534 		 * Start issuing IO for the next log block early - this
10535 		 * should help keep the L2ARC device busy while we
10536 		 * decompress and restore this log block.
10537 		 */
10538 		*next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
10539 		    next_lb);
10540 	}
10541 
10542 	/* Wait for the IO to read this log block to complete */
10543 	if ((err = zio_wait(this_io)) != 0) {
10544 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
10545 		zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
10546 		    "offset: %llu, vdev guid: %llu", err,
10547 		    (u_longlong_t)this_lbp->lbp_daddr,
10548 		    (u_longlong_t)dev->l2ad_vdev->vdev_guid);
10549 		goto cleanup;
10550 	}
10551 
10552 	/*
10553 	 * Make sure the buffer checks out.
10554 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10555 	 */
10556 	asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
10557 	fletcher_4_native(this_lb, asize, NULL, &cksum);
10558 	if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
10559 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
10560 		zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
10561 		    "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
10562 		    (u_longlong_t)this_lbp->lbp_daddr,
10563 		    (u_longlong_t)dev->l2ad_vdev->vdev_guid,
10564 		    (u_longlong_t)dev->l2ad_hand,
10565 		    (u_longlong_t)dev->l2ad_evict);
10566 		err = SET_ERROR(ECKSUM);
10567 		goto cleanup;
10568 	}
10569 
10570 	/* Now we can take our time decoding this buffer */
10571 	switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
10572 	case ZIO_COMPRESS_OFF:
10573 		break;
10574 	case ZIO_COMPRESS_LZ4:
10575 		abd = abd_alloc_for_io(asize, B_TRUE);
10576 		abd_copy_from_buf_off(abd, this_lb, 0, asize);
10577 		if ((err = zio_decompress_data(
10578 		    L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
10579 		    abd, this_lb, asize, sizeof (*this_lb), NULL)) != 0) {
10580 			err = SET_ERROR(EINVAL);
10581 			goto cleanup;
10582 		}
10583 		break;
10584 	default:
10585 		err = SET_ERROR(EINVAL);
10586 		goto cleanup;
10587 	}
10588 	if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
10589 		byteswap_uint64_array(this_lb, sizeof (*this_lb));
10590 	if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
10591 		err = SET_ERROR(EINVAL);
10592 		goto cleanup;
10593 	}
10594 cleanup:
10595 	/* Abort an in-flight fetch I/O in case of error */
10596 	if (err != 0 && *next_io != NULL) {
10597 		l2arc_log_blk_fetch_abort(*next_io);
10598 		*next_io = NULL;
10599 	}
10600 	if (abd != NULL)
10601 		abd_free(abd);
10602 	return (err);
10603 }
10604 
10605 /*
10606  * Restores the payload of a log block to ARC. This creates empty ARC hdr
10607  * entries which only contain an l2arc hdr, essentially restoring the
10608  * buffers to their L2ARC evicted state. This function also updates space
10609  * usage on the L2ARC vdev to make sure it tracks restored buffers.
10610  */
10611 static void
10612 l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
10613     uint64_t lb_asize)
10614 {
10615 	uint64_t	size = 0, asize = 0;
10616 	uint64_t	log_entries = dev->l2ad_log_entries;
10617 
10618 	/*
10619 	 * Usually arc_adapt() is called only for data, not headers, but
10620 	 * since we may allocate significant amount of memory here, let ARC
10621 	 * grow its arc_c.
10622 	 */
10623 	arc_adapt(log_entries * HDR_L2ONLY_SIZE, arc_l2c_only);
10624 
10625 	for (int i = log_entries - 1; i >= 0; i--) {
10626 		/*
10627 		 * Restore goes in the reverse temporal direction to preserve
10628 		 * correct temporal ordering of buffers in the l2ad_buflist.
10629 		 * l2arc_hdr_restore also does a list_insert_tail instead of
10630 		 * list_insert_head on the l2ad_buflist:
10631 		 *
10632 		 *		LIST	l2ad_buflist		LIST
10633 		 *		HEAD  <------ (time) ------	TAIL
10634 		 * direction	+-----+-----+-----+-----+-----+    direction
10635 		 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
10636 		 * fill		+-----+-----+-----+-----+-----+
10637 		 *		^				^
10638 		 *		|				|
10639 		 *		|				|
10640 		 *	l2arc_feed_thread		l2arc_rebuild
10641 		 *	will place new bufs here	restores bufs here
10642 		 *
10643 		 * During l2arc_rebuild() the device is not used by
10644 		 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
10645 		 */
10646 		size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
10647 		asize += vdev_psize_to_asize(dev->l2ad_vdev,
10648 		    L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
10649 		l2arc_hdr_restore(&lb->lb_entries[i], dev);
10650 	}
10651 
10652 	/*
10653 	 * Record rebuild stats:
10654 	 *	size		Logical size of restored buffers in the L2ARC
10655 	 *	asize		Aligned size of restored buffers in the L2ARC
10656 	 */
10657 	ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
10658 	ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
10659 	ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
10660 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
10661 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
10662 	ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
10663 }
10664 
10665 /*
10666  * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
10667  * into a state indicating that it has been evicted to L2ARC.
10668  */
10669 static void
10670 l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
10671 {
10672 	arc_buf_hdr_t		*hdr, *exists;
10673 	kmutex_t		*hash_lock;
10674 	arc_buf_contents_t	type = L2BLK_GET_TYPE((le)->le_prop);
10675 	uint64_t		asize;
10676 
10677 	/*
10678 	 * Do all the allocation before grabbing any locks, this lets us
10679 	 * sleep if memory is full and we don't have to deal with failed
10680 	 * allocations.
10681 	 */
10682 	hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
10683 	    dev, le->le_dva, le->le_daddr,
10684 	    L2BLK_GET_PSIZE((le)->le_prop), le->le_birth,
10685 	    L2BLK_GET_COMPRESS((le)->le_prop), le->le_complevel,
10686 	    L2BLK_GET_PROTECTED((le)->le_prop),
10687 	    L2BLK_GET_PREFETCH((le)->le_prop),
10688 	    L2BLK_GET_STATE((le)->le_prop));
10689 	asize = vdev_psize_to_asize(dev->l2ad_vdev,
10690 	    L2BLK_GET_PSIZE((le)->le_prop));
10691 
10692 	/*
10693 	 * vdev_space_update() has to be called before arc_hdr_destroy() to
10694 	 * avoid underflow since the latter also calls vdev_space_update().
10695 	 */
10696 	l2arc_hdr_arcstats_increment(hdr);
10697 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10698 
10699 	mutex_enter(&dev->l2ad_mtx);
10700 	list_insert_tail(&dev->l2ad_buflist, hdr);
10701 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
10702 	mutex_exit(&dev->l2ad_mtx);
10703 
10704 	exists = buf_hash_insert(hdr, &hash_lock);
10705 	if (exists) {
10706 		/* Buffer was already cached, no need to restore it. */
10707 		arc_hdr_destroy(hdr);
10708 		/*
10709 		 * If the buffer is already cached, check whether it has
10710 		 * L2ARC metadata. If not, enter them and update the flag.
10711 		 * This is important is case of onlining a cache device, since
10712 		 * we previously evicted all L2ARC metadata from ARC.
10713 		 */
10714 		if (!HDR_HAS_L2HDR(exists)) {
10715 			arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
10716 			exists->b_l2hdr.b_dev = dev;
10717 			exists->b_l2hdr.b_daddr = le->le_daddr;
10718 			exists->b_l2hdr.b_arcs_state =
10719 			    L2BLK_GET_STATE((le)->le_prop);
10720 			mutex_enter(&dev->l2ad_mtx);
10721 			list_insert_tail(&dev->l2ad_buflist, exists);
10722 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
10723 			    arc_hdr_size(exists), exists);
10724 			mutex_exit(&dev->l2ad_mtx);
10725 			l2arc_hdr_arcstats_increment(exists);
10726 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10727 		}
10728 		ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
10729 	}
10730 
10731 	mutex_exit(hash_lock);
10732 }
10733 
10734 /*
10735  * Starts an asynchronous read IO to read a log block. This is used in log
10736  * block reconstruction to start reading the next block before we are done
10737  * decoding and reconstructing the current block, to keep the l2arc device
10738  * nice and hot with read IO to process.
10739  * The returned zio will contain a newly allocated memory buffers for the IO
10740  * data which should then be freed by the caller once the zio is no longer
10741  * needed (i.e. due to it having completed). If you wish to abort this
10742  * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
10743  * care of disposing of the allocated buffers correctly.
10744  */
10745 static zio_t *
10746 l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
10747     l2arc_log_blk_phys_t *lb)
10748 {
10749 	uint32_t		asize;
10750 	zio_t			*pio;
10751 	l2arc_read_callback_t	*cb;
10752 
10753 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
10754 	asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10755 	ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
10756 
10757 	cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
10758 	cb->l2rcb_abd = abd_get_from_buf(lb, asize);
10759 	pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
10760 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
10761 	    ZIO_FLAG_DONT_RETRY);
10762 	(void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
10763 	    cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10764 	    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10765 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
10766 
10767 	return (pio);
10768 }
10769 
10770 /*
10771  * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
10772  * buffers allocated for it.
10773  */
10774 static void
10775 l2arc_log_blk_fetch_abort(zio_t *zio)
10776 {
10777 	(void) zio_wait(zio);
10778 }
10779 
10780 /*
10781  * Creates a zio to update the device header on an l2arc device.
10782  */
10783 void
10784 l2arc_dev_hdr_update(l2arc_dev_t *dev)
10785 {
10786 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10787 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10788 	abd_t			*abd;
10789 	int			err;
10790 
10791 	VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
10792 
10793 	l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
10794 	l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
10795 	l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10796 	l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
10797 	l2dhdr->dh_log_entries = dev->l2ad_log_entries;
10798 	l2dhdr->dh_evict = dev->l2ad_evict;
10799 	l2dhdr->dh_start = dev->l2ad_start;
10800 	l2dhdr->dh_end = dev->l2ad_end;
10801 	l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
10802 	l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
10803 	l2dhdr->dh_flags = 0;
10804 	l2dhdr->dh_trim_action_time = dev->l2ad_vdev->vdev_trim_action_time;
10805 	l2dhdr->dh_trim_state = dev->l2ad_vdev->vdev_trim_state;
10806 	if (dev->l2ad_first)
10807 		l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
10808 
10809 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10810 
10811 	err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
10812 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
10813 	    NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
10814 
10815 	abd_free(abd);
10816 
10817 	if (err != 0) {
10818 		zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
10819 		    "vdev guid: %llu", err,
10820 		    (u_longlong_t)dev->l2ad_vdev->vdev_guid);
10821 	}
10822 }
10823 
10824 /*
10825  * Commits a log block to the L2ARC device. This routine is invoked from
10826  * l2arc_write_buffers when the log block fills up.
10827  * This function allocates some memory to temporarily hold the serialized
10828  * buffer to be written. This is then released in l2arc_write_done.
10829  */
10830 static void
10831 l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
10832 {
10833 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
10834 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10835 	uint64_t		psize, asize;
10836 	zio_t			*wzio;
10837 	l2arc_lb_abd_buf_t	*abd_buf;
10838 	uint8_t			*tmpbuf;
10839 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
10840 
10841 	VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
10842 
10843 	tmpbuf = zio_buf_alloc(sizeof (*lb));
10844 	abd_buf = zio_buf_alloc(sizeof (*abd_buf));
10845 	abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
10846 	lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10847 	lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
10848 
10849 	/* link the buffer into the block chain */
10850 	lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
10851 	lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
10852 
10853 	/*
10854 	 * l2arc_log_blk_commit() may be called multiple times during a single
10855 	 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
10856 	 * so we can free them in l2arc_write_done() later on.
10857 	 */
10858 	list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
10859 
10860 	/* try to compress the buffer */
10861 	psize = zio_compress_data(ZIO_COMPRESS_LZ4,
10862 	    abd_buf->abd, tmpbuf, sizeof (*lb), 0);
10863 
10864 	/* a log block is never entirely zero */
10865 	ASSERT(psize != 0);
10866 	asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
10867 	ASSERT(asize <= sizeof (*lb));
10868 
10869 	/*
10870 	 * Update the start log block pointer in the device header to point
10871 	 * to the log block we're about to write.
10872 	 */
10873 	l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
10874 	l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
10875 	l2dhdr->dh_start_lbps[0].lbp_payload_asize =
10876 	    dev->l2ad_log_blk_payload_asize;
10877 	l2dhdr->dh_start_lbps[0].lbp_payload_start =
10878 	    dev->l2ad_log_blk_payload_start;
10879 	L2BLK_SET_LSIZE(
10880 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
10881 	L2BLK_SET_PSIZE(
10882 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
10883 	L2BLK_SET_CHECKSUM(
10884 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10885 	    ZIO_CHECKSUM_FLETCHER_4);
10886 	if (asize < sizeof (*lb)) {
10887 		/* compression succeeded */
10888 		memset(tmpbuf + psize, 0, asize - psize);
10889 		L2BLK_SET_COMPRESS(
10890 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10891 		    ZIO_COMPRESS_LZ4);
10892 	} else {
10893 		/* compression failed */
10894 		memcpy(tmpbuf, lb, sizeof (*lb));
10895 		L2BLK_SET_COMPRESS(
10896 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10897 		    ZIO_COMPRESS_OFF);
10898 	}
10899 
10900 	/* checksum what we're about to write */
10901 	fletcher_4_native(tmpbuf, asize, NULL,
10902 	    &l2dhdr->dh_start_lbps[0].lbp_cksum);
10903 
10904 	abd_free(abd_buf->abd);
10905 
10906 	/* perform the write itself */
10907 	abd_buf->abd = abd_get_from_buf(tmpbuf, sizeof (*lb));
10908 	abd_take_ownership_of_buf(abd_buf->abd, B_TRUE);
10909 	wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
10910 	    asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10911 	    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
10912 	DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
10913 	(void) zio_nowait(wzio);
10914 
10915 	dev->l2ad_hand += asize;
10916 	/*
10917 	 * Include the committed log block's pointer  in the list of pointers
10918 	 * to log blocks present in the L2ARC device.
10919 	 */
10920 	memcpy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[0],
10921 	    sizeof (l2arc_log_blkptr_t));
10922 	mutex_enter(&dev->l2ad_mtx);
10923 	list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
10924 	ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10925 	ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10926 	zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10927 	zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
10928 	mutex_exit(&dev->l2ad_mtx);
10929 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10930 
10931 	/* bump the kstats */
10932 	ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
10933 	ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
10934 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
10935 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
10936 	    dev->l2ad_log_blk_payload_asize / asize);
10937 
10938 	/* start a new log block */
10939 	dev->l2ad_log_ent_idx = 0;
10940 	dev->l2ad_log_blk_payload_asize = 0;
10941 	dev->l2ad_log_blk_payload_start = 0;
10942 }
10943 
10944 /*
10945  * Validates an L2ARC log block address to make sure that it can be read
10946  * from the provided L2ARC device.
10947  */
10948 boolean_t
10949 l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
10950 {
10951 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
10952 	uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10953 	uint64_t end = lbp->lbp_daddr + asize - 1;
10954 	uint64_t start = lbp->lbp_payload_start;
10955 	boolean_t evicted = B_FALSE;
10956 
10957 	/*
10958 	 * A log block is valid if all of the following conditions are true:
10959 	 * - it fits entirely (including its payload) between l2ad_start and
10960 	 *   l2ad_end
10961 	 * - it has a valid size
10962 	 * - neither the log block itself nor part of its payload was evicted
10963 	 *   by l2arc_evict():
10964 	 *
10965 	 *		l2ad_hand          l2ad_evict
10966 	 *		|			 |	lbp_daddr
10967 	 *		|     start		 |	|  end
10968 	 *		|     |			 |	|  |
10969 	 *		V     V		         V	V  V
10970 	 *   l2ad_start ============================================ l2ad_end
10971 	 *                    --------------------------||||
10972 	 *				^		 ^
10973 	 *				|		log block
10974 	 *				payload
10975 	 */
10976 
10977 	evicted =
10978 	    l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
10979 	    l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
10980 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
10981 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
10982 
10983 	return (start >= dev->l2ad_start && end <= dev->l2ad_end &&
10984 	    asize > 0 && asize <= sizeof (l2arc_log_blk_phys_t) &&
10985 	    (!evicted || dev->l2ad_first));
10986 }
10987 
10988 /*
10989  * Inserts ARC buffer header `hdr' into the current L2ARC log block on
10990  * the device. The buffer being inserted must be present in L2ARC.
10991  * Returns B_TRUE if the L2ARC log block is full and needs to be committed
10992  * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
10993  */
10994 static boolean_t
10995 l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
10996 {
10997 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
10998 	l2arc_log_ent_phys_t	*le;
10999 
11000 	if (dev->l2ad_log_entries == 0)
11001 		return (B_FALSE);
11002 
11003 	int index = dev->l2ad_log_ent_idx++;
11004 
11005 	ASSERT3S(index, <, dev->l2ad_log_entries);
11006 	ASSERT(HDR_HAS_L2HDR(hdr));
11007 
11008 	le = &lb->lb_entries[index];
11009 	memset(le, 0, sizeof (*le));
11010 	le->le_dva = hdr->b_dva;
11011 	le->le_birth = hdr->b_birth;
11012 	le->le_daddr = hdr->b_l2hdr.b_daddr;
11013 	if (index == 0)
11014 		dev->l2ad_log_blk_payload_start = le->le_daddr;
11015 	L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
11016 	L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
11017 	L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
11018 	le->le_complevel = hdr->b_complevel;
11019 	L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
11020 	L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
11021 	L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
11022 	L2BLK_SET_STATE((le)->le_prop, hdr->b_l1hdr.b_state->arcs_state);
11023 
11024 	dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
11025 	    HDR_GET_PSIZE(hdr));
11026 
11027 	return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
11028 }
11029 
11030 /*
11031  * Checks whether a given L2ARC device address sits in a time-sequential
11032  * range. The trick here is that the L2ARC is a rotary buffer, so we can't
11033  * just do a range comparison, we need to handle the situation in which the
11034  * range wraps around the end of the L2ARC device. Arguments:
11035  *	bottom -- Lower end of the range to check (written to earlier).
11036  *	top    -- Upper end of the range to check (written to later).
11037  *	check  -- The address for which we want to determine if it sits in
11038  *		  between the top and bottom.
11039  *
11040  * The 3-way conditional below represents the following cases:
11041  *
11042  *	bottom < top : Sequentially ordered case:
11043  *	  <check>--------+-------------------+
11044  *	                 |  (overlap here?)  |
11045  *	 L2ARC dev       V                   V
11046  *	 |---------------<bottom>============<top>--------------|
11047  *
11048  *	bottom > top: Looped-around case:
11049  *	                      <check>--------+------------------+
11050  *	                                     |  (overlap here?) |
11051  *	 L2ARC dev                           V                  V
11052  *	 |===============<top>---------------<bottom>===========|
11053  *	 ^               ^
11054  *	 |  (or here?)   |
11055  *	 +---------------+---------<check>
11056  *
11057  *	top == bottom : Just a single address comparison.
11058  */
11059 boolean_t
11060 l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
11061 {
11062 	if (bottom < top)
11063 		return (bottom <= check && check <= top);
11064 	else if (bottom > top)
11065 		return (check <= top || bottom <= check);
11066 	else
11067 		return (check == top);
11068 }
11069 
11070 EXPORT_SYMBOL(arc_buf_size);
11071 EXPORT_SYMBOL(arc_write);
11072 EXPORT_SYMBOL(arc_read);
11073 EXPORT_SYMBOL(arc_buf_info);
11074 EXPORT_SYMBOL(arc_getbuf_func);
11075 EXPORT_SYMBOL(arc_add_prune_callback);
11076 EXPORT_SYMBOL(arc_remove_prune_callback);
11077 
11078 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min, param_set_arc_min,
11079 	param_get_long, ZMOD_RW, "Minimum ARC size in bytes");
11080 
11081 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, max, param_set_arc_max,
11082 	param_get_long, ZMOD_RW, "Maximum ARC size in bytes");
11083 
11084 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_limit, param_set_arc_long,
11085 	param_get_long, ZMOD_RW, "Metadata limit for ARC size in bytes");
11086 
11087 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_limit_percent,
11088     param_set_arc_long, param_get_long, ZMOD_RW,
11089 	"Percent of ARC size for ARC meta limit");
11090 
11091 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_min, param_set_arc_long,
11092 	param_get_long, ZMOD_RW, "Minimum ARC metadata size in bytes");
11093 
11094 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_prune, INT, ZMOD_RW,
11095 	"Meta objects to scan for prune");
11096 
11097 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_adjust_restarts, INT, ZMOD_RW,
11098 	"Limit number of restarts in arc_evict_meta");
11099 
11100 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_strategy, INT, ZMOD_RW,
11101 	"Meta reclaim strategy");
11102 
11103 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, grow_retry, param_set_arc_int,
11104 	param_get_int, ZMOD_RW, "Seconds before growing ARC size");
11105 
11106 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, p_dampener_disable, INT, ZMOD_RW,
11107 	"Disable arc_p adapt dampener");
11108 
11109 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, shrink_shift, param_set_arc_int,
11110 	param_get_int, ZMOD_RW, "log2(fraction of ARC to reclaim)");
11111 
11112 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, pc_percent, UINT, ZMOD_RW,
11113 	"Percent of pagecache to reclaim ARC to");
11114 
11115 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, p_min_shift, param_set_arc_int,
11116 	param_get_int, ZMOD_RW, "arc_c shift to calc min/max arc_p");
11117 
11118 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, average_blocksize, INT, ZMOD_RD,
11119 	"Target average block size");
11120 
11121 ZFS_MODULE_PARAM(zfs, zfs_, compressed_arc_enabled, INT, ZMOD_RW,
11122 	"Disable compressed ARC buffers");
11123 
11124 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prefetch_ms, param_set_arc_int,
11125 	param_get_int, ZMOD_RW, "Min life of prefetch block in ms");
11126 
11127 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prescient_prefetch_ms,
11128     param_set_arc_int, param_get_int, ZMOD_RW,
11129 	"Min life of prescient prefetched block in ms");
11130 
11131 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_max, ULONG, ZMOD_RW,
11132 	"Max write bytes per interval");
11133 
11134 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_boost, ULONG, ZMOD_RW,
11135 	"Extra write bytes during device warmup");
11136 
11137 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom, ULONG, ZMOD_RW,
11138 	"Number of max device writes to precache");
11139 
11140 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom_boost, ULONG, ZMOD_RW,
11141 	"Compressed l2arc_headroom multiplier");
11142 
11143 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, trim_ahead, ULONG, ZMOD_RW,
11144 	"TRIM ahead L2ARC write size multiplier");
11145 
11146 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_secs, ULONG, ZMOD_RW,
11147 	"Seconds between L2ARC writing");
11148 
11149 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_min_ms, ULONG, ZMOD_RW,
11150 	"Min feed interval in milliseconds");
11151 
11152 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, noprefetch, INT, ZMOD_RW,
11153 	"Skip caching prefetched buffers");
11154 
11155 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_again, INT, ZMOD_RW,
11156 	"Turbo L2ARC warmup");
11157 
11158 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, norw, INT, ZMOD_RW,
11159 	"No reads during writes");
11160 
11161 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, meta_percent, INT, ZMOD_RW,
11162 	"Percent of ARC size allowed for L2ARC-only headers");
11163 
11164 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_enabled, INT, ZMOD_RW,
11165 	"Rebuild the L2ARC when importing a pool");
11166 
11167 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_blocks_min_l2size, ULONG, ZMOD_RW,
11168 	"Min size in bytes to write rebuild log blocks in L2ARC");
11169 
11170 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, mfuonly, INT, ZMOD_RW,
11171 	"Cache only MFU data from ARC into L2ARC");
11172 
11173 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, exclude_special, INT, ZMOD_RW,
11174 	"Exclude dbufs on special vdevs from being cached to L2ARC if set.");
11175 
11176 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, lotsfree_percent, param_set_arc_int,
11177 	param_get_int, ZMOD_RW, "System free memory I/O throttle in bytes");
11178 
11179 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, sys_free, param_set_arc_long,
11180 	param_get_long, ZMOD_RW, "System free memory target size in bytes");
11181 
11182 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit, param_set_arc_long,
11183 	param_get_long, ZMOD_RW, "Minimum bytes of dnodes in ARC");
11184 
11185 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit_percent,
11186     param_set_arc_long, param_get_long, ZMOD_RW,
11187 	"Percent of ARC meta buffers for dnodes");
11188 
11189 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, dnode_reduce_percent, ULONG, ZMOD_RW,
11190 	"Percentage of excess dnodes to try to unpin");
11191 
11192 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, eviction_pct, INT, ZMOD_RW,
11193 	"When full, ARC allocation waits for eviction of this % of alloc size");
11194 
11195 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, evict_batch_limit, INT, ZMOD_RW,
11196 	"The number of headers to evict per sublist before moving to the next");
11197 
11198 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, prune_task_threads, INT, ZMOD_RW,
11199 	"Number of arc_prune threads");
11200