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