xref: /freebsd/sys/contrib/openzfs/module/zfs/arc.c (revision c40487d49bde43806672a0917a7ccc5d1e6301fd)
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 	if (arc_ksp != NULL)
4795 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4796 
4797 	/*
4798 	 * We have to rely on arc_wait_for_eviction() to tell us when to
4799 	 * evict, rather than checking if we are overflowing here, so that we
4800 	 * are sure to not leave arc_wait_for_eviction() waiting on aew_cv.
4801 	 * If we have become "not overflowing" since arc_wait_for_eviction()
4802 	 * checked, we need to wake it up.  We could broadcast the CV here,
4803 	 * but arc_wait_for_eviction() may have not yet gone to sleep.  We
4804 	 * would need to use a mutex to ensure that this function doesn't
4805 	 * broadcast until arc_wait_for_eviction() has gone to sleep (e.g.
4806 	 * the arc_evict_lock).  However, the lock ordering of such a lock
4807 	 * would necessarily be incorrect with respect to the zthr_lock,
4808 	 * which is held before this function is called, and is held by
4809 	 * arc_wait_for_eviction() when it calls zthr_wakeup().
4810 	 */
4811 	return (arc_evict_needed);
4812 }
4813 
4814 /*
4815  * Keep arc_size under arc_c by running arc_evict which evicts data
4816  * from the ARC.
4817  */
4818 /* ARGSUSED */
4819 static void
4820 arc_evict_cb(void *arg, zthr_t *zthr)
4821 {
4822 	uint64_t evicted = 0;
4823 	fstrans_cookie_t cookie = spl_fstrans_mark();
4824 
4825 	/* Evict from cache */
4826 	evicted = arc_evict();
4827 
4828 	/*
4829 	 * If evicted is zero, we couldn't evict anything
4830 	 * via arc_evict(). This could be due to hash lock
4831 	 * collisions, but more likely due to the majority of
4832 	 * arc buffers being unevictable. Therefore, even if
4833 	 * arc_size is above arc_c, another pass is unlikely to
4834 	 * be helpful and could potentially cause us to enter an
4835 	 * infinite loop.  Additionally, zthr_iscancelled() is
4836 	 * checked here so that if the arc is shutting down, the
4837 	 * broadcast will wake any remaining arc evict waiters.
4838 	 */
4839 	mutex_enter(&arc_evict_lock);
4840 	arc_evict_needed = !zthr_iscancelled(arc_evict_zthr) &&
4841 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4842 	if (!arc_evict_needed) {
4843 		/*
4844 		 * We're either no longer overflowing, or we
4845 		 * can't evict anything more, so we should wake
4846 		 * arc_get_data_impl() sooner.
4847 		 */
4848 		arc_evict_waiter_t *aw;
4849 		while ((aw = list_remove_head(&arc_evict_waiters)) != NULL) {
4850 			cv_broadcast(&aw->aew_cv);
4851 		}
4852 		arc_set_need_free();
4853 	}
4854 	mutex_exit(&arc_evict_lock);
4855 	spl_fstrans_unmark(cookie);
4856 }
4857 
4858 /* ARGSUSED */
4859 static boolean_t
4860 arc_reap_cb_check(void *arg, zthr_t *zthr)
4861 {
4862 	int64_t free_memory = arc_available_memory();
4863 	static int reap_cb_check_counter = 0;
4864 
4865 	/*
4866 	 * If a kmem reap is already active, don't schedule more.  We must
4867 	 * check for this because kmem_cache_reap_soon() won't actually
4868 	 * block on the cache being reaped (this is to prevent callers from
4869 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4870 	 * on a system with many, many full magazines, can take minutes).
4871 	 */
4872 	if (!kmem_cache_reap_active() && free_memory < 0) {
4873 
4874 		arc_no_grow = B_TRUE;
4875 		arc_warm = B_TRUE;
4876 		/*
4877 		 * Wait at least zfs_grow_retry (default 5) seconds
4878 		 * before considering growing.
4879 		 */
4880 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4881 		return (B_TRUE);
4882 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4883 		arc_no_grow = B_TRUE;
4884 	} else if (gethrtime() >= arc_growtime) {
4885 		arc_no_grow = B_FALSE;
4886 	}
4887 
4888 	/*
4889 	 * Called unconditionally every 60 seconds to reclaim unused
4890 	 * zstd compression and decompression context. This is done
4891 	 * here to avoid the need for an independent thread.
4892 	 */
4893 	if (!((reap_cb_check_counter++) % 60))
4894 		zfs_zstd_cache_reap_now();
4895 
4896 	return (B_FALSE);
4897 }
4898 
4899 /*
4900  * Keep enough free memory in the system by reaping the ARC's kmem
4901  * caches.  To cause more slabs to be reapable, we may reduce the
4902  * target size of the cache (arc_c), causing the arc_evict_cb()
4903  * to free more buffers.
4904  */
4905 /* ARGSUSED */
4906 static void
4907 arc_reap_cb(void *arg, zthr_t *zthr)
4908 {
4909 	int64_t free_memory;
4910 	fstrans_cookie_t cookie = spl_fstrans_mark();
4911 
4912 	/*
4913 	 * Kick off asynchronous kmem_reap()'s of all our caches.
4914 	 */
4915 	arc_kmem_reap_soon();
4916 
4917 	/*
4918 	 * Wait at least arc_kmem_cache_reap_retry_ms between
4919 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
4920 	 * end up in a situation where we spend lots of time reaping
4921 	 * caches, while we're near arc_c_min.  Waiting here also gives the
4922 	 * subsequent free memory check a chance of finding that the
4923 	 * asynchronous reap has already freed enough memory, and we don't
4924 	 * need to call arc_reduce_target_size().
4925 	 */
4926 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4927 
4928 	/*
4929 	 * Reduce the target size as needed to maintain the amount of free
4930 	 * memory in the system at a fraction of the arc_size (1/128th by
4931 	 * default).  If oversubscribed (free_memory < 0) then reduce the
4932 	 * target arc_size by the deficit amount plus the fractional
4933 	 * amount.  If free memory is positive but less then the fractional
4934 	 * amount, reduce by what is needed to hit the fractional amount.
4935 	 */
4936 	free_memory = arc_available_memory();
4937 
4938 	int64_t to_free =
4939 	    (arc_c >> arc_shrink_shift) - free_memory;
4940 	if (to_free > 0) {
4941 		arc_reduce_target_size(to_free);
4942 	}
4943 	spl_fstrans_unmark(cookie);
4944 }
4945 
4946 #ifdef _KERNEL
4947 /*
4948  * Determine the amount of memory eligible for eviction contained in the
4949  * ARC. All clean data reported by the ghost lists can always be safely
4950  * evicted. Due to arc_c_min, the same does not hold for all clean data
4951  * contained by the regular mru and mfu lists.
4952  *
4953  * In the case of the regular mru and mfu lists, we need to report as
4954  * much clean data as possible, such that evicting that same reported
4955  * data will not bring arc_size below arc_c_min. Thus, in certain
4956  * circumstances, the total amount of clean data in the mru and mfu
4957  * lists might not actually be evictable.
4958  *
4959  * The following two distinct cases are accounted for:
4960  *
4961  * 1. The sum of the amount of dirty data contained by both the mru and
4962  *    mfu lists, plus the ARC's other accounting (e.g. the anon list),
4963  *    is greater than or equal to arc_c_min.
4964  *    (i.e. amount of dirty data >= arc_c_min)
4965  *
4966  *    This is the easy case; all clean data contained by the mru and mfu
4967  *    lists is evictable. Evicting all clean data can only drop arc_size
4968  *    to the amount of dirty data, which is greater than arc_c_min.
4969  *
4970  * 2. The sum of the amount of dirty data contained by both the mru and
4971  *    mfu lists, plus the ARC's other accounting (e.g. the anon list),
4972  *    is less than arc_c_min.
4973  *    (i.e. arc_c_min > amount of dirty data)
4974  *
4975  *    2.1. arc_size is greater than or equal arc_c_min.
4976  *         (i.e. arc_size >= arc_c_min > amount of dirty data)
4977  *
4978  *         In this case, not all clean data from the regular mru and mfu
4979  *         lists is actually evictable; we must leave enough clean data
4980  *         to keep arc_size above arc_c_min. Thus, the maximum amount of
4981  *         evictable data from the two lists combined, is exactly the
4982  *         difference between arc_size and arc_c_min.
4983  *
4984  *    2.2. arc_size is less than arc_c_min
4985  *         (i.e. arc_c_min > arc_size > amount of dirty data)
4986  *
4987  *         In this case, none of the data contained in the mru and mfu
4988  *         lists is evictable, even if it's clean. Since arc_size is
4989  *         already below arc_c_min, evicting any more would only
4990  *         increase this negative difference.
4991  */
4992 
4993 #endif /* _KERNEL */
4994 
4995 /*
4996  * Adapt arc info given the number of bytes we are trying to add and
4997  * the state that we are coming from.  This function is only called
4998  * when we are adding new content to the cache.
4999  */
5000 static void
5001 arc_adapt(int bytes, arc_state_t *state)
5002 {
5003 	int mult;
5004 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
5005 	int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
5006 	int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
5007 
5008 	ASSERT(bytes > 0);
5009 	/*
5010 	 * Adapt the target size of the MRU list:
5011 	 *	- if we just hit in the MRU ghost list, then increase
5012 	 *	  the target size of the MRU list.
5013 	 *	- if we just hit in the MFU ghost list, then increase
5014 	 *	  the target size of the MFU list by decreasing the
5015 	 *	  target size of the MRU list.
5016 	 */
5017 	if (state == arc_mru_ghost) {
5018 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
5019 		if (!zfs_arc_p_dampener_disable)
5020 			mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
5021 
5022 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
5023 	} else if (state == arc_mfu_ghost) {
5024 		uint64_t delta;
5025 
5026 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
5027 		if (!zfs_arc_p_dampener_disable)
5028 			mult = MIN(mult, 10);
5029 
5030 		delta = MIN(bytes * mult, arc_p);
5031 		arc_p = MAX(arc_p_min, arc_p - delta);
5032 	}
5033 	ASSERT((int64_t)arc_p >= 0);
5034 
5035 	/*
5036 	 * Wake reap thread if we do not have any available memory
5037 	 */
5038 	if (arc_reclaim_needed()) {
5039 		zthr_wakeup(arc_reap_zthr);
5040 		return;
5041 	}
5042 
5043 	if (arc_no_grow)
5044 		return;
5045 
5046 	if (arc_c >= arc_c_max)
5047 		return;
5048 
5049 	/*
5050 	 * If we're within (2 * maxblocksize) bytes of the target
5051 	 * cache size, increment the target cache size
5052 	 */
5053 	ASSERT3U(arc_c, >=, 2ULL << SPA_MAXBLOCKSHIFT);
5054 	if (aggsum_upper_bound(&arc_size) >=
5055 	    arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
5056 		atomic_add_64(&arc_c, (int64_t)bytes);
5057 		if (arc_c > arc_c_max)
5058 			arc_c = arc_c_max;
5059 		else if (state == arc_anon)
5060 			atomic_add_64(&arc_p, (int64_t)bytes);
5061 		if (arc_p > arc_c)
5062 			arc_p = arc_c;
5063 	}
5064 	ASSERT((int64_t)arc_p >= 0);
5065 }
5066 
5067 /*
5068  * Check if arc_size has grown past our upper threshold, determined by
5069  * zfs_arc_overflow_shift.
5070  */
5071 boolean_t
5072 arc_is_overflowing(void)
5073 {
5074 	/* Always allow at least one block of overflow */
5075 	int64_t overflow = MAX(SPA_MAXBLOCKSIZE,
5076 	    arc_c >> zfs_arc_overflow_shift);
5077 
5078 	/*
5079 	 * We just compare the lower bound here for performance reasons. Our
5080 	 * primary goals are to make sure that the arc never grows without
5081 	 * bound, and that it can reach its maximum size. This check
5082 	 * accomplishes both goals. The maximum amount we could run over by is
5083 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
5084 	 * in the ARC. In practice, that's in the tens of MB, which is low
5085 	 * enough to be safe.
5086 	 */
5087 	return (aggsum_lower_bound(&arc_size) >= (int64_t)arc_c + overflow);
5088 }
5089 
5090 static abd_t *
5091 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag,
5092     boolean_t do_adapt)
5093 {
5094 	arc_buf_contents_t type = arc_buf_type(hdr);
5095 
5096 	arc_get_data_impl(hdr, size, tag, do_adapt);
5097 	if (type == ARC_BUFC_METADATA) {
5098 		return (abd_alloc(size, B_TRUE));
5099 	} else {
5100 		ASSERT(type == ARC_BUFC_DATA);
5101 		return (abd_alloc(size, B_FALSE));
5102 	}
5103 }
5104 
5105 static void *
5106 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5107 {
5108 	arc_buf_contents_t type = arc_buf_type(hdr);
5109 
5110 	arc_get_data_impl(hdr, size, tag, B_TRUE);
5111 	if (type == ARC_BUFC_METADATA) {
5112 		return (zio_buf_alloc(size));
5113 	} else {
5114 		ASSERT(type == ARC_BUFC_DATA);
5115 		return (zio_data_buf_alloc(size));
5116 	}
5117 }
5118 
5119 /*
5120  * Wait for the specified amount of data (in bytes) to be evicted from the
5121  * ARC, and for there to be sufficient free memory in the system.  Waiting for
5122  * eviction ensures that the memory used by the ARC decreases.  Waiting for
5123  * free memory ensures that the system won't run out of free pages, regardless
5124  * of ARC behavior and settings.  See arc_lowmem_init().
5125  */
5126 void
5127 arc_wait_for_eviction(uint64_t amount)
5128 {
5129 	mutex_enter(&arc_evict_lock);
5130 	if (arc_is_overflowing()) {
5131 		arc_evict_needed = B_TRUE;
5132 		zthr_wakeup(arc_evict_zthr);
5133 
5134 		if (amount != 0) {
5135 			arc_evict_waiter_t aw;
5136 			list_link_init(&aw.aew_node);
5137 			cv_init(&aw.aew_cv, NULL, CV_DEFAULT, NULL);
5138 
5139 			arc_evict_waiter_t *last =
5140 			    list_tail(&arc_evict_waiters);
5141 			if (last != NULL) {
5142 				ASSERT3U(last->aew_count, >, arc_evict_count);
5143 				aw.aew_count = last->aew_count + amount;
5144 			} else {
5145 				aw.aew_count = arc_evict_count + amount;
5146 			}
5147 
5148 			list_insert_tail(&arc_evict_waiters, &aw);
5149 
5150 			arc_set_need_free();
5151 
5152 			DTRACE_PROBE3(arc__wait__for__eviction,
5153 			    uint64_t, amount,
5154 			    uint64_t, arc_evict_count,
5155 			    uint64_t, aw.aew_count);
5156 
5157 			/*
5158 			 * We will be woken up either when arc_evict_count
5159 			 * reaches aew_count, or when the ARC is no longer
5160 			 * overflowing and eviction completes.
5161 			 */
5162 			cv_wait(&aw.aew_cv, &arc_evict_lock);
5163 
5164 			/*
5165 			 * In case of "false" wakeup, we will still be on the
5166 			 * list.
5167 			 */
5168 			if (list_link_active(&aw.aew_node))
5169 				list_remove(&arc_evict_waiters, &aw);
5170 
5171 			cv_destroy(&aw.aew_cv);
5172 		}
5173 	}
5174 	mutex_exit(&arc_evict_lock);
5175 }
5176 
5177 /*
5178  * Allocate a block and return it to the caller. If we are hitting the
5179  * hard limit for the cache size, we must sleep, waiting for the eviction
5180  * thread to catch up. If we're past the target size but below the hard
5181  * limit, we'll only signal the reclaim thread and continue on.
5182  */
5183 static void
5184 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag,
5185     boolean_t do_adapt)
5186 {
5187 	arc_state_t *state = hdr->b_l1hdr.b_state;
5188 	arc_buf_contents_t type = arc_buf_type(hdr);
5189 
5190 	if (do_adapt)
5191 		arc_adapt(size, state);
5192 
5193 	/*
5194 	 * If arc_size is currently overflowing, we must be adding data
5195 	 * faster than we are evicting.  To ensure we don't compound the
5196 	 * problem by adding more data and forcing arc_size to grow even
5197 	 * further past it's target size, we wait for the eviction thread to
5198 	 * make some progress.  We also wait for there to be sufficient free
5199 	 * memory in the system, as measured by arc_free_memory().
5200 	 *
5201 	 * Specifically, we wait for zfs_arc_eviction_pct percent of the
5202 	 * requested size to be evicted.  This should be more than 100%, to
5203 	 * ensure that that progress is also made towards getting arc_size
5204 	 * under arc_c.  See the comment above zfs_arc_eviction_pct.
5205 	 *
5206 	 * We do the overflowing check without holding the arc_evict_lock to
5207 	 * reduce lock contention in this hot path.  Note that
5208 	 * arc_wait_for_eviction() will acquire the lock and check again to
5209 	 * ensure we are truly overflowing before blocking.
5210 	 */
5211 	if (arc_is_overflowing()) {
5212 		arc_wait_for_eviction(size *
5213 		    zfs_arc_eviction_pct / 100);
5214 	}
5215 
5216 	VERIFY3U(hdr->b_type, ==, type);
5217 	if (type == ARC_BUFC_METADATA) {
5218 		arc_space_consume(size, ARC_SPACE_META);
5219 	} else {
5220 		arc_space_consume(size, ARC_SPACE_DATA);
5221 	}
5222 
5223 	/*
5224 	 * Update the state size.  Note that ghost states have a
5225 	 * "ghost size" and so don't need to be updated.
5226 	 */
5227 	if (!GHOST_STATE(state)) {
5228 
5229 		(void) zfs_refcount_add_many(&state->arcs_size, size, tag);
5230 
5231 		/*
5232 		 * If this is reached via arc_read, the link is
5233 		 * protected by the hash lock. If reached via
5234 		 * arc_buf_alloc, the header should not be accessed by
5235 		 * any other thread. And, if reached via arc_read_done,
5236 		 * the hash lock will protect it if it's found in the
5237 		 * hash table; otherwise no other thread should be
5238 		 * trying to [add|remove]_reference it.
5239 		 */
5240 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5241 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5242 			(void) zfs_refcount_add_many(&state->arcs_esize[type],
5243 			    size, tag);
5244 		}
5245 
5246 		/*
5247 		 * If we are growing the cache, and we are adding anonymous
5248 		 * data, and we have outgrown arc_p, update arc_p
5249 		 */
5250 		if (aggsum_upper_bound(&arc_size) < arc_c &&
5251 		    hdr->b_l1hdr.b_state == arc_anon &&
5252 		    (zfs_refcount_count(&arc_anon->arcs_size) +
5253 		    zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
5254 			arc_p = MIN(arc_c, arc_p + size);
5255 	}
5256 }
5257 
5258 static void
5259 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5260 {
5261 	arc_free_data_impl(hdr, size, tag);
5262 	abd_free(abd);
5263 }
5264 
5265 static void
5266 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5267 {
5268 	arc_buf_contents_t type = arc_buf_type(hdr);
5269 
5270 	arc_free_data_impl(hdr, size, tag);
5271 	if (type == ARC_BUFC_METADATA) {
5272 		zio_buf_free(buf, size);
5273 	} else {
5274 		ASSERT(type == ARC_BUFC_DATA);
5275 		zio_data_buf_free(buf, size);
5276 	}
5277 }
5278 
5279 /*
5280  * Free the arc data buffer.
5281  */
5282 static void
5283 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5284 {
5285 	arc_state_t *state = hdr->b_l1hdr.b_state;
5286 	arc_buf_contents_t type = arc_buf_type(hdr);
5287 
5288 	/* protected by hash lock, if in the hash table */
5289 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5290 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5291 		ASSERT(state != arc_anon && state != arc_l2c_only);
5292 
5293 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
5294 		    size, tag);
5295 	}
5296 	(void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
5297 
5298 	VERIFY3U(hdr->b_type, ==, type);
5299 	if (type == ARC_BUFC_METADATA) {
5300 		arc_space_return(size, ARC_SPACE_META);
5301 	} else {
5302 		ASSERT(type == ARC_BUFC_DATA);
5303 		arc_space_return(size, ARC_SPACE_DATA);
5304 	}
5305 }
5306 
5307 /*
5308  * This routine is called whenever a buffer is accessed.
5309  * NOTE: the hash lock is dropped in this function.
5310  */
5311 static void
5312 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5313 {
5314 	clock_t now;
5315 
5316 	ASSERT(MUTEX_HELD(hash_lock));
5317 	ASSERT(HDR_HAS_L1HDR(hdr));
5318 
5319 	if (hdr->b_l1hdr.b_state == arc_anon) {
5320 		/*
5321 		 * This buffer is not in the cache, and does not
5322 		 * appear in our "ghost" list.  Add the new buffer
5323 		 * to the MRU state.
5324 		 */
5325 
5326 		ASSERT0(hdr->b_l1hdr.b_arc_access);
5327 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5328 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5329 		arc_change_state(arc_mru, hdr, hash_lock);
5330 
5331 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
5332 		now = ddi_get_lbolt();
5333 
5334 		/*
5335 		 * If this buffer is here because of a prefetch, then either:
5336 		 * - clear the flag if this is a "referencing" read
5337 		 *   (any subsequent access will bump this into the MFU state).
5338 		 * or
5339 		 * - move the buffer to the head of the list if this is
5340 		 *   another prefetch (to make it less likely to be evicted).
5341 		 */
5342 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5343 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5344 				/* link protected by hash lock */
5345 				ASSERT(multilist_link_active(
5346 				    &hdr->b_l1hdr.b_arc_node));
5347 			} else {
5348 				arc_hdr_clear_flags(hdr,
5349 				    ARC_FLAG_PREFETCH |
5350 				    ARC_FLAG_PRESCIENT_PREFETCH);
5351 				atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
5352 				ARCSTAT_BUMP(arcstat_mru_hits);
5353 			}
5354 			hdr->b_l1hdr.b_arc_access = now;
5355 			return;
5356 		}
5357 
5358 		/*
5359 		 * This buffer has been "accessed" only once so far,
5360 		 * but it is still in the cache. Move it to the MFU
5361 		 * state.
5362 		 */
5363 		if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
5364 		    ARC_MINTIME)) {
5365 			/*
5366 			 * More than 125ms have passed since we
5367 			 * instantiated this buffer.  Move it to the
5368 			 * most frequently used state.
5369 			 */
5370 			hdr->b_l1hdr.b_arc_access = now;
5371 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5372 			arc_change_state(arc_mfu, hdr, hash_lock);
5373 		}
5374 		atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
5375 		ARCSTAT_BUMP(arcstat_mru_hits);
5376 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5377 		arc_state_t	*new_state;
5378 		/*
5379 		 * This buffer has been "accessed" recently, but
5380 		 * was evicted from the cache.  Move it to the
5381 		 * MFU state.
5382 		 */
5383 
5384 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5385 			new_state = arc_mru;
5386 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5387 				arc_hdr_clear_flags(hdr,
5388 				    ARC_FLAG_PREFETCH |
5389 				    ARC_FLAG_PRESCIENT_PREFETCH);
5390 			}
5391 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5392 		} else {
5393 			new_state = arc_mfu;
5394 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5395 		}
5396 
5397 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5398 		arc_change_state(new_state, hdr, hash_lock);
5399 
5400 		atomic_inc_32(&hdr->b_l1hdr.b_mru_ghost_hits);
5401 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5402 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
5403 		/*
5404 		 * This buffer has been accessed more than once and is
5405 		 * still in the cache.  Keep it in the MFU state.
5406 		 *
5407 		 * NOTE: an add_reference() that occurred when we did
5408 		 * the arc_read() will have kicked this off the list.
5409 		 * If it was a prefetch, we will explicitly move it to
5410 		 * the head of the list now.
5411 		 */
5412 
5413 		atomic_inc_32(&hdr->b_l1hdr.b_mfu_hits);
5414 		ARCSTAT_BUMP(arcstat_mfu_hits);
5415 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5416 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5417 		arc_state_t	*new_state = arc_mfu;
5418 		/*
5419 		 * This buffer has been accessed more than once but has
5420 		 * been evicted from the cache.  Move it back to the
5421 		 * MFU state.
5422 		 */
5423 
5424 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5425 			/*
5426 			 * This is a prefetch access...
5427 			 * move this block back to the MRU state.
5428 			 */
5429 			new_state = arc_mru;
5430 		}
5431 
5432 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5433 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5434 		arc_change_state(new_state, hdr, hash_lock);
5435 
5436 		atomic_inc_32(&hdr->b_l1hdr.b_mfu_ghost_hits);
5437 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5438 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5439 		/*
5440 		 * This buffer is on the 2nd Level ARC.
5441 		 */
5442 
5443 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5444 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5445 		arc_change_state(arc_mfu, hdr, hash_lock);
5446 	} else {
5447 		cmn_err(CE_PANIC, "invalid arc state 0x%p",
5448 		    hdr->b_l1hdr.b_state);
5449 	}
5450 }
5451 
5452 /*
5453  * This routine is called by dbuf_hold() to update the arc_access() state
5454  * which otherwise would be skipped for entries in the dbuf cache.
5455  */
5456 void
5457 arc_buf_access(arc_buf_t *buf)
5458 {
5459 	mutex_enter(&buf->b_evict_lock);
5460 	arc_buf_hdr_t *hdr = buf->b_hdr;
5461 
5462 	/*
5463 	 * Avoid taking the hash_lock when possible as an optimization.
5464 	 * The header must be checked again under the hash_lock in order
5465 	 * to handle the case where it is concurrently being released.
5466 	 */
5467 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5468 		mutex_exit(&buf->b_evict_lock);
5469 		return;
5470 	}
5471 
5472 	kmutex_t *hash_lock = HDR_LOCK(hdr);
5473 	mutex_enter(hash_lock);
5474 
5475 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5476 		mutex_exit(hash_lock);
5477 		mutex_exit(&buf->b_evict_lock);
5478 		ARCSTAT_BUMP(arcstat_access_skip);
5479 		return;
5480 	}
5481 
5482 	mutex_exit(&buf->b_evict_lock);
5483 
5484 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5485 	    hdr->b_l1hdr.b_state == arc_mfu);
5486 
5487 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5488 	arc_access(hdr, hash_lock);
5489 	mutex_exit(hash_lock);
5490 
5491 	ARCSTAT_BUMP(arcstat_hits);
5492 	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr) && !HDR_PRESCIENT_PREFETCH(hdr),
5493 	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5494 }
5495 
5496 /* a generic arc_read_done_func_t which you can use */
5497 /* ARGSUSED */
5498 void
5499 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5500     arc_buf_t *buf, void *arg)
5501 {
5502 	if (buf == NULL)
5503 		return;
5504 
5505 	bcopy(buf->b_data, arg, arc_buf_size(buf));
5506 	arc_buf_destroy(buf, arg);
5507 }
5508 
5509 /* a generic arc_read_done_func_t */
5510 /* ARGSUSED */
5511 void
5512 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5513     arc_buf_t *buf, void *arg)
5514 {
5515 	arc_buf_t **bufp = arg;
5516 
5517 	if (buf == NULL) {
5518 		ASSERT(zio == NULL || zio->io_error != 0);
5519 		*bufp = NULL;
5520 	} else {
5521 		ASSERT(zio == NULL || zio->io_error == 0);
5522 		*bufp = buf;
5523 		ASSERT(buf->b_data != NULL);
5524 	}
5525 }
5526 
5527 static void
5528 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5529 {
5530 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5531 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5532 		ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
5533 	} else {
5534 		if (HDR_COMPRESSION_ENABLED(hdr)) {
5535 			ASSERT3U(arc_hdr_get_compress(hdr), ==,
5536 			    BP_GET_COMPRESS(bp));
5537 		}
5538 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5539 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5540 		ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
5541 	}
5542 }
5543 
5544 static void
5545 arc_read_done(zio_t *zio)
5546 {
5547 	blkptr_t 	*bp = zio->io_bp;
5548 	arc_buf_hdr_t	*hdr = zio->io_private;
5549 	kmutex_t	*hash_lock = NULL;
5550 	arc_callback_t	*callback_list;
5551 	arc_callback_t	*acb;
5552 	boolean_t	freeable = B_FALSE;
5553 
5554 	/*
5555 	 * The hdr was inserted into hash-table and removed from lists
5556 	 * prior to starting I/O.  We should find this header, since
5557 	 * it's in the hash table, and it should be legit since it's
5558 	 * not possible to evict it during the I/O.  The only possible
5559 	 * reason for it not to be found is if we were freed during the
5560 	 * read.
5561 	 */
5562 	if (HDR_IN_HASH_TABLE(hdr)) {
5563 		arc_buf_hdr_t *found;
5564 
5565 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5566 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
5567 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
5568 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
5569 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
5570 
5571 		found = buf_hash_find(hdr->b_spa, zio->io_bp, &hash_lock);
5572 
5573 		ASSERT((found == hdr &&
5574 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5575 		    (found == hdr && HDR_L2_READING(hdr)));
5576 		ASSERT3P(hash_lock, !=, NULL);
5577 	}
5578 
5579 	if (BP_IS_PROTECTED(bp)) {
5580 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5581 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5582 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5583 		    hdr->b_crypt_hdr.b_iv);
5584 
5585 		if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5586 			void *tmpbuf;
5587 
5588 			tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5589 			    sizeof (zil_chain_t));
5590 			zio_crypt_decode_mac_zil(tmpbuf,
5591 			    hdr->b_crypt_hdr.b_mac);
5592 			abd_return_buf(zio->io_abd, tmpbuf,
5593 			    sizeof (zil_chain_t));
5594 		} else {
5595 			zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
5596 		}
5597 	}
5598 
5599 	if (zio->io_error == 0) {
5600 		/* byteswap if necessary */
5601 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5602 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
5603 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5604 			} else {
5605 				hdr->b_l1hdr.b_byteswap =
5606 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5607 			}
5608 		} else {
5609 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5610 		}
5611 		if (!HDR_L2_READING(hdr)) {
5612 			hdr->b_complevel = zio->io_prop.zp_complevel;
5613 		}
5614 	}
5615 
5616 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5617 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5618 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5619 
5620 	callback_list = hdr->b_l1hdr.b_acb;
5621 	ASSERT3P(callback_list, !=, NULL);
5622 
5623 	if (hash_lock && zio->io_error == 0 &&
5624 	    hdr->b_l1hdr.b_state == arc_anon) {
5625 		/*
5626 		 * Only call arc_access on anonymous buffers.  This is because
5627 		 * if we've issued an I/O for an evicted buffer, we've already
5628 		 * called arc_access (to prevent any simultaneous readers from
5629 		 * getting confused).
5630 		 */
5631 		arc_access(hdr, hash_lock);
5632 	}
5633 
5634 	/*
5635 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
5636 	 * make a buf containing the data according to the parameters which were
5637 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5638 	 * aren't needlessly decompressing the data multiple times.
5639 	 */
5640 	int callback_cnt = 0;
5641 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5642 		if (!acb->acb_done)
5643 			continue;
5644 
5645 		callback_cnt++;
5646 
5647 		if (zio->io_error != 0)
5648 			continue;
5649 
5650 		int error = arc_buf_alloc_impl(hdr, zio->io_spa,
5651 		    &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
5652 		    acb->acb_compressed, acb->acb_noauth, B_TRUE,
5653 		    &acb->acb_buf);
5654 
5655 		/*
5656 		 * Assert non-speculative zios didn't fail because an
5657 		 * encryption key wasn't loaded
5658 		 */
5659 		ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
5660 		    error != EACCES);
5661 
5662 		/*
5663 		 * If we failed to decrypt, report an error now (as the zio
5664 		 * layer would have done if it had done the transforms).
5665 		 */
5666 		if (error == ECKSUM) {
5667 			ASSERT(BP_IS_PROTECTED(bp));
5668 			error = SET_ERROR(EIO);
5669 			if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5670 				spa_log_error(zio->io_spa, &acb->acb_zb);
5671 				(void) zfs_ereport_post(
5672 				    FM_EREPORT_ZFS_AUTHENTICATION,
5673 				    zio->io_spa, NULL, &acb->acb_zb, zio, 0);
5674 			}
5675 		}
5676 
5677 		if (error != 0) {
5678 			/*
5679 			 * Decompression or decryption failed.  Set
5680 			 * io_error so that when we call acb_done
5681 			 * (below), we will indicate that the read
5682 			 * failed. Note that in the unusual case
5683 			 * where one callback is compressed and another
5684 			 * uncompressed, we will mark all of them
5685 			 * as failed, even though the uncompressed
5686 			 * one can't actually fail.  In this case,
5687 			 * the hdr will not be anonymous, because
5688 			 * if there are multiple callbacks, it's
5689 			 * because multiple threads found the same
5690 			 * arc buf in the hash table.
5691 			 */
5692 			zio->io_error = error;
5693 		}
5694 	}
5695 
5696 	/*
5697 	 * If there are multiple callbacks, we must have the hash lock,
5698 	 * because the only way for multiple threads to find this hdr is
5699 	 * in the hash table.  This ensures that if there are multiple
5700 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
5701 	 * we couldn't use arc_buf_destroy() in the error case below.
5702 	 */
5703 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
5704 
5705 	hdr->b_l1hdr.b_acb = NULL;
5706 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5707 	if (callback_cnt == 0)
5708 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
5709 
5710 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5711 	    callback_list != NULL);
5712 
5713 	if (zio->io_error == 0) {
5714 		arc_hdr_verify(hdr, zio->io_bp);
5715 	} else {
5716 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5717 		if (hdr->b_l1hdr.b_state != arc_anon)
5718 			arc_change_state(arc_anon, hdr, hash_lock);
5719 		if (HDR_IN_HASH_TABLE(hdr))
5720 			buf_hash_remove(hdr);
5721 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5722 	}
5723 
5724 	/*
5725 	 * Broadcast before we drop the hash_lock to avoid the possibility
5726 	 * that the hdr (and hence the cv) might be freed before we get to
5727 	 * the cv_broadcast().
5728 	 */
5729 	cv_broadcast(&hdr->b_l1hdr.b_cv);
5730 
5731 	if (hash_lock != NULL) {
5732 		mutex_exit(hash_lock);
5733 	} else {
5734 		/*
5735 		 * This block was freed while we waited for the read to
5736 		 * complete.  It has been removed from the hash table and
5737 		 * moved to the anonymous state (so that it won't show up
5738 		 * in the cache).
5739 		 */
5740 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5741 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5742 	}
5743 
5744 	/* execute each callback and free its structure */
5745 	while ((acb = callback_list) != NULL) {
5746 		if (acb->acb_done != NULL) {
5747 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
5748 				/*
5749 				 * If arc_buf_alloc_impl() fails during
5750 				 * decompression, the buf will still be
5751 				 * allocated, and needs to be freed here.
5752 				 */
5753 				arc_buf_destroy(acb->acb_buf,
5754 				    acb->acb_private);
5755 				acb->acb_buf = NULL;
5756 			}
5757 			acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5758 			    acb->acb_buf, acb->acb_private);
5759 		}
5760 
5761 		if (acb->acb_zio_dummy != NULL) {
5762 			acb->acb_zio_dummy->io_error = zio->io_error;
5763 			zio_nowait(acb->acb_zio_dummy);
5764 		}
5765 
5766 		callback_list = acb->acb_next;
5767 		kmem_free(acb, sizeof (arc_callback_t));
5768 	}
5769 
5770 	if (freeable)
5771 		arc_hdr_destroy(hdr);
5772 }
5773 
5774 /*
5775  * "Read" the block at the specified DVA (in bp) via the
5776  * cache.  If the block is found in the cache, invoke the provided
5777  * callback immediately and return.  Note that the `zio' parameter
5778  * in the callback will be NULL in this case, since no IO was
5779  * required.  If the block is not in the cache pass the read request
5780  * on to the spa with a substitute callback function, so that the
5781  * requested block will be added to the cache.
5782  *
5783  * If a read request arrives for a block that has a read in-progress,
5784  * either wait for the in-progress read to complete (and return the
5785  * results); or, if this is a read with a "done" func, add a record
5786  * to the read to invoke the "done" func when the read completes,
5787  * and return; or just return.
5788  *
5789  * arc_read_done() will invoke all the requested "done" functions
5790  * for readers of this block.
5791  */
5792 int
5793 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
5794     arc_read_done_func_t *done, void *private, zio_priority_t priority,
5795     int zio_flags, arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5796 {
5797 	arc_buf_hdr_t *hdr = NULL;
5798 	kmutex_t *hash_lock = NULL;
5799 	zio_t *rzio;
5800 	uint64_t guid = spa_load_guid(spa);
5801 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5802 	boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5803 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5804 	boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5805 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5806 	boolean_t embedded_bp = !!BP_IS_EMBEDDED(bp);
5807 	int rc = 0;
5808 
5809 	ASSERT(!embedded_bp ||
5810 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5811 	ASSERT(!BP_IS_HOLE(bp));
5812 	ASSERT(!BP_IS_REDACTED(bp));
5813 
5814 	/*
5815 	 * Normally SPL_FSTRANS will already be set since kernel threads which
5816 	 * expect to call the DMU interfaces will set it when created.  System
5817 	 * calls are similarly handled by setting/cleaning the bit in the
5818 	 * registered callback (module/os/.../zfs/zpl_*).
5819 	 *
5820 	 * External consumers such as Lustre which call the exported DMU
5821 	 * interfaces may not have set SPL_FSTRANS.  To avoid a deadlock
5822 	 * on the hash_lock always set and clear the bit.
5823 	 */
5824 	fstrans_cookie_t cookie = spl_fstrans_mark();
5825 top:
5826 	if (!embedded_bp) {
5827 		/*
5828 		 * Embedded BP's have no DVA and require no I/O to "read".
5829 		 * Create an anonymous arc buf to back it.
5830 		 */
5831 		hdr = buf_hash_find(guid, bp, &hash_lock);
5832 	}
5833 
5834 	/*
5835 	 * Determine if we have an L1 cache hit or a cache miss. For simplicity
5836 	 * we maintain encrypted data separately from compressed / uncompressed
5837 	 * data. If the user is requesting raw encrypted data and we don't have
5838 	 * that in the header we will read from disk to guarantee that we can
5839 	 * get it even if the encryption keys aren't loaded.
5840 	 */
5841 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
5842 	    (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
5843 		arc_buf_t *buf = NULL;
5844 		*arc_flags |= ARC_FLAG_CACHED;
5845 
5846 		if (HDR_IO_IN_PROGRESS(hdr)) {
5847 			zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5848 
5849 			if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
5850 				mutex_exit(hash_lock);
5851 				ARCSTAT_BUMP(arcstat_cached_only_in_progress);
5852 				rc = SET_ERROR(ENOENT);
5853 				goto out;
5854 			}
5855 
5856 			ASSERT3P(head_zio, !=, NULL);
5857 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5858 			    priority == ZIO_PRIORITY_SYNC_READ) {
5859 				/*
5860 				 * This is a sync read that needs to wait for
5861 				 * an in-flight async read. Request that the
5862 				 * zio have its priority upgraded.
5863 				 */
5864 				zio_change_priority(head_zio, priority);
5865 				DTRACE_PROBE1(arc__async__upgrade__sync,
5866 				    arc_buf_hdr_t *, hdr);
5867 				ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5868 			}
5869 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5870 				arc_hdr_clear_flags(hdr,
5871 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5872 			}
5873 
5874 			if (*arc_flags & ARC_FLAG_WAIT) {
5875 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5876 				mutex_exit(hash_lock);
5877 				goto top;
5878 			}
5879 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5880 
5881 			if (done) {
5882 				arc_callback_t *acb = NULL;
5883 
5884 				acb = kmem_zalloc(sizeof (arc_callback_t),
5885 				    KM_SLEEP);
5886 				acb->acb_done = done;
5887 				acb->acb_private = private;
5888 				acb->acb_compressed = compressed_read;
5889 				acb->acb_encrypted = encrypted_read;
5890 				acb->acb_noauth = noauth_read;
5891 				acb->acb_zb = *zb;
5892 				if (pio != NULL)
5893 					acb->acb_zio_dummy = zio_null(pio,
5894 					    spa, NULL, NULL, NULL, zio_flags);
5895 
5896 				ASSERT3P(acb->acb_done, !=, NULL);
5897 				acb->acb_zio_head = head_zio;
5898 				acb->acb_next = hdr->b_l1hdr.b_acb;
5899 				hdr->b_l1hdr.b_acb = acb;
5900 				mutex_exit(hash_lock);
5901 				goto out;
5902 			}
5903 			mutex_exit(hash_lock);
5904 			goto out;
5905 		}
5906 
5907 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5908 		    hdr->b_l1hdr.b_state == arc_mfu);
5909 
5910 		if (done) {
5911 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5912 				/*
5913 				 * This is a demand read which does not have to
5914 				 * wait for i/o because we did a predictive
5915 				 * prefetch i/o for it, which has completed.
5916 				 */
5917 				DTRACE_PROBE1(
5918 				    arc__demand__hit__predictive__prefetch,
5919 				    arc_buf_hdr_t *, hdr);
5920 				ARCSTAT_BUMP(
5921 				    arcstat_demand_hit_predictive_prefetch);
5922 				arc_hdr_clear_flags(hdr,
5923 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5924 			}
5925 
5926 			if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5927 				ARCSTAT_BUMP(
5928 				    arcstat_demand_hit_prescient_prefetch);
5929 				arc_hdr_clear_flags(hdr,
5930 				    ARC_FLAG_PRESCIENT_PREFETCH);
5931 			}
5932 
5933 			ASSERT(!embedded_bp || !BP_IS_HOLE(bp));
5934 
5935 			/* Get a buf with the desired data in it. */
5936 			rc = arc_buf_alloc_impl(hdr, spa, zb, private,
5937 			    encrypted_read, compressed_read, noauth_read,
5938 			    B_TRUE, &buf);
5939 			if (rc == ECKSUM) {
5940 				/*
5941 				 * Convert authentication and decryption errors
5942 				 * to EIO (and generate an ereport if needed)
5943 				 * before leaving the ARC.
5944 				 */
5945 				rc = SET_ERROR(EIO);
5946 				if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5947 					spa_log_error(spa, zb);
5948 					(void) zfs_ereport_post(
5949 					    FM_EREPORT_ZFS_AUTHENTICATION,
5950 					    spa, NULL, zb, NULL, 0);
5951 				}
5952 			}
5953 			if (rc != 0) {
5954 				(void) remove_reference(hdr, hash_lock,
5955 				    private);
5956 				arc_buf_destroy_impl(buf);
5957 				buf = NULL;
5958 			}
5959 
5960 			/* assert any errors weren't due to unloaded keys */
5961 			ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
5962 			    rc != EACCES);
5963 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
5964 		    zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5965 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5966 		}
5967 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5968 		arc_access(hdr, hash_lock);
5969 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5970 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5971 		if (*arc_flags & ARC_FLAG_L2CACHE)
5972 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5973 		mutex_exit(hash_lock);
5974 		ARCSTAT_BUMP(arcstat_hits);
5975 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5976 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5977 		    data, metadata, hits);
5978 
5979 		if (done)
5980 			done(NULL, zb, bp, buf, private);
5981 	} else {
5982 		uint64_t lsize = BP_GET_LSIZE(bp);
5983 		uint64_t psize = BP_GET_PSIZE(bp);
5984 		arc_callback_t *acb;
5985 		vdev_t *vd = NULL;
5986 		uint64_t addr = 0;
5987 		boolean_t devw = B_FALSE;
5988 		uint64_t size;
5989 		abd_t *hdr_abd;
5990 		int alloc_flags = encrypted_read ? ARC_HDR_ALLOC_RDATA : 0;
5991 
5992 		if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
5993 			rc = SET_ERROR(ENOENT);
5994 			if (hash_lock != NULL)
5995 				mutex_exit(hash_lock);
5996 			goto out;
5997 		}
5998 
5999 		/*
6000 		 * Gracefully handle a damaged logical block size as a
6001 		 * checksum error.
6002 		 */
6003 		if (lsize > spa_maxblocksize(spa)) {
6004 			rc = SET_ERROR(ECKSUM);
6005 			if (hash_lock != NULL)
6006 				mutex_exit(hash_lock);
6007 			goto out;
6008 		}
6009 
6010 		if (hdr == NULL) {
6011 			/*
6012 			 * This block is not in the cache or it has
6013 			 * embedded data.
6014 			 */
6015 			arc_buf_hdr_t *exists = NULL;
6016 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
6017 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
6018 			    BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), 0, type,
6019 			    encrypted_read);
6020 
6021 			if (!embedded_bp) {
6022 				hdr->b_dva = *BP_IDENTITY(bp);
6023 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
6024 				exists = buf_hash_insert(hdr, &hash_lock);
6025 			}
6026 			if (exists != NULL) {
6027 				/* somebody beat us to the hash insert */
6028 				mutex_exit(hash_lock);
6029 				buf_discard_identity(hdr);
6030 				arc_hdr_destroy(hdr);
6031 				goto top; /* restart the IO request */
6032 			}
6033 		} else {
6034 			/*
6035 			 * This block is in the ghost cache or encrypted data
6036 			 * was requested and we didn't have it. If it was
6037 			 * L2-only (and thus didn't have an L1 hdr),
6038 			 * we realloc the header to add an L1 hdr.
6039 			 */
6040 			if (!HDR_HAS_L1HDR(hdr)) {
6041 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
6042 				    hdr_full_cache);
6043 			}
6044 
6045 			if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
6046 				ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6047 				ASSERT(!HDR_HAS_RABD(hdr));
6048 				ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6049 				ASSERT0(zfs_refcount_count(
6050 				    &hdr->b_l1hdr.b_refcnt));
6051 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
6052 				ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
6053 			} else if (HDR_IO_IN_PROGRESS(hdr)) {
6054 				/*
6055 				 * If this header already had an IO in progress
6056 				 * and we are performing another IO to fetch
6057 				 * encrypted data we must wait until the first
6058 				 * IO completes so as not to confuse
6059 				 * arc_read_done(). This should be very rare
6060 				 * and so the performance impact shouldn't
6061 				 * matter.
6062 				 */
6063 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
6064 				mutex_exit(hash_lock);
6065 				goto top;
6066 			}
6067 
6068 			/*
6069 			 * This is a delicate dance that we play here.
6070 			 * This hdr might be in the ghost list so we access
6071 			 * it to move it out of the ghost list before we
6072 			 * initiate the read. If it's a prefetch then
6073 			 * it won't have a callback so we'll remove the
6074 			 * reference that arc_buf_alloc_impl() created. We
6075 			 * do this after we've called arc_access() to
6076 			 * avoid hitting an assert in remove_reference().
6077 			 */
6078 			arc_adapt(arc_hdr_size(hdr), hdr->b_l1hdr.b_state);
6079 			arc_access(hdr, hash_lock);
6080 			arc_hdr_alloc_abd(hdr, alloc_flags);
6081 		}
6082 
6083 		if (encrypted_read) {
6084 			ASSERT(HDR_HAS_RABD(hdr));
6085 			size = HDR_GET_PSIZE(hdr);
6086 			hdr_abd = hdr->b_crypt_hdr.b_rabd;
6087 			zio_flags |= ZIO_FLAG_RAW;
6088 		} else {
6089 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6090 			size = arc_hdr_size(hdr);
6091 			hdr_abd = hdr->b_l1hdr.b_pabd;
6092 
6093 			if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
6094 				zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6095 			}
6096 
6097 			/*
6098 			 * For authenticated bp's, we do not ask the ZIO layer
6099 			 * to authenticate them since this will cause the entire
6100 			 * IO to fail if the key isn't loaded. Instead, we
6101 			 * defer authentication until arc_buf_fill(), which will
6102 			 * verify the data when the key is available.
6103 			 */
6104 			if (BP_IS_AUTHENTICATED(bp))
6105 				zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
6106 		}
6107 
6108 		if (*arc_flags & ARC_FLAG_PREFETCH &&
6109 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))
6110 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6111 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6112 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
6113 		if (*arc_flags & ARC_FLAG_L2CACHE)
6114 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6115 		if (BP_IS_AUTHENTICATED(bp))
6116 			arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6117 		if (BP_GET_LEVEL(bp) > 0)
6118 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
6119 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
6120 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
6121 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
6122 
6123 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
6124 		acb->acb_done = done;
6125 		acb->acb_private = private;
6126 		acb->acb_compressed = compressed_read;
6127 		acb->acb_encrypted = encrypted_read;
6128 		acb->acb_noauth = noauth_read;
6129 		acb->acb_zb = *zb;
6130 
6131 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6132 		hdr->b_l1hdr.b_acb = acb;
6133 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6134 
6135 		if (HDR_HAS_L2HDR(hdr) &&
6136 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
6137 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
6138 			addr = hdr->b_l2hdr.b_daddr;
6139 			/*
6140 			 * Lock out L2ARC device removal.
6141 			 */
6142 			if (vdev_is_dead(vd) ||
6143 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6144 				vd = NULL;
6145 		}
6146 
6147 		/*
6148 		 * We count both async reads and scrub IOs as asynchronous so
6149 		 * that both can be upgraded in the event of a cache hit while
6150 		 * the read IO is still in-flight.
6151 		 */
6152 		if (priority == ZIO_PRIORITY_ASYNC_READ ||
6153 		    priority == ZIO_PRIORITY_SCRUB)
6154 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6155 		else
6156 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6157 
6158 		/*
6159 		 * At this point, we have a level 1 cache miss or a blkptr
6160 		 * with embedded data.  Try again in L2ARC if possible.
6161 		 */
6162 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6163 
6164 		/*
6165 		 * Skip ARC stat bump for block pointers with embedded
6166 		 * data. The data are read from the blkptr itself via
6167 		 * decode_embedded_bp_compressed().
6168 		 */
6169 		if (!embedded_bp) {
6170 			DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr,
6171 			    blkptr_t *, bp, uint64_t, lsize,
6172 			    zbookmark_phys_t *, zb);
6173 			ARCSTAT_BUMP(arcstat_misses);
6174 			ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
6175 			    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data,
6176 			    metadata, misses);
6177 		}
6178 
6179 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
6180 			/*
6181 			 * Read from the L2ARC if the following are true:
6182 			 * 1. The L2ARC vdev was previously cached.
6183 			 * 2. This buffer still has L2ARC metadata.
6184 			 * 3. This buffer isn't currently writing to the L2ARC.
6185 			 * 4. The L2ARC entry wasn't evicted, which may
6186 			 *    also have invalidated the vdev.
6187 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
6188 			 */
6189 			if (HDR_HAS_L2HDR(hdr) &&
6190 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
6191 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
6192 				l2arc_read_callback_t *cb;
6193 				abd_t *abd;
6194 				uint64_t asize;
6195 
6196 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6197 				ARCSTAT_BUMP(arcstat_l2_hits);
6198 				atomic_inc_32(&hdr->b_l2hdr.b_hits);
6199 
6200 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6201 				    KM_SLEEP);
6202 				cb->l2rcb_hdr = hdr;
6203 				cb->l2rcb_bp = *bp;
6204 				cb->l2rcb_zb = *zb;
6205 				cb->l2rcb_flags = zio_flags;
6206 
6207 				/*
6208 				 * When Compressed ARC is disabled, but the
6209 				 * L2ARC block is compressed, arc_hdr_size()
6210 				 * will have returned LSIZE rather than PSIZE.
6211 				 */
6212 				if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
6213 				    !HDR_COMPRESSION_ENABLED(hdr) &&
6214 				    HDR_GET_PSIZE(hdr) != 0) {
6215 					size = HDR_GET_PSIZE(hdr);
6216 				}
6217 
6218 				asize = vdev_psize_to_asize(vd, size);
6219 				if (asize != size) {
6220 					abd = abd_alloc_for_io(asize,
6221 					    HDR_ISTYPE_METADATA(hdr));
6222 					cb->l2rcb_abd = abd;
6223 				} else {
6224 					abd = hdr_abd;
6225 				}
6226 
6227 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6228 				    addr + asize <= vd->vdev_psize -
6229 				    VDEV_LABEL_END_SIZE);
6230 
6231 				/*
6232 				 * l2arc read.  The SCL_L2ARC lock will be
6233 				 * released by l2arc_read_done().
6234 				 * Issue a null zio if the underlying buffer
6235 				 * was squashed to zero size by compression.
6236 				 */
6237 				ASSERT3U(arc_hdr_get_compress(hdr), !=,
6238 				    ZIO_COMPRESS_EMPTY);
6239 				rzio = zio_read_phys(pio, vd, addr,
6240 				    asize, abd,
6241 				    ZIO_CHECKSUM_OFF,
6242 				    l2arc_read_done, cb, priority,
6243 				    zio_flags | ZIO_FLAG_DONT_CACHE |
6244 				    ZIO_FLAG_CANFAIL |
6245 				    ZIO_FLAG_DONT_PROPAGATE |
6246 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
6247 				acb->acb_zio_head = rzio;
6248 
6249 				if (hash_lock != NULL)
6250 					mutex_exit(hash_lock);
6251 
6252 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6253 				    zio_t *, rzio);
6254 				ARCSTAT_INCR(arcstat_l2_read_bytes,
6255 				    HDR_GET_PSIZE(hdr));
6256 
6257 				if (*arc_flags & ARC_FLAG_NOWAIT) {
6258 					zio_nowait(rzio);
6259 					goto out;
6260 				}
6261 
6262 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
6263 				if (zio_wait(rzio) == 0)
6264 					goto out;
6265 
6266 				/* l2arc read error; goto zio_read() */
6267 				if (hash_lock != NULL)
6268 					mutex_enter(hash_lock);
6269 			} else {
6270 				DTRACE_PROBE1(l2arc__miss,
6271 				    arc_buf_hdr_t *, hdr);
6272 				ARCSTAT_BUMP(arcstat_l2_misses);
6273 				if (HDR_L2_WRITING(hdr))
6274 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
6275 				spa_config_exit(spa, SCL_L2ARC, vd);
6276 			}
6277 		} else {
6278 			if (vd != NULL)
6279 				spa_config_exit(spa, SCL_L2ARC, vd);
6280 			/*
6281 			 * Skip ARC stat bump for block pointers with
6282 			 * embedded data. The data are read from the blkptr
6283 			 * itself via decode_embedded_bp_compressed().
6284 			 */
6285 			if (l2arc_ndev != 0 && !embedded_bp) {
6286 				DTRACE_PROBE1(l2arc__miss,
6287 				    arc_buf_hdr_t *, hdr);
6288 				ARCSTAT_BUMP(arcstat_l2_misses);
6289 			}
6290 		}
6291 
6292 		rzio = zio_read(pio, spa, bp, hdr_abd, size,
6293 		    arc_read_done, hdr, priority, zio_flags, zb);
6294 		acb->acb_zio_head = rzio;
6295 
6296 		if (hash_lock != NULL)
6297 			mutex_exit(hash_lock);
6298 
6299 		if (*arc_flags & ARC_FLAG_WAIT) {
6300 			rc = zio_wait(rzio);
6301 			goto out;
6302 		}
6303 
6304 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6305 		zio_nowait(rzio);
6306 	}
6307 
6308 out:
6309 	/* embedded bps don't actually go to disk */
6310 	if (!embedded_bp)
6311 		spa_read_history_add(spa, zb, *arc_flags);
6312 	spl_fstrans_unmark(cookie);
6313 	return (rc);
6314 }
6315 
6316 arc_prune_t *
6317 arc_add_prune_callback(arc_prune_func_t *func, void *private)
6318 {
6319 	arc_prune_t *p;
6320 
6321 	p = kmem_alloc(sizeof (*p), KM_SLEEP);
6322 	p->p_pfunc = func;
6323 	p->p_private = private;
6324 	list_link_init(&p->p_node);
6325 	zfs_refcount_create(&p->p_refcnt);
6326 
6327 	mutex_enter(&arc_prune_mtx);
6328 	zfs_refcount_add(&p->p_refcnt, &arc_prune_list);
6329 	list_insert_head(&arc_prune_list, p);
6330 	mutex_exit(&arc_prune_mtx);
6331 
6332 	return (p);
6333 }
6334 
6335 void
6336 arc_remove_prune_callback(arc_prune_t *p)
6337 {
6338 	boolean_t wait = B_FALSE;
6339 	mutex_enter(&arc_prune_mtx);
6340 	list_remove(&arc_prune_list, p);
6341 	if (zfs_refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
6342 		wait = B_TRUE;
6343 	mutex_exit(&arc_prune_mtx);
6344 
6345 	/* wait for arc_prune_task to finish */
6346 	if (wait)
6347 		taskq_wait_outstanding(arc_prune_taskq, 0);
6348 	ASSERT0(zfs_refcount_count(&p->p_refcnt));
6349 	zfs_refcount_destroy(&p->p_refcnt);
6350 	kmem_free(p, sizeof (*p));
6351 }
6352 
6353 /*
6354  * Notify the arc that a block was freed, and thus will never be used again.
6355  */
6356 void
6357 arc_freed(spa_t *spa, const blkptr_t *bp)
6358 {
6359 	arc_buf_hdr_t *hdr;
6360 	kmutex_t *hash_lock;
6361 	uint64_t guid = spa_load_guid(spa);
6362 
6363 	ASSERT(!BP_IS_EMBEDDED(bp));
6364 
6365 	hdr = buf_hash_find(guid, bp, &hash_lock);
6366 	if (hdr == NULL)
6367 		return;
6368 
6369 	/*
6370 	 * We might be trying to free a block that is still doing I/O
6371 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6372 	 * dmu_sync-ed block). If this block is being prefetched, then it
6373 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6374 	 * until the I/O completes. A block may also have a reference if it is
6375 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6376 	 * have written the new block to its final resting place on disk but
6377 	 * without the dedup flag set. This would have left the hdr in the MRU
6378 	 * state and discoverable. When the txg finally syncs it detects that
6379 	 * the block was overridden in open context and issues an override I/O.
6380 	 * Since this is a dedup block, the override I/O will determine if the
6381 	 * block is already in the DDT. If so, then it will replace the io_bp
6382 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
6383 	 * reaches the done callback, dbuf_write_override_done, it will
6384 	 * check to see if the io_bp and io_bp_override are identical.
6385 	 * If they are not, then it indicates that the bp was replaced with
6386 	 * the bp in the DDT and the override bp is freed. This allows
6387 	 * us to arrive here with a reference on a block that is being
6388 	 * freed. So if we have an I/O in progress, or a reference to
6389 	 * this hdr, then we don't destroy the hdr.
6390 	 */
6391 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6392 	    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6393 		arc_change_state(arc_anon, hdr, hash_lock);
6394 		arc_hdr_destroy(hdr);
6395 		mutex_exit(hash_lock);
6396 	} else {
6397 		mutex_exit(hash_lock);
6398 	}
6399 
6400 }
6401 
6402 /*
6403  * Release this buffer from the cache, making it an anonymous buffer.  This
6404  * must be done after a read and prior to modifying the buffer contents.
6405  * If the buffer has more than one reference, we must make
6406  * a new hdr for the buffer.
6407  */
6408 void
6409 arc_release(arc_buf_t *buf, void *tag)
6410 {
6411 	arc_buf_hdr_t *hdr = buf->b_hdr;
6412 
6413 	/*
6414 	 * It would be nice to assert that if its DMU metadata (level >
6415 	 * 0 || it's the dnode file), then it must be syncing context.
6416 	 * But we don't know that information at this level.
6417 	 */
6418 
6419 	mutex_enter(&buf->b_evict_lock);
6420 
6421 	ASSERT(HDR_HAS_L1HDR(hdr));
6422 
6423 	/*
6424 	 * We don't grab the hash lock prior to this check, because if
6425 	 * the buffer's header is in the arc_anon state, it won't be
6426 	 * linked into the hash table.
6427 	 */
6428 	if (hdr->b_l1hdr.b_state == arc_anon) {
6429 		mutex_exit(&buf->b_evict_lock);
6430 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6431 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
6432 		ASSERT(!HDR_HAS_L2HDR(hdr));
6433 		ASSERT(HDR_EMPTY(hdr));
6434 
6435 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6436 		ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6437 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6438 
6439 		hdr->b_l1hdr.b_arc_access = 0;
6440 
6441 		/*
6442 		 * If the buf is being overridden then it may already
6443 		 * have a hdr that is not empty.
6444 		 */
6445 		buf_discard_identity(hdr);
6446 		arc_buf_thaw(buf);
6447 
6448 		return;
6449 	}
6450 
6451 	kmutex_t *hash_lock = HDR_LOCK(hdr);
6452 	mutex_enter(hash_lock);
6453 
6454 	/*
6455 	 * This assignment is only valid as long as the hash_lock is
6456 	 * held, we must be careful not to reference state or the
6457 	 * b_state field after dropping the lock.
6458 	 */
6459 	arc_state_t *state = hdr->b_l1hdr.b_state;
6460 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6461 	ASSERT3P(state, !=, arc_anon);
6462 
6463 	/* this buffer is not on any list */
6464 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6465 
6466 	if (HDR_HAS_L2HDR(hdr)) {
6467 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6468 
6469 		/*
6470 		 * We have to recheck this conditional again now that
6471 		 * we're holding the l2ad_mtx to prevent a race with
6472 		 * another thread which might be concurrently calling
6473 		 * l2arc_evict(). In that case, l2arc_evict() might have
6474 		 * destroyed the header's L2 portion as we were waiting
6475 		 * to acquire the l2ad_mtx.
6476 		 */
6477 		if (HDR_HAS_L2HDR(hdr))
6478 			arc_hdr_l2hdr_destroy(hdr);
6479 
6480 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6481 	}
6482 
6483 	/*
6484 	 * Do we have more than one buf?
6485 	 */
6486 	if (hdr->b_l1hdr.b_bufcnt > 1) {
6487 		arc_buf_hdr_t *nhdr;
6488 		uint64_t spa = hdr->b_spa;
6489 		uint64_t psize = HDR_GET_PSIZE(hdr);
6490 		uint64_t lsize = HDR_GET_LSIZE(hdr);
6491 		boolean_t protected = HDR_PROTECTED(hdr);
6492 		enum zio_compress compress = arc_hdr_get_compress(hdr);
6493 		arc_buf_contents_t type = arc_buf_type(hdr);
6494 		VERIFY3U(hdr->b_type, ==, type);
6495 
6496 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6497 		(void) remove_reference(hdr, hash_lock, tag);
6498 
6499 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6500 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6501 			ASSERT(ARC_BUF_LAST(buf));
6502 		}
6503 
6504 		/*
6505 		 * Pull the data off of this hdr and attach it to
6506 		 * a new anonymous hdr. Also find the last buffer
6507 		 * in the hdr's buffer list.
6508 		 */
6509 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6510 		ASSERT3P(lastbuf, !=, NULL);
6511 
6512 		/*
6513 		 * If the current arc_buf_t and the hdr are sharing their data
6514 		 * buffer, then we must stop sharing that block.
6515 		 */
6516 		if (arc_buf_is_shared(buf)) {
6517 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6518 			VERIFY(!arc_buf_is_shared(lastbuf));
6519 
6520 			/*
6521 			 * First, sever the block sharing relationship between
6522 			 * buf and the arc_buf_hdr_t.
6523 			 */
6524 			arc_unshare_buf(hdr, buf);
6525 
6526 			/*
6527 			 * Now we need to recreate the hdr's b_pabd. Since we
6528 			 * have lastbuf handy, we try to share with it, but if
6529 			 * we can't then we allocate a new b_pabd and copy the
6530 			 * data from buf into it.
6531 			 */
6532 			if (arc_can_share(hdr, lastbuf)) {
6533 				arc_share_buf(hdr, lastbuf);
6534 			} else {
6535 				arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6536 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6537 				    buf->b_data, psize);
6538 			}
6539 			VERIFY3P(lastbuf->b_data, !=, NULL);
6540 		} else if (HDR_SHARED_DATA(hdr)) {
6541 			/*
6542 			 * Uncompressed shared buffers are always at the end
6543 			 * of the list. Compressed buffers don't have the
6544 			 * same requirements. This makes it hard to
6545 			 * simply assert that the lastbuf is shared so
6546 			 * we rely on the hdr's compression flags to determine
6547 			 * if we have a compressed, shared buffer.
6548 			 */
6549 			ASSERT(arc_buf_is_shared(lastbuf) ||
6550 			    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
6551 			ASSERT(!ARC_BUF_SHARED(buf));
6552 		}
6553 
6554 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
6555 		ASSERT3P(state, !=, arc_l2c_only);
6556 
6557 		(void) zfs_refcount_remove_many(&state->arcs_size,
6558 		    arc_buf_size(buf), buf);
6559 
6560 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6561 			ASSERT3P(state, !=, arc_l2c_only);
6562 			(void) zfs_refcount_remove_many(
6563 			    &state->arcs_esize[type],
6564 			    arc_buf_size(buf), buf);
6565 		}
6566 
6567 		hdr->b_l1hdr.b_bufcnt -= 1;
6568 		if (ARC_BUF_ENCRYPTED(buf))
6569 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
6570 
6571 		arc_cksum_verify(buf);
6572 		arc_buf_unwatch(buf);
6573 
6574 		/* if this is the last uncompressed buf free the checksum */
6575 		if (!arc_hdr_has_uncompressed_buf(hdr))
6576 			arc_cksum_free(hdr);
6577 
6578 		mutex_exit(hash_lock);
6579 
6580 		/*
6581 		 * Allocate a new hdr. The new hdr will contain a b_pabd
6582 		 * buffer which will be freed in arc_write().
6583 		 */
6584 		nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6585 		    compress, hdr->b_complevel, type, HDR_HAS_RABD(hdr));
6586 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6587 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6588 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6589 		VERIFY3U(nhdr->b_type, ==, type);
6590 		ASSERT(!HDR_SHARED_DATA(nhdr));
6591 
6592 		nhdr->b_l1hdr.b_buf = buf;
6593 		nhdr->b_l1hdr.b_bufcnt = 1;
6594 		if (ARC_BUF_ENCRYPTED(buf))
6595 			nhdr->b_crypt_hdr.b_ebufcnt = 1;
6596 		nhdr->b_l1hdr.b_mru_hits = 0;
6597 		nhdr->b_l1hdr.b_mru_ghost_hits = 0;
6598 		nhdr->b_l1hdr.b_mfu_hits = 0;
6599 		nhdr->b_l1hdr.b_mfu_ghost_hits = 0;
6600 		nhdr->b_l1hdr.b_l2_hits = 0;
6601 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6602 		buf->b_hdr = nhdr;
6603 
6604 		mutex_exit(&buf->b_evict_lock);
6605 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
6606 		    arc_buf_size(buf), buf);
6607 	} else {
6608 		mutex_exit(&buf->b_evict_lock);
6609 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6610 		/* protected by hash lock, or hdr is on arc_anon */
6611 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6612 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6613 		hdr->b_l1hdr.b_mru_hits = 0;
6614 		hdr->b_l1hdr.b_mru_ghost_hits = 0;
6615 		hdr->b_l1hdr.b_mfu_hits = 0;
6616 		hdr->b_l1hdr.b_mfu_ghost_hits = 0;
6617 		hdr->b_l1hdr.b_l2_hits = 0;
6618 		arc_change_state(arc_anon, hdr, hash_lock);
6619 		hdr->b_l1hdr.b_arc_access = 0;
6620 
6621 		mutex_exit(hash_lock);
6622 		buf_discard_identity(hdr);
6623 		arc_buf_thaw(buf);
6624 	}
6625 }
6626 
6627 int
6628 arc_released(arc_buf_t *buf)
6629 {
6630 	int released;
6631 
6632 	mutex_enter(&buf->b_evict_lock);
6633 	released = (buf->b_data != NULL &&
6634 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
6635 	mutex_exit(&buf->b_evict_lock);
6636 	return (released);
6637 }
6638 
6639 #ifdef ZFS_DEBUG
6640 int
6641 arc_referenced(arc_buf_t *buf)
6642 {
6643 	int referenced;
6644 
6645 	mutex_enter(&buf->b_evict_lock);
6646 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6647 	mutex_exit(&buf->b_evict_lock);
6648 	return (referenced);
6649 }
6650 #endif
6651 
6652 static void
6653 arc_write_ready(zio_t *zio)
6654 {
6655 	arc_write_callback_t *callback = zio->io_private;
6656 	arc_buf_t *buf = callback->awcb_buf;
6657 	arc_buf_hdr_t *hdr = buf->b_hdr;
6658 	blkptr_t *bp = zio->io_bp;
6659 	uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6660 	fstrans_cookie_t cookie = spl_fstrans_mark();
6661 
6662 	ASSERT(HDR_HAS_L1HDR(hdr));
6663 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6664 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6665 
6666 	/*
6667 	 * If we're reexecuting this zio because the pool suspended, then
6668 	 * cleanup any state that was previously set the first time the
6669 	 * callback was invoked.
6670 	 */
6671 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6672 		arc_cksum_free(hdr);
6673 		arc_buf_unwatch(buf);
6674 		if (hdr->b_l1hdr.b_pabd != NULL) {
6675 			if (arc_buf_is_shared(buf)) {
6676 				arc_unshare_buf(hdr, buf);
6677 			} else {
6678 				arc_hdr_free_abd(hdr, B_FALSE);
6679 			}
6680 		}
6681 
6682 		if (HDR_HAS_RABD(hdr))
6683 			arc_hdr_free_abd(hdr, B_TRUE);
6684 	}
6685 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6686 	ASSERT(!HDR_HAS_RABD(hdr));
6687 	ASSERT(!HDR_SHARED_DATA(hdr));
6688 	ASSERT(!arc_buf_is_shared(buf));
6689 
6690 	callback->awcb_ready(zio, buf, callback->awcb_private);
6691 
6692 	if (HDR_IO_IN_PROGRESS(hdr))
6693 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6694 
6695 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6696 
6697 	if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6698 		hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6699 
6700 	if (BP_IS_PROTECTED(bp)) {
6701 		/* ZIL blocks are written through zio_rewrite */
6702 		ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6703 		ASSERT(HDR_PROTECTED(hdr));
6704 
6705 		if (BP_SHOULD_BYTESWAP(bp)) {
6706 			if (BP_GET_LEVEL(bp) > 0) {
6707 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6708 			} else {
6709 				hdr->b_l1hdr.b_byteswap =
6710 				    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6711 			}
6712 		} else {
6713 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6714 		}
6715 
6716 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6717 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6718 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6719 		    hdr->b_crypt_hdr.b_iv);
6720 		zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6721 	}
6722 
6723 	/*
6724 	 * If this block was written for raw encryption but the zio layer
6725 	 * ended up only authenticating it, adjust the buffer flags now.
6726 	 */
6727 	if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6728 		arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6729 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6730 		if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6731 			buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6732 	} else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6733 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6734 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6735 	}
6736 
6737 	/* this must be done after the buffer flags are adjusted */
6738 	arc_cksum_compute(buf);
6739 
6740 	enum zio_compress compress;
6741 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6742 		compress = ZIO_COMPRESS_OFF;
6743 	} else {
6744 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6745 		compress = BP_GET_COMPRESS(bp);
6746 	}
6747 	HDR_SET_PSIZE(hdr, psize);
6748 	arc_hdr_set_compress(hdr, compress);
6749 	hdr->b_complevel = zio->io_prop.zp_complevel;
6750 
6751 	if (zio->io_error != 0 || psize == 0)
6752 		goto out;
6753 
6754 	/*
6755 	 * Fill the hdr with data. If the buffer is encrypted we have no choice
6756 	 * but to copy the data into b_radb. If the hdr is compressed, the data
6757 	 * we want is available from the zio, otherwise we can take it from
6758 	 * the buf.
6759 	 *
6760 	 * We might be able to share the buf's data with the hdr here. However,
6761 	 * doing so would cause the ARC to be full of linear ABDs if we write a
6762 	 * lot of shareable data. As a compromise, we check whether scattered
6763 	 * ABDs are allowed, and assume that if they are then the user wants
6764 	 * the ARC to be primarily filled with them regardless of the data being
6765 	 * written. Therefore, if they're allowed then we allocate one and copy
6766 	 * the data into it; otherwise, we share the data directly if we can.
6767 	 */
6768 	if (ARC_BUF_ENCRYPTED(buf)) {
6769 		ASSERT3U(psize, >, 0);
6770 		ASSERT(ARC_BUF_COMPRESSED(buf));
6771 		arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6772 		abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6773 	} else if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6774 		/*
6775 		 * Ideally, we would always copy the io_abd into b_pabd, but the
6776 		 * user may have disabled compressed ARC, thus we must check the
6777 		 * hdr's compression setting rather than the io_bp's.
6778 		 */
6779 		if (BP_IS_ENCRYPTED(bp)) {
6780 			ASSERT3U(psize, >, 0);
6781 			arc_hdr_alloc_abd(hdr,
6782 			    ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6783 			abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6784 		} else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6785 		    !ARC_BUF_COMPRESSED(buf)) {
6786 			ASSERT3U(psize, >, 0);
6787 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6788 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6789 		} else {
6790 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6791 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6792 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6793 			    arc_buf_size(buf));
6794 		}
6795 	} else {
6796 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6797 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6798 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6799 
6800 		arc_share_buf(hdr, buf);
6801 	}
6802 
6803 out:
6804 	arc_hdr_verify(hdr, bp);
6805 	spl_fstrans_unmark(cookie);
6806 }
6807 
6808 static void
6809 arc_write_children_ready(zio_t *zio)
6810 {
6811 	arc_write_callback_t *callback = zio->io_private;
6812 	arc_buf_t *buf = callback->awcb_buf;
6813 
6814 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
6815 }
6816 
6817 /*
6818  * The SPA calls this callback for each physical write that happens on behalf
6819  * of a logical write.  See the comment in dbuf_write_physdone() for details.
6820  */
6821 static void
6822 arc_write_physdone(zio_t *zio)
6823 {
6824 	arc_write_callback_t *cb = zio->io_private;
6825 	if (cb->awcb_physdone != NULL)
6826 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6827 }
6828 
6829 static void
6830 arc_write_done(zio_t *zio)
6831 {
6832 	arc_write_callback_t *callback = zio->io_private;
6833 	arc_buf_t *buf = callback->awcb_buf;
6834 	arc_buf_hdr_t *hdr = buf->b_hdr;
6835 
6836 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6837 
6838 	if (zio->io_error == 0) {
6839 		arc_hdr_verify(hdr, zio->io_bp);
6840 
6841 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6842 			buf_discard_identity(hdr);
6843 		} else {
6844 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6845 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6846 		}
6847 	} else {
6848 		ASSERT(HDR_EMPTY(hdr));
6849 	}
6850 
6851 	/*
6852 	 * If the block to be written was all-zero or compressed enough to be
6853 	 * embedded in the BP, no write was performed so there will be no
6854 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
6855 	 * (and uncached).
6856 	 */
6857 	if (!HDR_EMPTY(hdr)) {
6858 		arc_buf_hdr_t *exists;
6859 		kmutex_t *hash_lock;
6860 
6861 		ASSERT3U(zio->io_error, ==, 0);
6862 
6863 		arc_cksum_verify(buf);
6864 
6865 		exists = buf_hash_insert(hdr, &hash_lock);
6866 		if (exists != NULL) {
6867 			/*
6868 			 * This can only happen if we overwrite for
6869 			 * sync-to-convergence, because we remove
6870 			 * buffers from the hash table when we arc_free().
6871 			 */
6872 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6873 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6874 					panic("bad overwrite, hdr=%p exists=%p",
6875 					    (void *)hdr, (void *)exists);
6876 				ASSERT(zfs_refcount_is_zero(
6877 				    &exists->b_l1hdr.b_refcnt));
6878 				arc_change_state(arc_anon, exists, hash_lock);
6879 				arc_hdr_destroy(exists);
6880 				mutex_exit(hash_lock);
6881 				exists = buf_hash_insert(hdr, &hash_lock);
6882 				ASSERT3P(exists, ==, NULL);
6883 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6884 				/* nopwrite */
6885 				ASSERT(zio->io_prop.zp_nopwrite);
6886 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6887 					panic("bad nopwrite, hdr=%p exists=%p",
6888 					    (void *)hdr, (void *)exists);
6889 			} else {
6890 				/* Dedup */
6891 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6892 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6893 				ASSERT(BP_GET_DEDUP(zio->io_bp));
6894 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6895 			}
6896 		}
6897 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6898 		/* if it's not anon, we are doing a scrub */
6899 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6900 			arc_access(hdr, hash_lock);
6901 		mutex_exit(hash_lock);
6902 	} else {
6903 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6904 	}
6905 
6906 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6907 	callback->awcb_done(zio, buf, callback->awcb_private);
6908 
6909 	abd_put(zio->io_abd);
6910 	kmem_free(callback, sizeof (arc_write_callback_t));
6911 }
6912 
6913 zio_t *
6914 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
6915     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc,
6916     const zio_prop_t *zp, arc_write_done_func_t *ready,
6917     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6918     arc_write_done_func_t *done, void *private, zio_priority_t priority,
6919     int zio_flags, const zbookmark_phys_t *zb)
6920 {
6921 	arc_buf_hdr_t *hdr = buf->b_hdr;
6922 	arc_write_callback_t *callback;
6923 	zio_t *zio;
6924 	zio_prop_t localprop = *zp;
6925 
6926 	ASSERT3P(ready, !=, NULL);
6927 	ASSERT3P(done, !=, NULL);
6928 	ASSERT(!HDR_IO_ERROR(hdr));
6929 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6930 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6931 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6932 	if (l2arc)
6933 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6934 
6935 	if (ARC_BUF_ENCRYPTED(buf)) {
6936 		ASSERT(ARC_BUF_COMPRESSED(buf));
6937 		localprop.zp_encrypt = B_TRUE;
6938 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6939 		localprop.zp_complevel = hdr->b_complevel;
6940 		localprop.zp_byteorder =
6941 		    (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
6942 		    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
6943 		bcopy(hdr->b_crypt_hdr.b_salt, localprop.zp_salt,
6944 		    ZIO_DATA_SALT_LEN);
6945 		bcopy(hdr->b_crypt_hdr.b_iv, localprop.zp_iv,
6946 		    ZIO_DATA_IV_LEN);
6947 		bcopy(hdr->b_crypt_hdr.b_mac, localprop.zp_mac,
6948 		    ZIO_DATA_MAC_LEN);
6949 		if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
6950 			localprop.zp_nopwrite = B_FALSE;
6951 			localprop.zp_copies =
6952 			    MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
6953 		}
6954 		zio_flags |= ZIO_FLAG_RAW;
6955 	} else if (ARC_BUF_COMPRESSED(buf)) {
6956 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6957 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6958 		localprop.zp_complevel = hdr->b_complevel;
6959 		zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6960 	}
6961 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6962 	callback->awcb_ready = ready;
6963 	callback->awcb_children_ready = children_ready;
6964 	callback->awcb_physdone = physdone;
6965 	callback->awcb_done = done;
6966 	callback->awcb_private = private;
6967 	callback->awcb_buf = buf;
6968 
6969 	/*
6970 	 * The hdr's b_pabd is now stale, free it now. A new data block
6971 	 * will be allocated when the zio pipeline calls arc_write_ready().
6972 	 */
6973 	if (hdr->b_l1hdr.b_pabd != NULL) {
6974 		/*
6975 		 * If the buf is currently sharing the data block with
6976 		 * the hdr then we need to break that relationship here.
6977 		 * The hdr will remain with a NULL data pointer and the
6978 		 * buf will take sole ownership of the block.
6979 		 */
6980 		if (arc_buf_is_shared(buf)) {
6981 			arc_unshare_buf(hdr, buf);
6982 		} else {
6983 			arc_hdr_free_abd(hdr, B_FALSE);
6984 		}
6985 		VERIFY3P(buf->b_data, !=, NULL);
6986 	}
6987 
6988 	if (HDR_HAS_RABD(hdr))
6989 		arc_hdr_free_abd(hdr, B_TRUE);
6990 
6991 	if (!(zio_flags & ZIO_FLAG_RAW))
6992 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6993 
6994 	ASSERT(!arc_buf_is_shared(buf));
6995 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6996 
6997 	zio = zio_write(pio, spa, txg, bp,
6998 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6999 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
7000 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
7001 	    arc_write_physdone, arc_write_done, callback,
7002 	    priority, zio_flags, zb);
7003 
7004 	return (zio);
7005 }
7006 
7007 void
7008 arc_tempreserve_clear(uint64_t reserve)
7009 {
7010 	atomic_add_64(&arc_tempreserve, -reserve);
7011 	ASSERT((int64_t)arc_tempreserve >= 0);
7012 }
7013 
7014 int
7015 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
7016 {
7017 	int error;
7018 	uint64_t anon_size;
7019 
7020 	if (!arc_no_grow &&
7021 	    reserve > arc_c/4 &&
7022 	    reserve * 4 > (2ULL << SPA_MAXBLOCKSHIFT))
7023 		arc_c = MIN(arc_c_max, reserve * 4);
7024 
7025 	/*
7026 	 * Throttle when the calculated memory footprint for the TXG
7027 	 * exceeds the target ARC size.
7028 	 */
7029 	if (reserve > arc_c) {
7030 		DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
7031 		return (SET_ERROR(ERESTART));
7032 	}
7033 
7034 	/*
7035 	 * Don't count loaned bufs as in flight dirty data to prevent long
7036 	 * network delays from blocking transactions that are ready to be
7037 	 * assigned to a txg.
7038 	 */
7039 
7040 	/* assert that it has not wrapped around */
7041 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
7042 
7043 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
7044 	    arc_loaned_bytes), 0);
7045 
7046 	/*
7047 	 * Writes will, almost always, require additional memory allocations
7048 	 * in order to compress/encrypt/etc the data.  We therefore need to
7049 	 * make sure that there is sufficient available memory for this.
7050 	 */
7051 	error = arc_memory_throttle(spa, reserve, txg);
7052 	if (error != 0)
7053 		return (error);
7054 
7055 	/*
7056 	 * Throttle writes when the amount of dirty data in the cache
7057 	 * gets too large.  We try to keep the cache less than half full
7058 	 * of dirty blocks so that our sync times don't grow too large.
7059 	 *
7060 	 * In the case of one pool being built on another pool, we want
7061 	 * to make sure we don't end up throttling the lower (backing)
7062 	 * pool when the upper pool is the majority contributor to dirty
7063 	 * data. To insure we make forward progress during throttling, we
7064 	 * also check the current pool's net dirty data and only throttle
7065 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
7066 	 * data in the cache.
7067 	 *
7068 	 * Note: if two requests come in concurrently, we might let them
7069 	 * both succeed, when one of them should fail.  Not a huge deal.
7070 	 */
7071 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
7072 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
7073 
7074 	if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
7075 	    anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
7076 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
7077 #ifdef ZFS_DEBUG
7078 		uint64_t meta_esize = zfs_refcount_count(
7079 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7080 		uint64_t data_esize =
7081 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7082 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
7083 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
7084 		    arc_tempreserve >> 10, meta_esize >> 10,
7085 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
7086 #endif
7087 		DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
7088 		return (SET_ERROR(ERESTART));
7089 	}
7090 	atomic_add_64(&arc_tempreserve, reserve);
7091 	return (0);
7092 }
7093 
7094 static void
7095 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
7096     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
7097 {
7098 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
7099 	evict_data->value.ui64 =
7100 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
7101 	evict_metadata->value.ui64 =
7102 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
7103 }
7104 
7105 static int
7106 arc_kstat_update(kstat_t *ksp, int rw)
7107 {
7108 	arc_stats_t *as = ksp->ks_data;
7109 
7110 	if (rw == KSTAT_WRITE) {
7111 		return (SET_ERROR(EACCES));
7112 	} else {
7113 		arc_kstat_update_state(arc_anon,
7114 		    &as->arcstat_anon_size,
7115 		    &as->arcstat_anon_evictable_data,
7116 		    &as->arcstat_anon_evictable_metadata);
7117 		arc_kstat_update_state(arc_mru,
7118 		    &as->arcstat_mru_size,
7119 		    &as->arcstat_mru_evictable_data,
7120 		    &as->arcstat_mru_evictable_metadata);
7121 		arc_kstat_update_state(arc_mru_ghost,
7122 		    &as->arcstat_mru_ghost_size,
7123 		    &as->arcstat_mru_ghost_evictable_data,
7124 		    &as->arcstat_mru_ghost_evictable_metadata);
7125 		arc_kstat_update_state(arc_mfu,
7126 		    &as->arcstat_mfu_size,
7127 		    &as->arcstat_mfu_evictable_data,
7128 		    &as->arcstat_mfu_evictable_metadata);
7129 		arc_kstat_update_state(arc_mfu_ghost,
7130 		    &as->arcstat_mfu_ghost_size,
7131 		    &as->arcstat_mfu_ghost_evictable_data,
7132 		    &as->arcstat_mfu_ghost_evictable_metadata);
7133 
7134 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
7135 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
7136 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
7137 		ARCSTAT(arcstat_metadata_size) =
7138 		    aggsum_value(&astat_metadata_size);
7139 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
7140 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
7141 		ARCSTAT(arcstat_dbuf_size) = aggsum_value(&astat_dbuf_size);
7142 #if defined(COMPAT_FREEBSD11)
7143 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_bonus_size) +
7144 		    aggsum_value(&astat_dnode_size) +
7145 		    aggsum_value(&astat_dbuf_size);
7146 #endif
7147 		ARCSTAT(arcstat_dnode_size) = aggsum_value(&astat_dnode_size);
7148 		ARCSTAT(arcstat_bonus_size) = aggsum_value(&astat_bonus_size);
7149 		ARCSTAT(arcstat_abd_chunk_waste_size) =
7150 		    aggsum_value(&astat_abd_chunk_waste_size);
7151 
7152 		as->arcstat_memory_all_bytes.value.ui64 =
7153 		    arc_all_memory();
7154 		as->arcstat_memory_free_bytes.value.ui64 =
7155 		    arc_free_memory();
7156 		as->arcstat_memory_available_bytes.value.i64 =
7157 		    arc_available_memory();
7158 	}
7159 
7160 	return (0);
7161 }
7162 
7163 /*
7164  * This function *must* return indices evenly distributed between all
7165  * sublists of the multilist. This is needed due to how the ARC eviction
7166  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
7167  * distributed between all sublists and uses this assumption when
7168  * deciding which sublist to evict from and how much to evict from it.
7169  */
7170 static unsigned int
7171 arc_state_multilist_index_func(multilist_t *ml, void *obj)
7172 {
7173 	arc_buf_hdr_t *hdr = obj;
7174 
7175 	/*
7176 	 * We rely on b_dva to generate evenly distributed index
7177 	 * numbers using buf_hash below. So, as an added precaution,
7178 	 * let's make sure we never add empty buffers to the arc lists.
7179 	 */
7180 	ASSERT(!HDR_EMPTY(hdr));
7181 
7182 	/*
7183 	 * The assumption here, is the hash value for a given
7184 	 * arc_buf_hdr_t will remain constant throughout its lifetime
7185 	 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
7186 	 * Thus, we don't need to store the header's sublist index
7187 	 * on insertion, as this index can be recalculated on removal.
7188 	 *
7189 	 * Also, the low order bits of the hash value are thought to be
7190 	 * distributed evenly. Otherwise, in the case that the multilist
7191 	 * has a power of two number of sublists, each sublists' usage
7192 	 * would not be evenly distributed.
7193 	 */
7194 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
7195 	    multilist_get_num_sublists(ml));
7196 }
7197 
7198 #define	WARN_IF_TUNING_IGNORED(tuning, value, do_warn) do {	\
7199 	if ((do_warn) && (tuning) && ((tuning) != (value))) {	\
7200 		cmn_err(CE_WARN,				\
7201 		    "ignoring tunable %s (using %llu instead)",	\
7202 		    (#tuning), (value));			\
7203 	}							\
7204 } while (0)
7205 
7206 /*
7207  * Called during module initialization and periodically thereafter to
7208  * apply reasonable changes to the exposed performance tunings.  Can also be
7209  * called explicitly by param_set_arc_*() functions when ARC tunables are
7210  * updated manually.  Non-zero zfs_* values which differ from the currently set
7211  * values will be applied.
7212  */
7213 void
7214 arc_tuning_update(boolean_t verbose)
7215 {
7216 	uint64_t allmem = arc_all_memory();
7217 	unsigned long limit;
7218 
7219 	/* Valid range: 32M - <arc_c_max> */
7220 	if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
7221 	    (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
7222 	    (zfs_arc_min <= arc_c_max)) {
7223 		arc_c_min = zfs_arc_min;
7224 		arc_c = MAX(arc_c, arc_c_min);
7225 	}
7226 	WARN_IF_TUNING_IGNORED(zfs_arc_min, arc_c_min, verbose);
7227 
7228 	/* Valid range: 64M - <all physical memory> */
7229 	if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
7230 	    (zfs_arc_max >= 64 << 20) && (zfs_arc_max < allmem) &&
7231 	    (zfs_arc_max > arc_c_min)) {
7232 		arc_c_max = zfs_arc_max;
7233 		arc_c = MIN(arc_c, arc_c_max);
7234 		arc_p = (arc_c >> 1);
7235 		if (arc_meta_limit > arc_c_max)
7236 			arc_meta_limit = arc_c_max;
7237 		if (arc_dnode_size_limit > arc_meta_limit)
7238 			arc_dnode_size_limit = arc_meta_limit;
7239 	}
7240 	WARN_IF_TUNING_IGNORED(zfs_arc_max, arc_c_max, verbose);
7241 
7242 	/* Valid range: 16M - <arc_c_max> */
7243 	if ((zfs_arc_meta_min) && (zfs_arc_meta_min != arc_meta_min) &&
7244 	    (zfs_arc_meta_min >= 1ULL << SPA_MAXBLOCKSHIFT) &&
7245 	    (zfs_arc_meta_min <= arc_c_max)) {
7246 		arc_meta_min = zfs_arc_meta_min;
7247 		if (arc_meta_limit < arc_meta_min)
7248 			arc_meta_limit = arc_meta_min;
7249 		if (arc_dnode_size_limit < arc_meta_min)
7250 			arc_dnode_size_limit = arc_meta_min;
7251 	}
7252 	WARN_IF_TUNING_IGNORED(zfs_arc_meta_min, arc_meta_min, verbose);
7253 
7254 	/* Valid range: <arc_meta_min> - <arc_c_max> */
7255 	limit = zfs_arc_meta_limit ? zfs_arc_meta_limit :
7256 	    MIN(zfs_arc_meta_limit_percent, 100) * arc_c_max / 100;
7257 	if ((limit != arc_meta_limit) &&
7258 	    (limit >= arc_meta_min) &&
7259 	    (limit <= arc_c_max))
7260 		arc_meta_limit = limit;
7261 	WARN_IF_TUNING_IGNORED(zfs_arc_meta_limit, arc_meta_limit, verbose);
7262 
7263 	/* Valid range: <arc_meta_min> - <arc_meta_limit> */
7264 	limit = zfs_arc_dnode_limit ? zfs_arc_dnode_limit :
7265 	    MIN(zfs_arc_dnode_limit_percent, 100) * arc_meta_limit / 100;
7266 	if ((limit != arc_dnode_size_limit) &&
7267 	    (limit >= arc_meta_min) &&
7268 	    (limit <= arc_meta_limit))
7269 		arc_dnode_size_limit = limit;
7270 	WARN_IF_TUNING_IGNORED(zfs_arc_dnode_limit, arc_dnode_size_limit,
7271 	    verbose);
7272 
7273 	/* Valid range: 1 - N */
7274 	if (zfs_arc_grow_retry)
7275 		arc_grow_retry = zfs_arc_grow_retry;
7276 
7277 	/* Valid range: 1 - N */
7278 	if (zfs_arc_shrink_shift) {
7279 		arc_shrink_shift = zfs_arc_shrink_shift;
7280 		arc_no_grow_shift = MIN(arc_no_grow_shift, arc_shrink_shift -1);
7281 	}
7282 
7283 	/* Valid range: 1 - N */
7284 	if (zfs_arc_p_min_shift)
7285 		arc_p_min_shift = zfs_arc_p_min_shift;
7286 
7287 	/* Valid range: 1 - N ms */
7288 	if (zfs_arc_min_prefetch_ms)
7289 		arc_min_prefetch_ms = zfs_arc_min_prefetch_ms;
7290 
7291 	/* Valid range: 1 - N ms */
7292 	if (zfs_arc_min_prescient_prefetch_ms) {
7293 		arc_min_prescient_prefetch_ms =
7294 		    zfs_arc_min_prescient_prefetch_ms;
7295 	}
7296 
7297 	/* Valid range: 0 - 100 */
7298 	if ((zfs_arc_lotsfree_percent >= 0) &&
7299 	    (zfs_arc_lotsfree_percent <= 100))
7300 		arc_lotsfree_percent = zfs_arc_lotsfree_percent;
7301 	WARN_IF_TUNING_IGNORED(zfs_arc_lotsfree_percent, arc_lotsfree_percent,
7302 	    verbose);
7303 
7304 	/* Valid range: 0 - <all physical memory> */
7305 	if ((zfs_arc_sys_free) && (zfs_arc_sys_free != arc_sys_free))
7306 		arc_sys_free = MIN(MAX(zfs_arc_sys_free, 0), allmem);
7307 	WARN_IF_TUNING_IGNORED(zfs_arc_sys_free, arc_sys_free, verbose);
7308 }
7309 
7310 static void
7311 arc_state_init(void)
7312 {
7313 	arc_anon = &ARC_anon;
7314 	arc_mru = &ARC_mru;
7315 	arc_mru_ghost = &ARC_mru_ghost;
7316 	arc_mfu = &ARC_mfu;
7317 	arc_mfu_ghost = &ARC_mfu_ghost;
7318 	arc_l2c_only = &ARC_l2c_only;
7319 
7320 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
7321 	    multilist_create(sizeof (arc_buf_hdr_t),
7322 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7323 	    arc_state_multilist_index_func);
7324 	arc_mru->arcs_list[ARC_BUFC_DATA] =
7325 	    multilist_create(sizeof (arc_buf_hdr_t),
7326 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7327 	    arc_state_multilist_index_func);
7328 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
7329 	    multilist_create(sizeof (arc_buf_hdr_t),
7330 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7331 	    arc_state_multilist_index_func);
7332 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
7333 	    multilist_create(sizeof (arc_buf_hdr_t),
7334 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7335 	    arc_state_multilist_index_func);
7336 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
7337 	    multilist_create(sizeof (arc_buf_hdr_t),
7338 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7339 	    arc_state_multilist_index_func);
7340 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
7341 	    multilist_create(sizeof (arc_buf_hdr_t),
7342 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7343 	    arc_state_multilist_index_func);
7344 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
7345 	    multilist_create(sizeof (arc_buf_hdr_t),
7346 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7347 	    arc_state_multilist_index_func);
7348 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
7349 	    multilist_create(sizeof (arc_buf_hdr_t),
7350 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7351 	    arc_state_multilist_index_func);
7352 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
7353 	    multilist_create(sizeof (arc_buf_hdr_t),
7354 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7355 	    arc_state_multilist_index_func);
7356 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
7357 	    multilist_create(sizeof (arc_buf_hdr_t),
7358 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7359 	    arc_state_multilist_index_func);
7360 
7361 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7362 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7363 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7364 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7365 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7366 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7367 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7368 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7369 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7370 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7371 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7372 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7373 
7374 	zfs_refcount_create(&arc_anon->arcs_size);
7375 	zfs_refcount_create(&arc_mru->arcs_size);
7376 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
7377 	zfs_refcount_create(&arc_mfu->arcs_size);
7378 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7379 	zfs_refcount_create(&arc_l2c_only->arcs_size);
7380 
7381 	aggsum_init(&arc_meta_used, 0);
7382 	aggsum_init(&arc_size, 0);
7383 	aggsum_init(&astat_data_size, 0);
7384 	aggsum_init(&astat_metadata_size, 0);
7385 	aggsum_init(&astat_hdr_size, 0);
7386 	aggsum_init(&astat_l2_hdr_size, 0);
7387 	aggsum_init(&astat_bonus_size, 0);
7388 	aggsum_init(&astat_dnode_size, 0);
7389 	aggsum_init(&astat_dbuf_size, 0);
7390 	aggsum_init(&astat_abd_chunk_waste_size, 0);
7391 
7392 	arc_anon->arcs_state = ARC_STATE_ANON;
7393 	arc_mru->arcs_state = ARC_STATE_MRU;
7394 	arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7395 	arc_mfu->arcs_state = ARC_STATE_MFU;
7396 	arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7397 	arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
7398 }
7399 
7400 static void
7401 arc_state_fini(void)
7402 {
7403 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7404 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7405 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7406 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7407 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7408 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7409 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7410 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7411 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7412 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7413 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7414 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7415 
7416 	zfs_refcount_destroy(&arc_anon->arcs_size);
7417 	zfs_refcount_destroy(&arc_mru->arcs_size);
7418 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7419 	zfs_refcount_destroy(&arc_mfu->arcs_size);
7420 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7421 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7422 
7423 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
7424 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7425 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7426 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7427 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
7428 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7429 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
7430 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7431 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7432 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
7433 
7434 	aggsum_fini(&arc_meta_used);
7435 	aggsum_fini(&arc_size);
7436 	aggsum_fini(&astat_data_size);
7437 	aggsum_fini(&astat_metadata_size);
7438 	aggsum_fini(&astat_hdr_size);
7439 	aggsum_fini(&astat_l2_hdr_size);
7440 	aggsum_fini(&astat_bonus_size);
7441 	aggsum_fini(&astat_dnode_size);
7442 	aggsum_fini(&astat_dbuf_size);
7443 	aggsum_fini(&astat_abd_chunk_waste_size);
7444 }
7445 
7446 uint64_t
7447 arc_target_bytes(void)
7448 {
7449 	return (arc_c);
7450 }
7451 
7452 void
7453 arc_init(void)
7454 {
7455 	uint64_t percent, allmem = arc_all_memory();
7456 	mutex_init(&arc_evict_lock, NULL, MUTEX_DEFAULT, NULL);
7457 	list_create(&arc_evict_waiters, sizeof (arc_evict_waiter_t),
7458 	    offsetof(arc_evict_waiter_t, aew_node));
7459 
7460 	arc_min_prefetch_ms = 1000;
7461 	arc_min_prescient_prefetch_ms = 6000;
7462 
7463 #if defined(_KERNEL)
7464 	arc_lowmem_init();
7465 #endif
7466 
7467 	/* Set min cache to 1/32 of all memory, or 32MB, whichever is more. */
7468 	arc_c_min = MAX(allmem / 32, 2ULL << SPA_MAXBLOCKSHIFT);
7469 
7470 	/* How to set default max varies by platform. */
7471 	arc_c_max = arc_default_max(arc_c_min, allmem);
7472 
7473 #ifndef _KERNEL
7474 	/*
7475 	 * In userland, there's only the memory pressure that we artificially
7476 	 * create (see arc_available_memory()).  Don't let arc_c get too
7477 	 * small, because it can cause transactions to be larger than
7478 	 * arc_c, causing arc_tempreserve_space() to fail.
7479 	 */
7480 	arc_c_min = MAX(arc_c_max / 2, 2ULL << SPA_MAXBLOCKSHIFT);
7481 #endif
7482 
7483 	arc_c = arc_c_min;
7484 	arc_p = (arc_c >> 1);
7485 
7486 	/* Set min to 1/2 of arc_c_min */
7487 	arc_meta_min = 1ULL << SPA_MAXBLOCKSHIFT;
7488 	/* Initialize maximum observed usage to zero */
7489 	arc_meta_max = 0;
7490 	/*
7491 	 * Set arc_meta_limit to a percent of arc_c_max with a floor of
7492 	 * arc_meta_min, and a ceiling of arc_c_max.
7493 	 */
7494 	percent = MIN(zfs_arc_meta_limit_percent, 100);
7495 	arc_meta_limit = MAX(arc_meta_min, (percent * arc_c_max) / 100);
7496 	percent = MIN(zfs_arc_dnode_limit_percent, 100);
7497 	arc_dnode_size_limit = (percent * arc_meta_limit) / 100;
7498 
7499 	/* Apply user specified tunings */
7500 	arc_tuning_update(B_TRUE);
7501 
7502 	/* if kmem_flags are set, lets try to use less memory */
7503 	if (kmem_debugging())
7504 		arc_c = arc_c / 2;
7505 	if (arc_c < arc_c_min)
7506 		arc_c = arc_c_min;
7507 
7508 	arc_state_init();
7509 
7510 	buf_init();
7511 
7512 	list_create(&arc_prune_list, sizeof (arc_prune_t),
7513 	    offsetof(arc_prune_t, p_node));
7514 	mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
7515 
7516 	arc_prune_taskq = taskq_create("arc_prune", boot_ncpus, defclsyspri,
7517 	    boot_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
7518 
7519 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7520 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7521 
7522 	if (arc_ksp != NULL) {
7523 		arc_ksp->ks_data = &arc_stats;
7524 		arc_ksp->ks_update = arc_kstat_update;
7525 		kstat_install(arc_ksp);
7526 	}
7527 
7528 	arc_evict_zthr = zthr_create_timer("arc_evict",
7529 	    arc_evict_cb_check, arc_evict_cb, NULL, SEC2NSEC(1));
7530 	arc_reap_zthr = zthr_create_timer("arc_reap",
7531 	    arc_reap_cb_check, arc_reap_cb, NULL, SEC2NSEC(1));
7532 
7533 	arc_warm = B_FALSE;
7534 
7535 	/*
7536 	 * Calculate maximum amount of dirty data per pool.
7537 	 *
7538 	 * If it has been set by a module parameter, take that.
7539 	 * Otherwise, use a percentage of physical memory defined by
7540 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
7541 	 * zfs_dirty_data_max_max (default 4G or 25% of physical memory).
7542 	 */
7543 #ifdef __LP64__
7544 	if (zfs_dirty_data_max_max == 0)
7545 		zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
7546 		    allmem * zfs_dirty_data_max_max_percent / 100);
7547 #else
7548 	if (zfs_dirty_data_max_max == 0)
7549 		zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
7550 		    allmem * zfs_dirty_data_max_max_percent / 100);
7551 #endif
7552 
7553 	if (zfs_dirty_data_max == 0) {
7554 		zfs_dirty_data_max = allmem *
7555 		    zfs_dirty_data_max_percent / 100;
7556 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7557 		    zfs_dirty_data_max_max);
7558 	}
7559 }
7560 
7561 void
7562 arc_fini(void)
7563 {
7564 	arc_prune_t *p;
7565 
7566 #ifdef _KERNEL
7567 	arc_lowmem_fini();
7568 #endif /* _KERNEL */
7569 
7570 	/* Use B_TRUE to ensure *all* buffers are evicted */
7571 	arc_flush(NULL, B_TRUE);
7572 
7573 	if (arc_ksp != NULL) {
7574 		kstat_delete(arc_ksp);
7575 		arc_ksp = NULL;
7576 	}
7577 
7578 	taskq_wait(arc_prune_taskq);
7579 	taskq_destroy(arc_prune_taskq);
7580 
7581 	mutex_enter(&arc_prune_mtx);
7582 	while ((p = list_head(&arc_prune_list)) != NULL) {
7583 		list_remove(&arc_prune_list, p);
7584 		zfs_refcount_remove(&p->p_refcnt, &arc_prune_list);
7585 		zfs_refcount_destroy(&p->p_refcnt);
7586 		kmem_free(p, sizeof (*p));
7587 	}
7588 	mutex_exit(&arc_prune_mtx);
7589 
7590 	list_destroy(&arc_prune_list);
7591 	mutex_destroy(&arc_prune_mtx);
7592 
7593 	(void) zthr_cancel(arc_evict_zthr);
7594 	(void) zthr_cancel(arc_reap_zthr);
7595 
7596 	mutex_destroy(&arc_evict_lock);
7597 	list_destroy(&arc_evict_waiters);
7598 
7599 	/*
7600 	 * Free any buffers that were tagged for destruction.  This needs
7601 	 * to occur before arc_state_fini() runs and destroys the aggsum
7602 	 * values which are updated when freeing scatter ABDs.
7603 	 */
7604 	l2arc_do_free_on_write();
7605 
7606 	/*
7607 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
7608 	 * trigger the release of kmem magazines, which can callback to
7609 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
7610 	 */
7611 	buf_fini();
7612 	arc_state_fini();
7613 
7614 	/*
7615 	 * We destroy the zthrs after all the ARC state has been
7616 	 * torn down to avoid the case of them receiving any
7617 	 * wakeup() signals after they are destroyed.
7618 	 */
7619 	zthr_destroy(arc_evict_zthr);
7620 	zthr_destroy(arc_reap_zthr);
7621 
7622 	ASSERT0(arc_loaned_bytes);
7623 }
7624 
7625 /*
7626  * Level 2 ARC
7627  *
7628  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7629  * It uses dedicated storage devices to hold cached data, which are populated
7630  * using large infrequent writes.  The main role of this cache is to boost
7631  * the performance of random read workloads.  The intended L2ARC devices
7632  * include short-stroked disks, solid state disks, and other media with
7633  * substantially faster read latency than disk.
7634  *
7635  *                 +-----------------------+
7636  *                 |         ARC           |
7637  *                 +-----------------------+
7638  *                    |         ^     ^
7639  *                    |         |     |
7640  *      l2arc_feed_thread()    arc_read()
7641  *                    |         |     |
7642  *                    |  l2arc read   |
7643  *                    V         |     |
7644  *               +---------------+    |
7645  *               |     L2ARC     |    |
7646  *               +---------------+    |
7647  *                   |    ^           |
7648  *          l2arc_write() |           |
7649  *                   |    |           |
7650  *                   V    |           |
7651  *                 +-------+      +-------+
7652  *                 | vdev  |      | vdev  |
7653  *                 | cache |      | cache |
7654  *                 +-------+      +-------+
7655  *                 +=========+     .-----.
7656  *                 :  L2ARC  :    |-_____-|
7657  *                 : devices :    | Disks |
7658  *                 +=========+    `-_____-'
7659  *
7660  * Read requests are satisfied from the following sources, in order:
7661  *
7662  *	1) ARC
7663  *	2) vdev cache of L2ARC devices
7664  *	3) L2ARC devices
7665  *	4) vdev cache of disks
7666  *	5) disks
7667  *
7668  * Some L2ARC device types exhibit extremely slow write performance.
7669  * To accommodate for this there are some significant differences between
7670  * the L2ARC and traditional cache design:
7671  *
7672  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
7673  * the ARC behave as usual, freeing buffers and placing headers on ghost
7674  * lists.  The ARC does not send buffers to the L2ARC during eviction as
7675  * this would add inflated write latencies for all ARC memory pressure.
7676  *
7677  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7678  * It does this by periodically scanning buffers from the eviction-end of
7679  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7680  * not already there. It scans until a headroom of buffers is satisfied,
7681  * which itself is a buffer for ARC eviction. If a compressible buffer is
7682  * found during scanning and selected for writing to an L2ARC device, we
7683  * temporarily boost scanning headroom during the next scan cycle to make
7684  * sure we adapt to compression effects (which might significantly reduce
7685  * the data volume we write to L2ARC). The thread that does this is
7686  * l2arc_feed_thread(), illustrated below; example sizes are included to
7687  * provide a better sense of ratio than this diagram:
7688  *
7689  *	       head -->                        tail
7690  *	        +---------------------+----------+
7691  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
7692  *	        +---------------------+----------+   |   o L2ARC eligible
7693  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
7694  *	        +---------------------+----------+   |
7695  *	             15.9 Gbytes      ^ 32 Mbytes    |
7696  *	                           headroom          |
7697  *	                                      l2arc_feed_thread()
7698  *	                                             |
7699  *	                 l2arc write hand <--[oooo]--'
7700  *	                         |           8 Mbyte
7701  *	                         |          write max
7702  *	                         V
7703  *		  +==============================+
7704  *	L2ARC dev |####|#|###|###|    |####| ... |
7705  *	          +==============================+
7706  *	                     32 Gbytes
7707  *
7708  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7709  * evicted, then the L2ARC has cached a buffer much sooner than it probably
7710  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
7711  * safe to say that this is an uncommon case, since buffers at the end of
7712  * the ARC lists have moved there due to inactivity.
7713  *
7714  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7715  * then the L2ARC simply misses copying some buffers.  This serves as a
7716  * pressure valve to prevent heavy read workloads from both stalling the ARC
7717  * with waits and clogging the L2ARC with writes.  This also helps prevent
7718  * the potential for the L2ARC to churn if it attempts to cache content too
7719  * quickly, such as during backups of the entire pool.
7720  *
7721  * 5. After system boot and before the ARC has filled main memory, there are
7722  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7723  * lists can remain mostly static.  Instead of searching from tail of these
7724  * lists as pictured, the l2arc_feed_thread() will search from the list heads
7725  * for eligible buffers, greatly increasing its chance of finding them.
7726  *
7727  * The L2ARC device write speed is also boosted during this time so that
7728  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
7729  * there are no L2ARC reads, and no fear of degrading read performance
7730  * through increased writes.
7731  *
7732  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7733  * the vdev queue can aggregate them into larger and fewer writes.  Each
7734  * device is written to in a rotor fashion, sweeping writes through
7735  * available space then repeating.
7736  *
7737  * 7. The L2ARC does not store dirty content.  It never needs to flush
7738  * write buffers back to disk based storage.
7739  *
7740  * 8. If an ARC buffer is written (and dirtied) which also exists in the
7741  * L2ARC, the now stale L2ARC buffer is immediately dropped.
7742  *
7743  * The performance of the L2ARC can be tweaked by a number of tunables, which
7744  * may be necessary for different workloads:
7745  *
7746  *	l2arc_write_max		max write bytes per interval
7747  *	l2arc_write_boost	extra write bytes during device warmup
7748  *	l2arc_noprefetch	skip caching prefetched buffers
7749  *	l2arc_headroom		number of max device writes to precache
7750  *	l2arc_headroom_boost	when we find compressed buffers during ARC
7751  *				scanning, we multiply headroom by this
7752  *				percentage factor for the next scan cycle,
7753  *				since more compressed buffers are likely to
7754  *				be present
7755  *	l2arc_feed_secs		seconds between L2ARC writing
7756  *
7757  * Tunables may be removed or added as future performance improvements are
7758  * integrated, and also may become zpool properties.
7759  *
7760  * There are three key functions that control how the L2ARC warms up:
7761  *
7762  *	l2arc_write_eligible()	check if a buffer is eligible to cache
7763  *	l2arc_write_size()	calculate how much to write
7764  *	l2arc_write_interval()	calculate sleep delay between writes
7765  *
7766  * These three functions determine what to write, how much, and how quickly
7767  * to send writes.
7768  *
7769  * L2ARC persistence:
7770  *
7771  * When writing buffers to L2ARC, we periodically add some metadata to
7772  * make sure we can pick them up after reboot, thus dramatically reducing
7773  * the impact that any downtime has on the performance of storage systems
7774  * with large caches.
7775  *
7776  * The implementation works fairly simply by integrating the following two
7777  * modifications:
7778  *
7779  * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
7780  *    which is an additional piece of metadata which describes what's been
7781  *    written. This allows us to rebuild the arc_buf_hdr_t structures of the
7782  *    main ARC buffers. There are 2 linked-lists of log blocks headed by
7783  *    dh_start_lbps[2]. We alternate which chain we append to, so they are
7784  *    time-wise and offset-wise interleaved, but that is an optimization rather
7785  *    than for correctness. The log block also includes a pointer to the
7786  *    previous block in its chain.
7787  *
7788  * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
7789  *    for our header bookkeeping purposes. This contains a device header,
7790  *    which contains our top-level reference structures. We update it each
7791  *    time we write a new log block, so that we're able to locate it in the
7792  *    L2ARC device. If this write results in an inconsistent device header
7793  *    (e.g. due to power failure), we detect this by verifying the header's
7794  *    checksum and simply fail to reconstruct the L2ARC after reboot.
7795  *
7796  * Implementation diagram:
7797  *
7798  * +=== L2ARC device (not to scale) ======================================+
7799  * |       ___two newest log block pointers__.__________                  |
7800  * |      /                                   \dh_start_lbps[1]           |
7801  * |	 /				       \         \dh_start_lbps[0]|
7802  * |.___/__.                                    V         V               |
7803  * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
7804  * ||   hdr|      ^         /^       /^        /         /                |
7805  * |+------+  ...--\-------/  \-----/--\------/         /                 |
7806  * |                \--------------/    \--------------/                  |
7807  * +======================================================================+
7808  *
7809  * As can be seen on the diagram, rather than using a simple linked list,
7810  * we use a pair of linked lists with alternating elements. This is a
7811  * performance enhancement due to the fact that we only find out the
7812  * address of the next log block access once the current block has been
7813  * completely read in. Obviously, this hurts performance, because we'd be
7814  * keeping the device's I/O queue at only a 1 operation deep, thus
7815  * incurring a large amount of I/O round-trip latency. Having two lists
7816  * allows us to fetch two log blocks ahead of where we are currently
7817  * rebuilding L2ARC buffers.
7818  *
7819  * On-device data structures:
7820  *
7821  * L2ARC device header:	l2arc_dev_hdr_phys_t
7822  * L2ARC log block:	l2arc_log_blk_phys_t
7823  *
7824  * L2ARC reconstruction:
7825  *
7826  * When writing data, we simply write in the standard rotary fashion,
7827  * evicting buffers as we go and simply writing new data over them (writing
7828  * a new log block every now and then). This obviously means that once we
7829  * loop around the end of the device, we will start cutting into an already
7830  * committed log block (and its referenced data buffers), like so:
7831  *
7832  *    current write head__       __old tail
7833  *                        \     /
7834  *                        V    V
7835  * <--|bufs |lb |bufs |lb |    |bufs |lb |bufs |lb |-->
7836  *                         ^    ^^^^^^^^^___________________________________
7837  *                         |                                                \
7838  *                   <<nextwrite>> may overwrite this blk and/or its bufs --'
7839  *
7840  * When importing the pool, we detect this situation and use it to stop
7841  * our scanning process (see l2arc_rebuild).
7842  *
7843  * There is one significant caveat to consider when rebuilding ARC contents
7844  * from an L2ARC device: what about invalidated buffers? Given the above
7845  * construction, we cannot update blocks which we've already written to amend
7846  * them to remove buffers which were invalidated. Thus, during reconstruction,
7847  * we might be populating the cache with buffers for data that's not on the
7848  * main pool anymore, or may have been overwritten!
7849  *
7850  * As it turns out, this isn't a problem. Every arc_read request includes
7851  * both the DVA and, crucially, the birth TXG of the BP the caller is
7852  * looking for. So even if the cache were populated by completely rotten
7853  * blocks for data that had been long deleted and/or overwritten, we'll
7854  * never actually return bad data from the cache, since the DVA with the
7855  * birth TXG uniquely identify a block in space and time - once created,
7856  * a block is immutable on disk. The worst thing we have done is wasted
7857  * some time and memory at l2arc rebuild to reconstruct outdated ARC
7858  * entries that will get dropped from the l2arc as it is being updated
7859  * with new blocks.
7860  *
7861  * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
7862  * hand are not restored. This is done by saving the offset (in bytes)
7863  * l2arc_evict() has evicted to in the L2ARC device header and taking it
7864  * into account when restoring buffers.
7865  */
7866 
7867 static boolean_t
7868 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7869 {
7870 	/*
7871 	 * A buffer is *not* eligible for the L2ARC if it:
7872 	 * 1. belongs to a different spa.
7873 	 * 2. is already cached on the L2ARC.
7874 	 * 3. has an I/O in progress (it may be an incomplete read).
7875 	 * 4. is flagged not eligible (zfs property).
7876 	 */
7877 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
7878 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
7879 		return (B_FALSE);
7880 
7881 	return (B_TRUE);
7882 }
7883 
7884 static uint64_t
7885 l2arc_write_size(l2arc_dev_t *dev)
7886 {
7887 	uint64_t size, dev_size, tsize;
7888 
7889 	/*
7890 	 * Make sure our globals have meaningful values in case the user
7891 	 * altered them.
7892 	 */
7893 	size = l2arc_write_max;
7894 	if (size == 0) {
7895 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7896 		    "be greater than zero, resetting it to the default (%d)",
7897 		    L2ARC_WRITE_SIZE);
7898 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
7899 	}
7900 
7901 	if (arc_warm == B_FALSE)
7902 		size += l2arc_write_boost;
7903 
7904 	/*
7905 	 * Make sure the write size does not exceed the size of the cache
7906 	 * device. This is important in l2arc_evict(), otherwise infinite
7907 	 * iteration can occur.
7908 	 */
7909 	dev_size = dev->l2ad_end - dev->l2ad_start;
7910 	tsize = size + l2arc_log_blk_overhead(size, dev);
7911 	if (dev->l2ad_vdev->vdev_has_trim && l2arc_trim_ahead > 0)
7912 		tsize += MAX(64 * 1024 * 1024,
7913 		    (tsize * l2arc_trim_ahead) / 100);
7914 
7915 	if (tsize >= dev_size) {
7916 		cmn_err(CE_NOTE, "l2arc_write_max or l2arc_write_boost "
7917 		    "plus the overhead of log blocks (persistent L2ARC, "
7918 		    "%llu bytes) exceeds the size of the cache device "
7919 		    "(guid %llu), resetting them to the default (%d)",
7920 		    l2arc_log_blk_overhead(size, dev),
7921 		    dev->l2ad_vdev->vdev_guid, L2ARC_WRITE_SIZE);
7922 		size = l2arc_write_max = l2arc_write_boost = L2ARC_WRITE_SIZE;
7923 
7924 		if (arc_warm == B_FALSE)
7925 			size += l2arc_write_boost;
7926 	}
7927 
7928 	return (size);
7929 
7930 }
7931 
7932 static clock_t
7933 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7934 {
7935 	clock_t interval, next, now;
7936 
7937 	/*
7938 	 * If the ARC lists are busy, increase our write rate; if the
7939 	 * lists are stale, idle back.  This is achieved by checking
7940 	 * how much we previously wrote - if it was more than half of
7941 	 * what we wanted, schedule the next write much sooner.
7942 	 */
7943 	if (l2arc_feed_again && wrote > (wanted / 2))
7944 		interval = (hz * l2arc_feed_min_ms) / 1000;
7945 	else
7946 		interval = hz * l2arc_feed_secs;
7947 
7948 	now = ddi_get_lbolt();
7949 	next = MAX(now, MIN(now + interval, began + interval));
7950 
7951 	return (next);
7952 }
7953 
7954 /*
7955  * Cycle through L2ARC devices.  This is how L2ARC load balances.
7956  * If a device is returned, this also returns holding the spa config lock.
7957  */
7958 static l2arc_dev_t *
7959 l2arc_dev_get_next(void)
7960 {
7961 	l2arc_dev_t *first, *next = NULL;
7962 
7963 	/*
7964 	 * Lock out the removal of spas (spa_namespace_lock), then removal
7965 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
7966 	 * both locks will be dropped and a spa config lock held instead.
7967 	 */
7968 	mutex_enter(&spa_namespace_lock);
7969 	mutex_enter(&l2arc_dev_mtx);
7970 
7971 	/* if there are no vdevs, there is nothing to do */
7972 	if (l2arc_ndev == 0)
7973 		goto out;
7974 
7975 	first = NULL;
7976 	next = l2arc_dev_last;
7977 	do {
7978 		/* loop around the list looking for a non-faulted vdev */
7979 		if (next == NULL) {
7980 			next = list_head(l2arc_dev_list);
7981 		} else {
7982 			next = list_next(l2arc_dev_list, next);
7983 			if (next == NULL)
7984 				next = list_head(l2arc_dev_list);
7985 		}
7986 
7987 		/* if we have come back to the start, bail out */
7988 		if (first == NULL)
7989 			first = next;
7990 		else if (next == first)
7991 			break;
7992 
7993 	} while (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
7994 	    next->l2ad_trim_all);
7995 
7996 	/* if we were unable to find any usable vdevs, return NULL */
7997 	if (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
7998 	    next->l2ad_trim_all)
7999 		next = NULL;
8000 
8001 	l2arc_dev_last = next;
8002 
8003 out:
8004 	mutex_exit(&l2arc_dev_mtx);
8005 
8006 	/*
8007 	 * Grab the config lock to prevent the 'next' device from being
8008 	 * removed while we are writing to it.
8009 	 */
8010 	if (next != NULL)
8011 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
8012 	mutex_exit(&spa_namespace_lock);
8013 
8014 	return (next);
8015 }
8016 
8017 /*
8018  * Free buffers that were tagged for destruction.
8019  */
8020 static void
8021 l2arc_do_free_on_write(void)
8022 {
8023 	list_t *buflist;
8024 	l2arc_data_free_t *df, *df_prev;
8025 
8026 	mutex_enter(&l2arc_free_on_write_mtx);
8027 	buflist = l2arc_free_on_write;
8028 
8029 	for (df = list_tail(buflist); df; df = df_prev) {
8030 		df_prev = list_prev(buflist, df);
8031 		ASSERT3P(df->l2df_abd, !=, NULL);
8032 		abd_free(df->l2df_abd);
8033 		list_remove(buflist, df);
8034 		kmem_free(df, sizeof (l2arc_data_free_t));
8035 	}
8036 
8037 	mutex_exit(&l2arc_free_on_write_mtx);
8038 }
8039 
8040 /*
8041  * A write to a cache device has completed.  Update all headers to allow
8042  * reads from these buffers to begin.
8043  */
8044 static void
8045 l2arc_write_done(zio_t *zio)
8046 {
8047 	l2arc_write_callback_t	*cb;
8048 	l2arc_lb_abd_buf_t	*abd_buf;
8049 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
8050 	l2arc_dev_t		*dev;
8051 	l2arc_dev_hdr_phys_t	*l2dhdr;
8052 	list_t			*buflist;
8053 	arc_buf_hdr_t		*head, *hdr, *hdr_prev;
8054 	kmutex_t		*hash_lock;
8055 	int64_t			bytes_dropped = 0;
8056 
8057 	cb = zio->io_private;
8058 	ASSERT3P(cb, !=, NULL);
8059 	dev = cb->l2wcb_dev;
8060 	l2dhdr = dev->l2ad_dev_hdr;
8061 	ASSERT3P(dev, !=, NULL);
8062 	head = cb->l2wcb_head;
8063 	ASSERT3P(head, !=, NULL);
8064 	buflist = &dev->l2ad_buflist;
8065 	ASSERT3P(buflist, !=, NULL);
8066 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
8067 	    l2arc_write_callback_t *, cb);
8068 
8069 	if (zio->io_error != 0)
8070 		ARCSTAT_BUMP(arcstat_l2_writes_error);
8071 
8072 	/*
8073 	 * All writes completed, or an error was hit.
8074 	 */
8075 top:
8076 	mutex_enter(&dev->l2ad_mtx);
8077 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
8078 		hdr_prev = list_prev(buflist, hdr);
8079 
8080 		hash_lock = HDR_LOCK(hdr);
8081 
8082 		/*
8083 		 * We cannot use mutex_enter or else we can deadlock
8084 		 * with l2arc_write_buffers (due to swapping the order
8085 		 * the hash lock and l2ad_mtx are taken).
8086 		 */
8087 		if (!mutex_tryenter(hash_lock)) {
8088 			/*
8089 			 * Missed the hash lock. We must retry so we
8090 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
8091 			 */
8092 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
8093 
8094 			/*
8095 			 * We don't want to rescan the headers we've
8096 			 * already marked as having been written out, so
8097 			 * we reinsert the head node so we can pick up
8098 			 * where we left off.
8099 			 */
8100 			list_remove(buflist, head);
8101 			list_insert_after(buflist, hdr, head);
8102 
8103 			mutex_exit(&dev->l2ad_mtx);
8104 
8105 			/*
8106 			 * We wait for the hash lock to become available
8107 			 * to try and prevent busy waiting, and increase
8108 			 * the chance we'll be able to acquire the lock
8109 			 * the next time around.
8110 			 */
8111 			mutex_enter(hash_lock);
8112 			mutex_exit(hash_lock);
8113 			goto top;
8114 		}
8115 
8116 		/*
8117 		 * We could not have been moved into the arc_l2c_only
8118 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
8119 		 * bit being set. Let's just ensure that's being enforced.
8120 		 */
8121 		ASSERT(HDR_HAS_L1HDR(hdr));
8122 
8123 		/*
8124 		 * Skipped - drop L2ARC entry and mark the header as no
8125 		 * longer L2 eligibile.
8126 		 */
8127 		if (zio->io_error != 0) {
8128 			/*
8129 			 * Error - drop L2ARC entry.
8130 			 */
8131 			list_remove(buflist, hdr);
8132 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
8133 
8134 			uint64_t psize = HDR_GET_PSIZE(hdr);
8135 			ARCSTAT_INCR(arcstat_l2_psize, -psize);
8136 			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
8137 
8138 			bytes_dropped +=
8139 			    vdev_psize_to_asize(dev->l2ad_vdev, psize);
8140 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
8141 			    arc_hdr_size(hdr), hdr);
8142 		}
8143 
8144 		/*
8145 		 * Allow ARC to begin reads and ghost list evictions to
8146 		 * this L2ARC entry.
8147 		 */
8148 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
8149 
8150 		mutex_exit(hash_lock);
8151 	}
8152 
8153 	/*
8154 	 * Free the allocated abd buffers for writing the log blocks.
8155 	 * If the zio failed reclaim the allocated space and remove the
8156 	 * pointers to these log blocks from the log block pointer list
8157 	 * of the L2ARC device.
8158 	 */
8159 	while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
8160 		abd_free(abd_buf->abd);
8161 		zio_buf_free(abd_buf, sizeof (*abd_buf));
8162 		if (zio->io_error != 0) {
8163 			lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
8164 			/*
8165 			 * L2BLK_GET_PSIZE returns aligned size for log
8166 			 * blocks.
8167 			 */
8168 			uint64_t asize =
8169 			    L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
8170 			bytes_dropped += asize;
8171 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8172 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8173 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8174 			    lb_ptr_buf);
8175 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8176 			kmem_free(lb_ptr_buf->lb_ptr,
8177 			    sizeof (l2arc_log_blkptr_t));
8178 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8179 		}
8180 	}
8181 	list_destroy(&cb->l2wcb_abd_list);
8182 
8183 	if (zio->io_error != 0) {
8184 		/*
8185 		 * Restore the lbps array in the header to its previous state.
8186 		 * If the list of log block pointers is empty, zero out the
8187 		 * log block pointers in the device header.
8188 		 */
8189 		lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
8190 		for (int i = 0; i < 2; i++) {
8191 			if (lb_ptr_buf == NULL) {
8192 				/*
8193 				 * If the list is empty zero out the device
8194 				 * header. Otherwise zero out the second log
8195 				 * block pointer in the header.
8196 				 */
8197 				if (i == 0) {
8198 					bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
8199 				} else {
8200 					bzero(&l2dhdr->dh_start_lbps[i],
8201 					    sizeof (l2arc_log_blkptr_t));
8202 				}
8203 				break;
8204 			}
8205 			bcopy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[i],
8206 			    sizeof (l2arc_log_blkptr_t));
8207 			lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
8208 			    lb_ptr_buf);
8209 		}
8210 	}
8211 
8212 	atomic_inc_64(&l2arc_writes_done);
8213 	list_remove(buflist, head);
8214 	ASSERT(!HDR_HAS_L1HDR(head));
8215 	kmem_cache_free(hdr_l2only_cache, head);
8216 	mutex_exit(&dev->l2ad_mtx);
8217 
8218 	ASSERT(dev->l2ad_vdev != NULL);
8219 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
8220 
8221 	l2arc_do_free_on_write();
8222 
8223 	kmem_free(cb, sizeof (l2arc_write_callback_t));
8224 }
8225 
8226 static int
8227 l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
8228 {
8229 	int ret;
8230 	spa_t *spa = zio->io_spa;
8231 	arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
8232 	blkptr_t *bp = zio->io_bp;
8233 	uint8_t salt[ZIO_DATA_SALT_LEN];
8234 	uint8_t iv[ZIO_DATA_IV_LEN];
8235 	uint8_t mac[ZIO_DATA_MAC_LEN];
8236 	boolean_t no_crypt = B_FALSE;
8237 
8238 	/*
8239 	 * ZIL data is never be written to the L2ARC, so we don't need
8240 	 * special handling for its unique MAC storage.
8241 	 */
8242 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
8243 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
8244 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8245 
8246 	/*
8247 	 * If the data was encrypted, decrypt it now. Note that
8248 	 * we must check the bp here and not the hdr, since the
8249 	 * hdr does not have its encryption parameters updated
8250 	 * until arc_read_done().
8251 	 */
8252 	if (BP_IS_ENCRYPTED(bp)) {
8253 		abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8254 		    B_TRUE);
8255 
8256 		zio_crypt_decode_params_bp(bp, salt, iv);
8257 		zio_crypt_decode_mac_bp(bp, mac);
8258 
8259 		ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
8260 		    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
8261 		    salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
8262 		    hdr->b_l1hdr.b_pabd, &no_crypt);
8263 		if (ret != 0) {
8264 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8265 			goto error;
8266 		}
8267 
8268 		/*
8269 		 * If we actually performed decryption, replace b_pabd
8270 		 * with the decrypted data. Otherwise we can just throw
8271 		 * our decryption buffer away.
8272 		 */
8273 		if (!no_crypt) {
8274 			arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8275 			    arc_hdr_size(hdr), hdr);
8276 			hdr->b_l1hdr.b_pabd = eabd;
8277 			zio->io_abd = eabd;
8278 		} else {
8279 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8280 		}
8281 	}
8282 
8283 	/*
8284 	 * If the L2ARC block was compressed, but ARC compression
8285 	 * is disabled we decompress the data into a new buffer and
8286 	 * replace the existing data.
8287 	 */
8288 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8289 	    !HDR_COMPRESSION_ENABLED(hdr)) {
8290 		abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8291 		    B_TRUE);
8292 		void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
8293 
8294 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
8295 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
8296 		    HDR_GET_LSIZE(hdr), &hdr->b_complevel);
8297 		if (ret != 0) {
8298 			abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8299 			arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
8300 			goto error;
8301 		}
8302 
8303 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8304 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8305 		    arc_hdr_size(hdr), hdr);
8306 		hdr->b_l1hdr.b_pabd = cabd;
8307 		zio->io_abd = cabd;
8308 		zio->io_size = HDR_GET_LSIZE(hdr);
8309 	}
8310 
8311 	return (0);
8312 
8313 error:
8314 	return (ret);
8315 }
8316 
8317 
8318 /*
8319  * A read to a cache device completed.  Validate buffer contents before
8320  * handing over to the regular ARC routines.
8321  */
8322 static void
8323 l2arc_read_done(zio_t *zio)
8324 {
8325 	int tfm_error = 0;
8326 	l2arc_read_callback_t *cb = zio->io_private;
8327 	arc_buf_hdr_t *hdr;
8328 	kmutex_t *hash_lock;
8329 	boolean_t valid_cksum;
8330 	boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
8331 	    (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
8332 
8333 	ASSERT3P(zio->io_vd, !=, NULL);
8334 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
8335 
8336 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
8337 
8338 	ASSERT3P(cb, !=, NULL);
8339 	hdr = cb->l2rcb_hdr;
8340 	ASSERT3P(hdr, !=, NULL);
8341 
8342 	hash_lock = HDR_LOCK(hdr);
8343 	mutex_enter(hash_lock);
8344 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
8345 
8346 	/*
8347 	 * If the data was read into a temporary buffer,
8348 	 * move it and free the buffer.
8349 	 */
8350 	if (cb->l2rcb_abd != NULL) {
8351 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
8352 		if (zio->io_error == 0) {
8353 			if (using_rdata) {
8354 				abd_copy(hdr->b_crypt_hdr.b_rabd,
8355 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8356 			} else {
8357 				abd_copy(hdr->b_l1hdr.b_pabd,
8358 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8359 			}
8360 		}
8361 
8362 		/*
8363 		 * The following must be done regardless of whether
8364 		 * there was an error:
8365 		 * - free the temporary buffer
8366 		 * - point zio to the real ARC buffer
8367 		 * - set zio size accordingly
8368 		 * These are required because zio is either re-used for
8369 		 * an I/O of the block in the case of the error
8370 		 * or the zio is passed to arc_read_done() and it
8371 		 * needs real data.
8372 		 */
8373 		abd_free(cb->l2rcb_abd);
8374 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
8375 
8376 		if (using_rdata) {
8377 			ASSERT(HDR_HAS_RABD(hdr));
8378 			zio->io_abd = zio->io_orig_abd =
8379 			    hdr->b_crypt_hdr.b_rabd;
8380 		} else {
8381 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8382 			zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8383 		}
8384 	}
8385 
8386 	ASSERT3P(zio->io_abd, !=, NULL);
8387 
8388 	/*
8389 	 * Check this survived the L2ARC journey.
8390 	 */
8391 	ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8392 	    (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8393 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
8394 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
8395 	zio->io_prop.zp_complevel = hdr->b_complevel;
8396 
8397 	valid_cksum = arc_cksum_is_equal(hdr, zio);
8398 
8399 	/*
8400 	 * b_rabd will always match the data as it exists on disk if it is
8401 	 * being used. Therefore if we are reading into b_rabd we do not
8402 	 * attempt to untransform the data.
8403 	 */
8404 	if (valid_cksum && !using_rdata)
8405 		tfm_error = l2arc_untransform(zio, cb);
8406 
8407 	if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8408 	    !HDR_L2_EVICTED(hdr)) {
8409 		mutex_exit(hash_lock);
8410 		zio->io_private = hdr;
8411 		arc_read_done(zio);
8412 	} else {
8413 		/*
8414 		 * Buffer didn't survive caching.  Increment stats and
8415 		 * reissue to the original storage device.
8416 		 */
8417 		if (zio->io_error != 0) {
8418 			ARCSTAT_BUMP(arcstat_l2_io_error);
8419 		} else {
8420 			zio->io_error = SET_ERROR(EIO);
8421 		}
8422 		if (!valid_cksum || tfm_error != 0)
8423 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8424 
8425 		/*
8426 		 * If there's no waiter, issue an async i/o to the primary
8427 		 * storage now.  If there *is* a waiter, the caller must
8428 		 * issue the i/o in a context where it's OK to block.
8429 		 */
8430 		if (zio->io_waiter == NULL) {
8431 			zio_t *pio = zio_unique_parent(zio);
8432 			void *abd = (using_rdata) ?
8433 			    hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
8434 
8435 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8436 
8437 			zio = zio_read(pio, zio->io_spa, zio->io_bp,
8438 			    abd, zio->io_size, arc_read_done,
8439 			    hdr, zio->io_priority, cb->l2rcb_flags,
8440 			    &cb->l2rcb_zb);
8441 
8442 			/*
8443 			 * Original ZIO will be freed, so we need to update
8444 			 * ARC header with the new ZIO pointer to be used
8445 			 * by zio_change_priority() in arc_read().
8446 			 */
8447 			for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
8448 			    acb != NULL; acb = acb->acb_next)
8449 				acb->acb_zio_head = zio;
8450 
8451 			mutex_exit(hash_lock);
8452 			zio_nowait(zio);
8453 		} else {
8454 			mutex_exit(hash_lock);
8455 		}
8456 	}
8457 
8458 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8459 }
8460 
8461 /*
8462  * This is the list priority from which the L2ARC will search for pages to
8463  * cache.  This is used within loops (0..3) to cycle through lists in the
8464  * desired order.  This order can have a significant effect on cache
8465  * performance.
8466  *
8467  * Currently the metadata lists are hit first, MFU then MRU, followed by
8468  * the data lists.  This function returns a locked list, and also returns
8469  * the lock pointer.
8470  */
8471 static multilist_sublist_t *
8472 l2arc_sublist_lock(int list_num)
8473 {
8474 	multilist_t *ml = NULL;
8475 	unsigned int idx;
8476 
8477 	ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
8478 
8479 	switch (list_num) {
8480 	case 0:
8481 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
8482 		break;
8483 	case 1:
8484 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
8485 		break;
8486 	case 2:
8487 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
8488 		break;
8489 	case 3:
8490 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
8491 		break;
8492 	default:
8493 		return (NULL);
8494 	}
8495 
8496 	/*
8497 	 * Return a randomly-selected sublist. This is acceptable
8498 	 * because the caller feeds only a little bit of data for each
8499 	 * call (8MB). Subsequent calls will result in different
8500 	 * sublists being selected.
8501 	 */
8502 	idx = multilist_get_random_index(ml);
8503 	return (multilist_sublist_lock(ml, idx));
8504 }
8505 
8506 /*
8507  * Calculates the maximum overhead of L2ARC metadata log blocks for a given
8508  * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
8509  * overhead in processing to make sure there is enough headroom available
8510  * when writing buffers.
8511  */
8512 static inline uint64_t
8513 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
8514 {
8515 	if (dev->l2ad_log_entries == 0) {
8516 		return (0);
8517 	} else {
8518 		uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
8519 
8520 		uint64_t log_blocks = (log_entries +
8521 		    dev->l2ad_log_entries - 1) /
8522 		    dev->l2ad_log_entries;
8523 
8524 		return (vdev_psize_to_asize(dev->l2ad_vdev,
8525 		    sizeof (l2arc_log_blk_phys_t)) * log_blocks);
8526 	}
8527 }
8528 
8529 /*
8530  * Evict buffers from the device write hand to the distance specified in
8531  * bytes. This distance may span populated buffers, it may span nothing.
8532  * This is clearing a region on the L2ARC device ready for writing.
8533  * If the 'all' boolean is set, every buffer is evicted.
8534  */
8535 static void
8536 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
8537 {
8538 	list_t *buflist;
8539 	arc_buf_hdr_t *hdr, *hdr_prev;
8540 	kmutex_t *hash_lock;
8541 	uint64_t taddr;
8542 	l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
8543 	vdev_t *vd = dev->l2ad_vdev;
8544 	boolean_t rerun;
8545 
8546 	buflist = &dev->l2ad_buflist;
8547 
8548 	/*
8549 	 * We need to add in the worst case scenario of log block overhead.
8550 	 */
8551 	distance += l2arc_log_blk_overhead(distance, dev);
8552 	if (vd->vdev_has_trim && l2arc_trim_ahead > 0) {
8553 		/*
8554 		 * Trim ahead of the write size 64MB or (l2arc_trim_ahead/100)
8555 		 * times the write size, whichever is greater.
8556 		 */
8557 		distance += MAX(64 * 1024 * 1024,
8558 		    (distance * l2arc_trim_ahead) / 100);
8559 	}
8560 
8561 top:
8562 	rerun = B_FALSE;
8563 	if (dev->l2ad_hand >= (dev->l2ad_end - distance)) {
8564 		/*
8565 		 * When there is no space to accommodate upcoming writes,
8566 		 * evict to the end. Then bump the write and evict hands
8567 		 * to the start and iterate. This iteration does not
8568 		 * happen indefinitely as we make sure in
8569 		 * l2arc_write_size() that when the write hand is reset,
8570 		 * the write size does not exceed the end of the device.
8571 		 */
8572 		rerun = B_TRUE;
8573 		taddr = dev->l2ad_end;
8574 	} else {
8575 		taddr = dev->l2ad_hand + distance;
8576 	}
8577 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
8578 	    uint64_t, taddr, boolean_t, all);
8579 
8580 	if (!all) {
8581 		/*
8582 		 * This check has to be placed after deciding whether to
8583 		 * iterate (rerun).
8584 		 */
8585 		if (dev->l2ad_first) {
8586 			/*
8587 			 * This is the first sweep through the device. There is
8588 			 * nothing to evict. We have already trimmmed the
8589 			 * whole device.
8590 			 */
8591 			goto out;
8592 		} else {
8593 			/*
8594 			 * Trim the space to be evicted.
8595 			 */
8596 			if (vd->vdev_has_trim && dev->l2ad_evict < taddr &&
8597 			    l2arc_trim_ahead > 0) {
8598 				/*
8599 				 * We have to drop the spa_config lock because
8600 				 * vdev_trim_range() will acquire it.
8601 				 * l2ad_evict already accounts for the label
8602 				 * size. To prevent vdev_trim_ranges() from
8603 				 * adding it again, we subtract it from
8604 				 * l2ad_evict.
8605 				 */
8606 				spa_config_exit(dev->l2ad_spa, SCL_L2ARC, dev);
8607 				vdev_trim_simple(vd,
8608 				    dev->l2ad_evict - VDEV_LABEL_START_SIZE,
8609 				    taddr - dev->l2ad_evict);
8610 				spa_config_enter(dev->l2ad_spa, SCL_L2ARC, dev,
8611 				    RW_READER);
8612 			}
8613 
8614 			/*
8615 			 * When rebuilding L2ARC we retrieve the evict hand
8616 			 * from the header of the device. Of note, l2arc_evict()
8617 			 * does not actually delete buffers from the cache
8618 			 * device, but trimming may do so depending on the
8619 			 * hardware implementation. Thus keeping track of the
8620 			 * evict hand is useful.
8621 			 */
8622 			dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
8623 		}
8624 	}
8625 
8626 retry:
8627 	mutex_enter(&dev->l2ad_mtx);
8628 	/*
8629 	 * We have to account for evicted log blocks. Run vdev_space_update()
8630 	 * on log blocks whose offset (in bytes) is before the evicted offset
8631 	 * (in bytes) by searching in the list of pointers to log blocks
8632 	 * present in the L2ARC device.
8633 	 */
8634 	for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
8635 	    lb_ptr_buf = lb_ptr_buf_prev) {
8636 
8637 		lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
8638 
8639 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
8640 		uint64_t asize = L2BLK_GET_PSIZE(
8641 		    (lb_ptr_buf->lb_ptr)->lbp_prop);
8642 
8643 		/*
8644 		 * We don't worry about log blocks left behind (ie
8645 		 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
8646 		 * will never write more than l2arc_evict() evicts.
8647 		 */
8648 		if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
8649 			break;
8650 		} else {
8651 			vdev_space_update(vd, -asize, 0, 0);
8652 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8653 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8654 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8655 			    lb_ptr_buf);
8656 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8657 			list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
8658 			kmem_free(lb_ptr_buf->lb_ptr,
8659 			    sizeof (l2arc_log_blkptr_t));
8660 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8661 		}
8662 	}
8663 
8664 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
8665 		hdr_prev = list_prev(buflist, hdr);
8666 
8667 		ASSERT(!HDR_EMPTY(hdr));
8668 		hash_lock = HDR_LOCK(hdr);
8669 
8670 		/*
8671 		 * We cannot use mutex_enter or else we can deadlock
8672 		 * with l2arc_write_buffers (due to swapping the order
8673 		 * the hash lock and l2ad_mtx are taken).
8674 		 */
8675 		if (!mutex_tryenter(hash_lock)) {
8676 			/*
8677 			 * Missed the hash lock.  Retry.
8678 			 */
8679 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
8680 			mutex_exit(&dev->l2ad_mtx);
8681 			mutex_enter(hash_lock);
8682 			mutex_exit(hash_lock);
8683 			goto retry;
8684 		}
8685 
8686 		/*
8687 		 * A header can't be on this list if it doesn't have L2 header.
8688 		 */
8689 		ASSERT(HDR_HAS_L2HDR(hdr));
8690 
8691 		/* Ensure this header has finished being written. */
8692 		ASSERT(!HDR_L2_WRITING(hdr));
8693 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8694 
8695 		if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
8696 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
8697 			/*
8698 			 * We've evicted to the target address,
8699 			 * or the end of the device.
8700 			 */
8701 			mutex_exit(hash_lock);
8702 			break;
8703 		}
8704 
8705 		if (!HDR_HAS_L1HDR(hdr)) {
8706 			ASSERT(!HDR_L2_READING(hdr));
8707 			/*
8708 			 * This doesn't exist in the ARC.  Destroy.
8709 			 * arc_hdr_destroy() will call list_remove()
8710 			 * and decrement arcstat_l2_lsize.
8711 			 */
8712 			arc_change_state(arc_anon, hdr, hash_lock);
8713 			arc_hdr_destroy(hdr);
8714 		} else {
8715 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
8716 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
8717 			/*
8718 			 * Invalidate issued or about to be issued
8719 			 * reads, since we may be about to write
8720 			 * over this location.
8721 			 */
8722 			if (HDR_L2_READING(hdr)) {
8723 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
8724 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
8725 			}
8726 
8727 			arc_hdr_l2hdr_destroy(hdr);
8728 		}
8729 		mutex_exit(hash_lock);
8730 	}
8731 	mutex_exit(&dev->l2ad_mtx);
8732 
8733 out:
8734 	/*
8735 	 * We need to check if we evict all buffers, otherwise we may iterate
8736 	 * unnecessarily.
8737 	 */
8738 	if (!all && rerun) {
8739 		/*
8740 		 * Bump device hand to the device start if it is approaching the
8741 		 * end. l2arc_evict() has already evicted ahead for this case.
8742 		 */
8743 		dev->l2ad_hand = dev->l2ad_start;
8744 		dev->l2ad_evict = dev->l2ad_start;
8745 		dev->l2ad_first = B_FALSE;
8746 		goto top;
8747 	}
8748 
8749 	ASSERT3U(dev->l2ad_hand + distance, <, dev->l2ad_end);
8750 	if (!dev->l2ad_first)
8751 		ASSERT3U(dev->l2ad_hand, <, dev->l2ad_evict);
8752 }
8753 
8754 /*
8755  * Handle any abd transforms that might be required for writing to the L2ARC.
8756  * If successful, this function will always return an abd with the data
8757  * transformed as it is on disk in a new abd of asize bytes.
8758  */
8759 static int
8760 l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
8761     abd_t **abd_out)
8762 {
8763 	int ret;
8764 	void *tmp = NULL;
8765 	abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
8766 	enum zio_compress compress = HDR_GET_COMPRESS(hdr);
8767 	uint64_t psize = HDR_GET_PSIZE(hdr);
8768 	uint64_t size = arc_hdr_size(hdr);
8769 	boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
8770 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
8771 	dsl_crypto_key_t *dck = NULL;
8772 	uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
8773 	boolean_t no_crypt = B_FALSE;
8774 
8775 	ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8776 	    !HDR_COMPRESSION_ENABLED(hdr)) ||
8777 	    HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
8778 	ASSERT3U(psize, <=, asize);
8779 
8780 	/*
8781 	 * If this data simply needs its own buffer, we simply allocate it
8782 	 * and copy the data. This may be done to eliminate a dependency on a
8783 	 * shared buffer or to reallocate the buffer to match asize.
8784 	 */
8785 	if (HDR_HAS_RABD(hdr) && asize != psize) {
8786 		ASSERT3U(asize, >=, psize);
8787 		to_write = abd_alloc_for_io(asize, ismd);
8788 		abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
8789 		if (psize != asize)
8790 			abd_zero_off(to_write, psize, asize - psize);
8791 		goto out;
8792 	}
8793 
8794 	if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
8795 	    !HDR_ENCRYPTED(hdr)) {
8796 		ASSERT3U(size, ==, psize);
8797 		to_write = abd_alloc_for_io(asize, ismd);
8798 		abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8799 		if (size != asize)
8800 			abd_zero_off(to_write, size, asize - size);
8801 		goto out;
8802 	}
8803 
8804 	if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
8805 		cabd = abd_alloc_for_io(asize, ismd);
8806 		tmp = abd_borrow_buf(cabd, asize);
8807 
8808 		psize = zio_compress_data(compress, to_write, tmp, size,
8809 		    hdr->b_complevel);
8810 
8811 		if (psize >= size) {
8812 			abd_return_buf(cabd, tmp, asize);
8813 			HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
8814 			to_write = cabd;
8815 			abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8816 			if (size != asize)
8817 				abd_zero_off(to_write, size, asize - size);
8818 			goto encrypt;
8819 		}
8820 		ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
8821 		if (psize < asize)
8822 			bzero((char *)tmp + psize, asize - psize);
8823 		psize = HDR_GET_PSIZE(hdr);
8824 		abd_return_buf_copy(cabd, tmp, asize);
8825 		to_write = cabd;
8826 	}
8827 
8828 encrypt:
8829 	if (HDR_ENCRYPTED(hdr)) {
8830 		eabd = abd_alloc_for_io(asize, ismd);
8831 
8832 		/*
8833 		 * If the dataset was disowned before the buffer
8834 		 * made it to this point, the key to re-encrypt
8835 		 * it won't be available. In this case we simply
8836 		 * won't write the buffer to the L2ARC.
8837 		 */
8838 		ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
8839 		    FTAG, &dck);
8840 		if (ret != 0)
8841 			goto error;
8842 
8843 		ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
8844 		    hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
8845 		    hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
8846 		    &no_crypt);
8847 		if (ret != 0)
8848 			goto error;
8849 
8850 		if (no_crypt)
8851 			abd_copy(eabd, to_write, psize);
8852 
8853 		if (psize != asize)
8854 			abd_zero_off(eabd, psize, asize - psize);
8855 
8856 		/* assert that the MAC we got here matches the one we saved */
8857 		ASSERT0(bcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
8858 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8859 
8860 		if (to_write == cabd)
8861 			abd_free(cabd);
8862 
8863 		to_write = eabd;
8864 	}
8865 
8866 out:
8867 	ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
8868 	*abd_out = to_write;
8869 	return (0);
8870 
8871 error:
8872 	if (dck != NULL)
8873 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8874 	if (cabd != NULL)
8875 		abd_free(cabd);
8876 	if (eabd != NULL)
8877 		abd_free(eabd);
8878 
8879 	*abd_out = NULL;
8880 	return (ret);
8881 }
8882 
8883 static void
8884 l2arc_blk_fetch_done(zio_t *zio)
8885 {
8886 	l2arc_read_callback_t *cb;
8887 
8888 	cb = zio->io_private;
8889 	if (cb->l2rcb_abd != NULL)
8890 		abd_put(cb->l2rcb_abd);
8891 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8892 }
8893 
8894 /*
8895  * Find and write ARC buffers to the L2ARC device.
8896  *
8897  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
8898  * for reading until they have completed writing.
8899  * The headroom_boost is an in-out parameter used to maintain headroom boost
8900  * state between calls to this function.
8901  *
8902  * Returns the number of bytes actually written (which may be smaller than
8903  * the delta by which the device hand has changed due to alignment and the
8904  * writing of log blocks).
8905  */
8906 static uint64_t
8907 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
8908 {
8909 	arc_buf_hdr_t 		*hdr, *hdr_prev, *head;
8910 	uint64_t 		write_asize, write_psize, write_lsize, headroom;
8911 	boolean_t		full;
8912 	l2arc_write_callback_t	*cb = NULL;
8913 	zio_t 			*pio, *wzio;
8914 	uint64_t 		guid = spa_load_guid(spa);
8915 
8916 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
8917 
8918 	pio = NULL;
8919 	write_lsize = write_asize = write_psize = 0;
8920 	full = B_FALSE;
8921 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
8922 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
8923 
8924 	/*
8925 	 * Copy buffers for L2ARC writing.
8926 	 */
8927 	for (int try = 0; try < L2ARC_FEED_TYPES; try++) {
8928 		/*
8929 		 * If try == 1 or 3, we cache MRU metadata and data
8930 		 * respectively.
8931 		 */
8932 		if (l2arc_mfuonly) {
8933 			if (try == 1 || try == 3)
8934 				continue;
8935 		}
8936 
8937 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
8938 		uint64_t passed_sz = 0;
8939 
8940 		VERIFY3P(mls, !=, NULL);
8941 
8942 		/*
8943 		 * L2ARC fast warmup.
8944 		 *
8945 		 * Until the ARC is warm and starts to evict, read from the
8946 		 * head of the ARC lists rather than the tail.
8947 		 */
8948 		if (arc_warm == B_FALSE)
8949 			hdr = multilist_sublist_head(mls);
8950 		else
8951 			hdr = multilist_sublist_tail(mls);
8952 
8953 		headroom = target_sz * l2arc_headroom;
8954 		if (zfs_compressed_arc_enabled)
8955 			headroom = (headroom * l2arc_headroom_boost) / 100;
8956 
8957 		for (; hdr; hdr = hdr_prev) {
8958 			kmutex_t *hash_lock;
8959 			abd_t *to_write = NULL;
8960 
8961 			if (arc_warm == B_FALSE)
8962 				hdr_prev = multilist_sublist_next(mls, hdr);
8963 			else
8964 				hdr_prev = multilist_sublist_prev(mls, hdr);
8965 
8966 			hash_lock = HDR_LOCK(hdr);
8967 			if (!mutex_tryenter(hash_lock)) {
8968 				/*
8969 				 * Skip this buffer rather than waiting.
8970 				 */
8971 				continue;
8972 			}
8973 
8974 			passed_sz += HDR_GET_LSIZE(hdr);
8975 			if (l2arc_headroom != 0 && passed_sz > headroom) {
8976 				/*
8977 				 * Searched too far.
8978 				 */
8979 				mutex_exit(hash_lock);
8980 				break;
8981 			}
8982 
8983 			if (!l2arc_write_eligible(guid, hdr)) {
8984 				mutex_exit(hash_lock);
8985 				continue;
8986 			}
8987 
8988 			/*
8989 			 * We rely on the L1 portion of the header below, so
8990 			 * it's invalid for this header to have been evicted out
8991 			 * of the ghost cache, prior to being written out. The
8992 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8993 			 */
8994 			ASSERT(HDR_HAS_L1HDR(hdr));
8995 
8996 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8997 			ASSERT3U(arc_hdr_size(hdr), >, 0);
8998 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
8999 			    HDR_HAS_RABD(hdr));
9000 			uint64_t psize = HDR_GET_PSIZE(hdr);
9001 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
9002 			    psize);
9003 
9004 			if ((write_asize + asize) > target_sz) {
9005 				full = B_TRUE;
9006 				mutex_exit(hash_lock);
9007 				break;
9008 			}
9009 
9010 			/*
9011 			 * We rely on the L1 portion of the header below, so
9012 			 * it's invalid for this header to have been evicted out
9013 			 * of the ghost cache, prior to being written out. The
9014 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
9015 			 */
9016 			arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
9017 			ASSERT(HDR_HAS_L1HDR(hdr));
9018 
9019 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
9020 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
9021 			    HDR_HAS_RABD(hdr));
9022 			ASSERT3U(arc_hdr_size(hdr), >, 0);
9023 
9024 			/*
9025 			 * If this header has b_rabd, we can use this since it
9026 			 * must always match the data exactly as it exists on
9027 			 * disk. Otherwise, the L2ARC can normally use the
9028 			 * hdr's data, but if we're sharing data between the
9029 			 * hdr and one of its bufs, L2ARC needs its own copy of
9030 			 * the data so that the ZIO below can't race with the
9031 			 * buf consumer. To ensure that this copy will be
9032 			 * available for the lifetime of the ZIO and be cleaned
9033 			 * up afterwards, we add it to the l2arc_free_on_write
9034 			 * queue. If we need to apply any transforms to the
9035 			 * data (compression, encryption) we will also need the
9036 			 * extra buffer.
9037 			 */
9038 			if (HDR_HAS_RABD(hdr) && psize == asize) {
9039 				to_write = hdr->b_crypt_hdr.b_rabd;
9040 			} else if ((HDR_COMPRESSION_ENABLED(hdr) ||
9041 			    HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
9042 			    !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
9043 			    psize == asize) {
9044 				to_write = hdr->b_l1hdr.b_pabd;
9045 			} else {
9046 				int ret;
9047 				arc_buf_contents_t type = arc_buf_type(hdr);
9048 
9049 				ret = l2arc_apply_transforms(spa, hdr, asize,
9050 				    &to_write);
9051 				if (ret != 0) {
9052 					arc_hdr_clear_flags(hdr,
9053 					    ARC_FLAG_L2_WRITING);
9054 					mutex_exit(hash_lock);
9055 					continue;
9056 				}
9057 
9058 				l2arc_free_abd_on_write(to_write, asize, type);
9059 			}
9060 
9061 			if (pio == NULL) {
9062 				/*
9063 				 * Insert a dummy header on the buflist so
9064 				 * l2arc_write_done() can find where the
9065 				 * write buffers begin without searching.
9066 				 */
9067 				mutex_enter(&dev->l2ad_mtx);
9068 				list_insert_head(&dev->l2ad_buflist, head);
9069 				mutex_exit(&dev->l2ad_mtx);
9070 
9071 				cb = kmem_alloc(
9072 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
9073 				cb->l2wcb_dev = dev;
9074 				cb->l2wcb_head = head;
9075 				/*
9076 				 * Create a list to save allocated abd buffers
9077 				 * for l2arc_log_blk_commit().
9078 				 */
9079 				list_create(&cb->l2wcb_abd_list,
9080 				    sizeof (l2arc_lb_abd_buf_t),
9081 				    offsetof(l2arc_lb_abd_buf_t, node));
9082 				pio = zio_root(spa, l2arc_write_done, cb,
9083 				    ZIO_FLAG_CANFAIL);
9084 			}
9085 
9086 			hdr->b_l2hdr.b_dev = dev;
9087 			hdr->b_l2hdr.b_hits = 0;
9088 
9089 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
9090 			arc_hdr_set_flags(hdr, ARC_FLAG_HAS_L2HDR);
9091 
9092 			mutex_enter(&dev->l2ad_mtx);
9093 			list_insert_head(&dev->l2ad_buflist, hdr);
9094 			mutex_exit(&dev->l2ad_mtx);
9095 
9096 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
9097 			    arc_hdr_size(hdr), hdr);
9098 
9099 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
9100 			    hdr->b_l2hdr.b_daddr, asize, to_write,
9101 			    ZIO_CHECKSUM_OFF, NULL, hdr,
9102 			    ZIO_PRIORITY_ASYNC_WRITE,
9103 			    ZIO_FLAG_CANFAIL, B_FALSE);
9104 
9105 			write_lsize += HDR_GET_LSIZE(hdr);
9106 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
9107 			    zio_t *, wzio);
9108 
9109 			write_psize += psize;
9110 			write_asize += asize;
9111 			dev->l2ad_hand += asize;
9112 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9113 
9114 			mutex_exit(hash_lock);
9115 
9116 			/*
9117 			 * Append buf info to current log and commit if full.
9118 			 * arcstat_l2_{size,asize} kstats are updated
9119 			 * internally.
9120 			 */
9121 			if (l2arc_log_blk_insert(dev, hdr))
9122 				l2arc_log_blk_commit(dev, pio, cb);
9123 
9124 			zio_nowait(wzio);
9125 		}
9126 
9127 		multilist_sublist_unlock(mls);
9128 
9129 		if (full == B_TRUE)
9130 			break;
9131 	}
9132 
9133 	/* No buffers selected for writing? */
9134 	if (pio == NULL) {
9135 		ASSERT0(write_lsize);
9136 		ASSERT(!HDR_HAS_L1HDR(head));
9137 		kmem_cache_free(hdr_l2only_cache, head);
9138 
9139 		/*
9140 		 * Although we did not write any buffers l2ad_evict may
9141 		 * have advanced.
9142 		 */
9143 		l2arc_dev_hdr_update(dev);
9144 
9145 		return (0);
9146 	}
9147 
9148 	if (!dev->l2ad_first)
9149 		ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
9150 
9151 	ASSERT3U(write_asize, <=, target_sz);
9152 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
9153 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
9154 	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
9155 	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
9156 
9157 	dev->l2ad_writing = B_TRUE;
9158 	(void) zio_wait(pio);
9159 	dev->l2ad_writing = B_FALSE;
9160 
9161 	/*
9162 	 * Update the device header after the zio completes as
9163 	 * l2arc_write_done() may have updated the memory holding the log block
9164 	 * pointers in the device header.
9165 	 */
9166 	l2arc_dev_hdr_update(dev);
9167 
9168 	return (write_asize);
9169 }
9170 
9171 static boolean_t
9172 l2arc_hdr_limit_reached(void)
9173 {
9174 	int64_t s = aggsum_upper_bound(&astat_l2_hdr_size);
9175 
9176 	return (arc_reclaim_needed() || (s > arc_meta_limit * 3 / 4) ||
9177 	    (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
9178 }
9179 
9180 /*
9181  * This thread feeds the L2ARC at regular intervals.  This is the beating
9182  * heart of the L2ARC.
9183  */
9184 /* ARGSUSED */
9185 static void
9186 l2arc_feed_thread(void *unused)
9187 {
9188 	callb_cpr_t cpr;
9189 	l2arc_dev_t *dev;
9190 	spa_t *spa;
9191 	uint64_t size, wrote;
9192 	clock_t begin, next = ddi_get_lbolt();
9193 	fstrans_cookie_t cookie;
9194 
9195 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
9196 
9197 	mutex_enter(&l2arc_feed_thr_lock);
9198 
9199 	cookie = spl_fstrans_mark();
9200 	while (l2arc_thread_exit == 0) {
9201 		CALLB_CPR_SAFE_BEGIN(&cpr);
9202 		(void) cv_timedwait_idle(&l2arc_feed_thr_cv,
9203 		    &l2arc_feed_thr_lock, next);
9204 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
9205 		next = ddi_get_lbolt() + hz;
9206 
9207 		/*
9208 		 * Quick check for L2ARC devices.
9209 		 */
9210 		mutex_enter(&l2arc_dev_mtx);
9211 		if (l2arc_ndev == 0) {
9212 			mutex_exit(&l2arc_dev_mtx);
9213 			continue;
9214 		}
9215 		mutex_exit(&l2arc_dev_mtx);
9216 		begin = ddi_get_lbolt();
9217 
9218 		/*
9219 		 * This selects the next l2arc device to write to, and in
9220 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
9221 		 * will return NULL if there are now no l2arc devices or if
9222 		 * they are all faulted.
9223 		 *
9224 		 * If a device is returned, its spa's config lock is also
9225 		 * held to prevent device removal.  l2arc_dev_get_next()
9226 		 * will grab and release l2arc_dev_mtx.
9227 		 */
9228 		if ((dev = l2arc_dev_get_next()) == NULL)
9229 			continue;
9230 
9231 		spa = dev->l2ad_spa;
9232 		ASSERT3P(spa, !=, NULL);
9233 
9234 		/*
9235 		 * If the pool is read-only then force the feed thread to
9236 		 * sleep a little longer.
9237 		 */
9238 		if (!spa_writeable(spa)) {
9239 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
9240 			spa_config_exit(spa, SCL_L2ARC, dev);
9241 			continue;
9242 		}
9243 
9244 		/*
9245 		 * Avoid contributing to memory pressure.
9246 		 */
9247 		if (l2arc_hdr_limit_reached()) {
9248 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
9249 			spa_config_exit(spa, SCL_L2ARC, dev);
9250 			continue;
9251 		}
9252 
9253 		ARCSTAT_BUMP(arcstat_l2_feeds);
9254 
9255 		size = l2arc_write_size(dev);
9256 
9257 		/*
9258 		 * Evict L2ARC buffers that will be overwritten.
9259 		 */
9260 		l2arc_evict(dev, size, B_FALSE);
9261 
9262 		/*
9263 		 * Write ARC buffers.
9264 		 */
9265 		wrote = l2arc_write_buffers(spa, dev, size);
9266 
9267 		/*
9268 		 * Calculate interval between writes.
9269 		 */
9270 		next = l2arc_write_interval(begin, size, wrote);
9271 		spa_config_exit(spa, SCL_L2ARC, dev);
9272 	}
9273 	spl_fstrans_unmark(cookie);
9274 
9275 	l2arc_thread_exit = 0;
9276 	cv_broadcast(&l2arc_feed_thr_cv);
9277 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
9278 	thread_exit();
9279 }
9280 
9281 boolean_t
9282 l2arc_vdev_present(vdev_t *vd)
9283 {
9284 	return (l2arc_vdev_get(vd) != NULL);
9285 }
9286 
9287 /*
9288  * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
9289  * the vdev_t isn't an L2ARC device.
9290  */
9291 l2arc_dev_t *
9292 l2arc_vdev_get(vdev_t *vd)
9293 {
9294 	l2arc_dev_t	*dev;
9295 
9296 	mutex_enter(&l2arc_dev_mtx);
9297 	for (dev = list_head(l2arc_dev_list); dev != NULL;
9298 	    dev = list_next(l2arc_dev_list, dev)) {
9299 		if (dev->l2ad_vdev == vd)
9300 			break;
9301 	}
9302 	mutex_exit(&l2arc_dev_mtx);
9303 
9304 	return (dev);
9305 }
9306 
9307 /*
9308  * Add a vdev for use by the L2ARC.  By this point the spa has already
9309  * validated the vdev and opened it.
9310  */
9311 void
9312 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
9313 {
9314 	l2arc_dev_t		*adddev;
9315 	uint64_t		l2dhdr_asize;
9316 
9317 	ASSERT(!l2arc_vdev_present(vd));
9318 
9319 	/*
9320 	 * Create a new l2arc device entry.
9321 	 */
9322 	adddev = vmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
9323 	adddev->l2ad_spa = spa;
9324 	adddev->l2ad_vdev = vd;
9325 	/* leave extra size for an l2arc device header */
9326 	l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
9327 	    MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
9328 	adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
9329 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
9330 	ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
9331 	adddev->l2ad_hand = adddev->l2ad_start;
9332 	adddev->l2ad_evict = adddev->l2ad_start;
9333 	adddev->l2ad_first = B_TRUE;
9334 	adddev->l2ad_writing = B_FALSE;
9335 	adddev->l2ad_trim_all = B_FALSE;
9336 	list_link_init(&adddev->l2ad_node);
9337 	adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
9338 
9339 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
9340 	/*
9341 	 * This is a list of all ARC buffers that are still valid on the
9342 	 * device.
9343 	 */
9344 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
9345 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
9346 
9347 	/*
9348 	 * This is a list of pointers to log blocks that are still present
9349 	 * on the device.
9350 	 */
9351 	list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
9352 	    offsetof(l2arc_lb_ptr_buf_t, node));
9353 
9354 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
9355 	zfs_refcount_create(&adddev->l2ad_alloc);
9356 	zfs_refcount_create(&adddev->l2ad_lb_asize);
9357 	zfs_refcount_create(&adddev->l2ad_lb_count);
9358 
9359 	/*
9360 	 * Add device to global list
9361 	 */
9362 	mutex_enter(&l2arc_dev_mtx);
9363 	list_insert_head(l2arc_dev_list, adddev);
9364 	atomic_inc_64(&l2arc_ndev);
9365 	mutex_exit(&l2arc_dev_mtx);
9366 
9367 	/*
9368 	 * Decide if vdev is eligible for L2ARC rebuild
9369 	 */
9370 	l2arc_rebuild_vdev(adddev->l2ad_vdev, B_FALSE);
9371 }
9372 
9373 void
9374 l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
9375 {
9376 	l2arc_dev_t		*dev = NULL;
9377 	l2arc_dev_hdr_phys_t	*l2dhdr;
9378 	uint64_t		l2dhdr_asize;
9379 	spa_t			*spa;
9380 	int			err;
9381 	boolean_t		l2dhdr_valid = B_TRUE;
9382 
9383 	dev = l2arc_vdev_get(vd);
9384 	ASSERT3P(dev, !=, NULL);
9385 	spa = dev->l2ad_spa;
9386 	l2dhdr = dev->l2ad_dev_hdr;
9387 	l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9388 
9389 	/*
9390 	 * The L2ARC has to hold at least the payload of one log block for
9391 	 * them to be restored (persistent L2ARC). The payload of a log block
9392 	 * depends on the amount of its log entries. We always write log blocks
9393 	 * with 1022 entries. How many of them are committed or restored depends
9394 	 * on the size of the L2ARC device. Thus the maximum payload of
9395 	 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
9396 	 * is less than that, we reduce the amount of committed and restored
9397 	 * log entries per block so as to enable persistence.
9398 	 */
9399 	if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
9400 		dev->l2ad_log_entries = 0;
9401 	} else {
9402 		dev->l2ad_log_entries = MIN((dev->l2ad_end -
9403 		    dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
9404 		    L2ARC_LOG_BLK_MAX_ENTRIES);
9405 	}
9406 
9407 	/*
9408 	 * Read the device header, if an error is returned do not rebuild L2ARC.
9409 	 */
9410 	if ((err = l2arc_dev_hdr_read(dev)) != 0)
9411 		l2dhdr_valid = B_FALSE;
9412 
9413 	if (l2dhdr_valid && dev->l2ad_log_entries > 0) {
9414 		/*
9415 		 * If we are onlining a cache device (vdev_reopen) that was
9416 		 * still present (l2arc_vdev_present()) and rebuild is enabled,
9417 		 * we should evict all ARC buffers and pointers to log blocks
9418 		 * and reclaim their space before restoring its contents to
9419 		 * L2ARC.
9420 		 */
9421 		if (reopen) {
9422 			if (!l2arc_rebuild_enabled) {
9423 				return;
9424 			} else {
9425 				l2arc_evict(dev, 0, B_TRUE);
9426 				/* start a new log block */
9427 				dev->l2ad_log_ent_idx = 0;
9428 				dev->l2ad_log_blk_payload_asize = 0;
9429 				dev->l2ad_log_blk_payload_start = 0;
9430 			}
9431 		}
9432 		/*
9433 		 * Just mark the device as pending for a rebuild. We won't
9434 		 * be starting a rebuild in line here as it would block pool
9435 		 * import. Instead spa_load_impl will hand that off to an
9436 		 * async task which will call l2arc_spa_rebuild_start.
9437 		 */
9438 		dev->l2ad_rebuild = B_TRUE;
9439 	} else if (spa_writeable(spa)) {
9440 		/*
9441 		 * In this case TRIM the whole device if l2arc_trim_ahead > 0,
9442 		 * otherwise create a new header. We zero out the memory holding
9443 		 * the header to reset dh_start_lbps. If we TRIM the whole
9444 		 * device the new header will be written by
9445 		 * vdev_trim_l2arc_thread() at the end of the TRIM to update the
9446 		 * trim_state in the header too. When reading the header, if
9447 		 * trim_state is not VDEV_TRIM_COMPLETE and l2arc_trim_ahead > 0
9448 		 * we opt to TRIM the whole device again.
9449 		 */
9450 		if (l2arc_trim_ahead > 0) {
9451 			dev->l2ad_trim_all = B_TRUE;
9452 		} else {
9453 			bzero(l2dhdr, l2dhdr_asize);
9454 			l2arc_dev_hdr_update(dev);
9455 		}
9456 	}
9457 }
9458 
9459 /*
9460  * Remove a vdev from the L2ARC.
9461  */
9462 void
9463 l2arc_remove_vdev(vdev_t *vd)
9464 {
9465 	l2arc_dev_t *remdev = NULL;
9466 
9467 	/*
9468 	 * Find the device by vdev
9469 	 */
9470 	remdev = l2arc_vdev_get(vd);
9471 	ASSERT3P(remdev, !=, NULL);
9472 
9473 	/*
9474 	 * Cancel any ongoing or scheduled rebuild.
9475 	 */
9476 	mutex_enter(&l2arc_rebuild_thr_lock);
9477 	if (remdev->l2ad_rebuild_began == B_TRUE) {
9478 		remdev->l2ad_rebuild_cancel = B_TRUE;
9479 		while (remdev->l2ad_rebuild == B_TRUE)
9480 			cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
9481 	}
9482 	mutex_exit(&l2arc_rebuild_thr_lock);
9483 
9484 	/*
9485 	 * Remove device from global list
9486 	 */
9487 	mutex_enter(&l2arc_dev_mtx);
9488 	list_remove(l2arc_dev_list, remdev);
9489 	l2arc_dev_last = NULL;		/* may have been invalidated */
9490 	atomic_dec_64(&l2arc_ndev);
9491 	mutex_exit(&l2arc_dev_mtx);
9492 
9493 	/*
9494 	 * Clear all buflists and ARC references.  L2ARC device flush.
9495 	 */
9496 	l2arc_evict(remdev, 0, B_TRUE);
9497 	list_destroy(&remdev->l2ad_buflist);
9498 	ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
9499 	list_destroy(&remdev->l2ad_lbptr_list);
9500 	mutex_destroy(&remdev->l2ad_mtx);
9501 	zfs_refcount_destroy(&remdev->l2ad_alloc);
9502 	zfs_refcount_destroy(&remdev->l2ad_lb_asize);
9503 	zfs_refcount_destroy(&remdev->l2ad_lb_count);
9504 	kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
9505 	vmem_free(remdev, sizeof (l2arc_dev_t));
9506 }
9507 
9508 void
9509 l2arc_init(void)
9510 {
9511 	l2arc_thread_exit = 0;
9512 	l2arc_ndev = 0;
9513 	l2arc_writes_sent = 0;
9514 	l2arc_writes_done = 0;
9515 
9516 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9517 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
9518 	mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9519 	cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
9520 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
9521 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
9522 
9523 	l2arc_dev_list = &L2ARC_dev_list;
9524 	l2arc_free_on_write = &L2ARC_free_on_write;
9525 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
9526 	    offsetof(l2arc_dev_t, l2ad_node));
9527 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
9528 	    offsetof(l2arc_data_free_t, l2df_list_node));
9529 }
9530 
9531 void
9532 l2arc_fini(void)
9533 {
9534 	mutex_destroy(&l2arc_feed_thr_lock);
9535 	cv_destroy(&l2arc_feed_thr_cv);
9536 	mutex_destroy(&l2arc_rebuild_thr_lock);
9537 	cv_destroy(&l2arc_rebuild_thr_cv);
9538 	mutex_destroy(&l2arc_dev_mtx);
9539 	mutex_destroy(&l2arc_free_on_write_mtx);
9540 
9541 	list_destroy(l2arc_dev_list);
9542 	list_destroy(l2arc_free_on_write);
9543 }
9544 
9545 void
9546 l2arc_start(void)
9547 {
9548 	if (!(spa_mode_global & SPA_MODE_WRITE))
9549 		return;
9550 
9551 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
9552 	    TS_RUN, defclsyspri);
9553 }
9554 
9555 void
9556 l2arc_stop(void)
9557 {
9558 	if (!(spa_mode_global & SPA_MODE_WRITE))
9559 		return;
9560 
9561 	mutex_enter(&l2arc_feed_thr_lock);
9562 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
9563 	l2arc_thread_exit = 1;
9564 	while (l2arc_thread_exit != 0)
9565 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
9566 	mutex_exit(&l2arc_feed_thr_lock);
9567 }
9568 
9569 /*
9570  * Punches out rebuild threads for the L2ARC devices in a spa. This should
9571  * be called after pool import from the spa async thread, since starting
9572  * these threads directly from spa_import() will make them part of the
9573  * "zpool import" context and delay process exit (and thus pool import).
9574  */
9575 void
9576 l2arc_spa_rebuild_start(spa_t *spa)
9577 {
9578 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
9579 
9580 	/*
9581 	 * Locate the spa's l2arc devices and kick off rebuild threads.
9582 	 */
9583 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
9584 		l2arc_dev_t *dev =
9585 		    l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
9586 		if (dev == NULL) {
9587 			/* Don't attempt a rebuild if the vdev is UNAVAIL */
9588 			continue;
9589 		}
9590 		mutex_enter(&l2arc_rebuild_thr_lock);
9591 		if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
9592 			dev->l2ad_rebuild_began = B_TRUE;
9593 			(void) thread_create(NULL, 0, l2arc_dev_rebuild_thread,
9594 			    dev, 0, &p0, TS_RUN, minclsyspri);
9595 		}
9596 		mutex_exit(&l2arc_rebuild_thr_lock);
9597 	}
9598 }
9599 
9600 /*
9601  * Main entry point for L2ARC rebuilding.
9602  */
9603 static void
9604 l2arc_dev_rebuild_thread(void *arg)
9605 {
9606 	l2arc_dev_t *dev = arg;
9607 
9608 	VERIFY(!dev->l2ad_rebuild_cancel);
9609 	VERIFY(dev->l2ad_rebuild);
9610 	(void) l2arc_rebuild(dev);
9611 	mutex_enter(&l2arc_rebuild_thr_lock);
9612 	dev->l2ad_rebuild_began = B_FALSE;
9613 	dev->l2ad_rebuild = B_FALSE;
9614 	mutex_exit(&l2arc_rebuild_thr_lock);
9615 
9616 	thread_exit();
9617 }
9618 
9619 /*
9620  * This function implements the actual L2ARC metadata rebuild. It:
9621  * starts reading the log block chain and restores each block's contents
9622  * to memory (reconstructing arc_buf_hdr_t's).
9623  *
9624  * Operation stops under any of the following conditions:
9625  *
9626  * 1) We reach the end of the log block chain.
9627  * 2) We encounter *any* error condition (cksum errors, io errors)
9628  */
9629 static int
9630 l2arc_rebuild(l2arc_dev_t *dev)
9631 {
9632 	vdev_t			*vd = dev->l2ad_vdev;
9633 	spa_t			*spa = vd->vdev_spa;
9634 	int			err = 0;
9635 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9636 	l2arc_log_blk_phys_t	*this_lb, *next_lb;
9637 	zio_t			*this_io = NULL, *next_io = NULL;
9638 	l2arc_log_blkptr_t	lbps[2];
9639 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
9640 	boolean_t		lock_held;
9641 
9642 	this_lb = vmem_zalloc(sizeof (*this_lb), KM_SLEEP);
9643 	next_lb = vmem_zalloc(sizeof (*next_lb), KM_SLEEP);
9644 
9645 	/*
9646 	 * We prevent device removal while issuing reads to the device,
9647 	 * then during the rebuilding phases we drop this lock again so
9648 	 * that a spa_unload or device remove can be initiated - this is
9649 	 * safe, because the spa will signal us to stop before removing
9650 	 * our device and wait for us to stop.
9651 	 */
9652 	spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
9653 	lock_held = B_TRUE;
9654 
9655 	/*
9656 	 * Retrieve the persistent L2ARC device state.
9657 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9658 	 */
9659 	dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
9660 	dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
9661 	    L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
9662 	    dev->l2ad_start);
9663 	dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
9664 
9665 	vd->vdev_trim_action_time = l2dhdr->dh_trim_action_time;
9666 	vd->vdev_trim_state = l2dhdr->dh_trim_state;
9667 
9668 	/*
9669 	 * In case the zfs module parameter l2arc_rebuild_enabled is false
9670 	 * we do not start the rebuild process.
9671 	 */
9672 	if (!l2arc_rebuild_enabled)
9673 		goto out;
9674 
9675 	/* Prepare the rebuild process */
9676 	bcopy(l2dhdr->dh_start_lbps, lbps, sizeof (lbps));
9677 
9678 	/* Start the rebuild process */
9679 	for (;;) {
9680 		if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
9681 			break;
9682 
9683 		if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
9684 		    this_lb, next_lb, this_io, &next_io)) != 0)
9685 			goto out;
9686 
9687 		/*
9688 		 * Our memory pressure valve. If the system is running low
9689 		 * on memory, rather than swamping memory with new ARC buf
9690 		 * hdrs, we opt not to rebuild the L2ARC. At this point,
9691 		 * however, we have already set up our L2ARC dev to chain in
9692 		 * new metadata log blocks, so the user may choose to offline/
9693 		 * online the L2ARC dev at a later time (or re-import the pool)
9694 		 * to reconstruct it (when there's less memory pressure).
9695 		 */
9696 		if (l2arc_hdr_limit_reached()) {
9697 			ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
9698 			cmn_err(CE_NOTE, "System running low on memory, "
9699 			    "aborting L2ARC rebuild.");
9700 			err = SET_ERROR(ENOMEM);
9701 			goto out;
9702 		}
9703 
9704 		spa_config_exit(spa, SCL_L2ARC, vd);
9705 		lock_held = B_FALSE;
9706 
9707 		/*
9708 		 * Now that we know that the next_lb checks out alright, we
9709 		 * can start reconstruction from this log block.
9710 		 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9711 		 */
9712 		uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
9713 		l2arc_log_blk_restore(dev, this_lb, asize, lbps[0].lbp_daddr);
9714 
9715 		/*
9716 		 * log block restored, include its pointer in the list of
9717 		 * pointers to log blocks present in the L2ARC device.
9718 		 */
9719 		lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
9720 		lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
9721 		    KM_SLEEP);
9722 		bcopy(&lbps[0], lb_ptr_buf->lb_ptr,
9723 		    sizeof (l2arc_log_blkptr_t));
9724 		mutex_enter(&dev->l2ad_mtx);
9725 		list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
9726 		ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
9727 		ARCSTAT_BUMP(arcstat_l2_log_blk_count);
9728 		zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
9729 		zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
9730 		mutex_exit(&dev->l2ad_mtx);
9731 		vdev_space_update(vd, asize, 0, 0);
9732 
9733 		/*
9734 		 * Protection against loops of log blocks:
9735 		 *
9736 		 *				       l2ad_hand  l2ad_evict
9737 		 *                                         V	      V
9738 		 * l2ad_start |=======================================| l2ad_end
9739 		 *             -----|||----|||---|||----|||
9740 		 *                  (3)    (2)   (1)    (0)
9741 		 *             ---|||---|||----|||---|||
9742 		 *		  (7)   (6)    (5)   (4)
9743 		 *
9744 		 * In this situation the pointer of log block (4) passes
9745 		 * l2arc_log_blkptr_valid() but the log block should not be
9746 		 * restored as it is overwritten by the payload of log block
9747 		 * (0). Only log blocks (0)-(3) should be restored. We check
9748 		 * whether l2ad_evict lies in between the payload starting
9749 		 * offset of the next log block (lbps[1].lbp_payload_start)
9750 		 * and the payload starting offset of the present log block
9751 		 * (lbps[0].lbp_payload_start). If true and this isn't the
9752 		 * first pass, we are looping from the beginning and we should
9753 		 * stop.
9754 		 */
9755 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
9756 		    lbps[0].lbp_payload_start, dev->l2ad_evict) &&
9757 		    !dev->l2ad_first)
9758 			goto out;
9759 
9760 		for (;;) {
9761 			mutex_enter(&l2arc_rebuild_thr_lock);
9762 			if (dev->l2ad_rebuild_cancel) {
9763 				dev->l2ad_rebuild = B_FALSE;
9764 				cv_signal(&l2arc_rebuild_thr_cv);
9765 				mutex_exit(&l2arc_rebuild_thr_lock);
9766 				err = SET_ERROR(ECANCELED);
9767 				goto out;
9768 			}
9769 			mutex_exit(&l2arc_rebuild_thr_lock);
9770 			if (spa_config_tryenter(spa, SCL_L2ARC, vd,
9771 			    RW_READER)) {
9772 				lock_held = B_TRUE;
9773 				break;
9774 			}
9775 			/*
9776 			 * L2ARC config lock held by somebody in writer,
9777 			 * possibly due to them trying to remove us. They'll
9778 			 * likely to want us to shut down, so after a little
9779 			 * delay, we check l2ad_rebuild_cancel and retry
9780 			 * the lock again.
9781 			 */
9782 			delay(1);
9783 		}
9784 
9785 		/*
9786 		 * Continue with the next log block.
9787 		 */
9788 		lbps[0] = lbps[1];
9789 		lbps[1] = this_lb->lb_prev_lbp;
9790 		PTR_SWAP(this_lb, next_lb);
9791 		this_io = next_io;
9792 		next_io = NULL;
9793 		}
9794 
9795 	if (this_io != NULL)
9796 		l2arc_log_blk_fetch_abort(this_io);
9797 out:
9798 	if (next_io != NULL)
9799 		l2arc_log_blk_fetch_abort(next_io);
9800 	vmem_free(this_lb, sizeof (*this_lb));
9801 	vmem_free(next_lb, sizeof (*next_lb));
9802 
9803 	if (!l2arc_rebuild_enabled) {
9804 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9805 		    "disabled");
9806 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
9807 		ARCSTAT_BUMP(arcstat_l2_rebuild_success);
9808 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9809 		    "successful, restored %llu blocks",
9810 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9811 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
9812 		/*
9813 		 * No error but also nothing restored, meaning the lbps array
9814 		 * in the device header points to invalid/non-present log
9815 		 * blocks. Reset the header.
9816 		 */
9817 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9818 		    "no valid log blocks");
9819 		bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
9820 		l2arc_dev_hdr_update(dev);
9821 	} else if (err == ECANCELED) {
9822 		/*
9823 		 * In case the rebuild was canceled do not log to spa history
9824 		 * log as the pool may be in the process of being removed.
9825 		 */
9826 		zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
9827 		    zfs_refcount_count(&dev->l2ad_lb_count));
9828 	} else if (err != 0) {
9829 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9830 		    "aborted, restored %llu blocks",
9831 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9832 	}
9833 
9834 	if (lock_held)
9835 		spa_config_exit(spa, SCL_L2ARC, vd);
9836 
9837 	return (err);
9838 }
9839 
9840 /*
9841  * Attempts to read the device header on the provided L2ARC device and writes
9842  * it to `hdr'. On success, this function returns 0, otherwise the appropriate
9843  * error code is returned.
9844  */
9845 static int
9846 l2arc_dev_hdr_read(l2arc_dev_t *dev)
9847 {
9848 	int			err;
9849 	uint64_t		guid;
9850 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9851 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9852 	abd_t 			*abd;
9853 
9854 	guid = spa_guid(dev->l2ad_vdev->vdev_spa);
9855 
9856 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
9857 
9858 	err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
9859 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
9860 	    ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_ASYNC_READ,
9861 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
9862 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
9863 	    ZIO_FLAG_SPECULATIVE, B_FALSE));
9864 
9865 	abd_put(abd);
9866 
9867 	if (err != 0) {
9868 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
9869 		zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
9870 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
9871 		return (err);
9872 	}
9873 
9874 	if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
9875 		byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
9876 
9877 	if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
9878 	    l2dhdr->dh_spa_guid != guid ||
9879 	    l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
9880 	    l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
9881 	    l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
9882 	    l2dhdr->dh_end != dev->l2ad_end ||
9883 	    !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
9884 	    l2dhdr->dh_evict) ||
9885 	    (l2dhdr->dh_trim_state != VDEV_TRIM_COMPLETE &&
9886 	    l2arc_trim_ahead > 0)) {
9887 		/*
9888 		 * Attempt to rebuild a device containing no actual dev hdr
9889 		 * or containing a header from some other pool or from another
9890 		 * version of persistent L2ARC.
9891 		 */
9892 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
9893 		return (SET_ERROR(ENOTSUP));
9894 	}
9895 
9896 	return (0);
9897 }
9898 
9899 /*
9900  * Reads L2ARC log blocks from storage and validates their contents.
9901  *
9902  * This function implements a simple fetcher to make sure that while
9903  * we're processing one buffer the L2ARC is already fetching the next
9904  * one in the chain.
9905  *
9906  * The arguments this_lp and next_lp point to the current and next log block
9907  * address in the block chain. Similarly, this_lb and next_lb hold the
9908  * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
9909  *
9910  * The `this_io' and `next_io' arguments are used for block fetching.
9911  * When issuing the first blk IO during rebuild, you should pass NULL for
9912  * `this_io'. This function will then issue a sync IO to read the block and
9913  * also issue an async IO to fetch the next block in the block chain. The
9914  * fetched IO is returned in `next_io'. On subsequent calls to this
9915  * function, pass the value returned in `next_io' from the previous call
9916  * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
9917  * Prior to the call, you should initialize your `next_io' pointer to be
9918  * NULL. If no fetch IO was issued, the pointer is left set at NULL.
9919  *
9920  * On success, this function returns 0, otherwise it returns an appropriate
9921  * error code. On error the fetching IO is aborted and cleared before
9922  * returning from this function. Therefore, if we return `success', the
9923  * caller can assume that we have taken care of cleanup of fetch IOs.
9924  */
9925 static int
9926 l2arc_log_blk_read(l2arc_dev_t *dev,
9927     const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
9928     l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
9929     zio_t *this_io, zio_t **next_io)
9930 {
9931 	int		err = 0;
9932 	zio_cksum_t	cksum;
9933 	abd_t		*abd = NULL;
9934 	uint64_t	asize;
9935 
9936 	ASSERT(this_lbp != NULL && next_lbp != NULL);
9937 	ASSERT(this_lb != NULL && next_lb != NULL);
9938 	ASSERT(next_io != NULL && *next_io == NULL);
9939 	ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
9940 
9941 	/*
9942 	 * Check to see if we have issued the IO for this log block in a
9943 	 * previous run. If not, this is the first call, so issue it now.
9944 	 */
9945 	if (this_io == NULL) {
9946 		this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
9947 		    this_lb);
9948 	}
9949 
9950 	/*
9951 	 * Peek to see if we can start issuing the next IO immediately.
9952 	 */
9953 	if (l2arc_log_blkptr_valid(dev, next_lbp)) {
9954 		/*
9955 		 * Start issuing IO for the next log block early - this
9956 		 * should help keep the L2ARC device busy while we
9957 		 * decompress and restore this log block.
9958 		 */
9959 		*next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
9960 		    next_lb);
9961 	}
9962 
9963 	/* Wait for the IO to read this log block to complete */
9964 	if ((err = zio_wait(this_io)) != 0) {
9965 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
9966 		zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
9967 		    "offset: %llu, vdev guid: %llu", err, this_lbp->lbp_daddr,
9968 		    dev->l2ad_vdev->vdev_guid);
9969 		goto cleanup;
9970 	}
9971 
9972 	/*
9973 	 * Make sure the buffer checks out.
9974 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9975 	 */
9976 	asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
9977 	fletcher_4_native(this_lb, asize, NULL, &cksum);
9978 	if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
9979 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
9980 		zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
9981 		    "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
9982 		    this_lbp->lbp_daddr, dev->l2ad_vdev->vdev_guid,
9983 		    dev->l2ad_hand, dev->l2ad_evict);
9984 		err = SET_ERROR(ECKSUM);
9985 		goto cleanup;
9986 	}
9987 
9988 	/* Now we can take our time decoding this buffer */
9989 	switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
9990 	case ZIO_COMPRESS_OFF:
9991 		break;
9992 	case ZIO_COMPRESS_LZ4:
9993 		abd = abd_alloc_for_io(asize, B_TRUE);
9994 		abd_copy_from_buf_off(abd, this_lb, 0, asize);
9995 		if ((err = zio_decompress_data(
9996 		    L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
9997 		    abd, this_lb, asize, sizeof (*this_lb), NULL)) != 0) {
9998 			err = SET_ERROR(EINVAL);
9999 			goto cleanup;
10000 		}
10001 		break;
10002 	default:
10003 		err = SET_ERROR(EINVAL);
10004 		goto cleanup;
10005 	}
10006 	if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
10007 		byteswap_uint64_array(this_lb, sizeof (*this_lb));
10008 	if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
10009 		err = SET_ERROR(EINVAL);
10010 		goto cleanup;
10011 	}
10012 cleanup:
10013 	/* Abort an in-flight fetch I/O in case of error */
10014 	if (err != 0 && *next_io != NULL) {
10015 		l2arc_log_blk_fetch_abort(*next_io);
10016 		*next_io = NULL;
10017 	}
10018 	if (abd != NULL)
10019 		abd_free(abd);
10020 	return (err);
10021 }
10022 
10023 /*
10024  * Restores the payload of a log block to ARC. This creates empty ARC hdr
10025  * entries which only contain an l2arc hdr, essentially restoring the
10026  * buffers to their L2ARC evicted state. This function also updates space
10027  * usage on the L2ARC vdev to make sure it tracks restored buffers.
10028  */
10029 static void
10030 l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
10031     uint64_t lb_asize, uint64_t lb_daddr)
10032 {
10033 	uint64_t	size = 0, asize = 0;
10034 	uint64_t	log_entries = dev->l2ad_log_entries;
10035 
10036 	/*
10037 	 * Usually arc_adapt() is called only for data, not headers, but
10038 	 * since we may allocate significant amount of memory here, let ARC
10039 	 * grow its arc_c.
10040 	 */
10041 	arc_adapt(log_entries * HDR_L2ONLY_SIZE, arc_l2c_only);
10042 
10043 	for (int i = log_entries - 1; i >= 0; i--) {
10044 		/*
10045 		 * Restore goes in the reverse temporal direction to preserve
10046 		 * correct temporal ordering of buffers in the l2ad_buflist.
10047 		 * l2arc_hdr_restore also does a list_insert_tail instead of
10048 		 * list_insert_head on the l2ad_buflist:
10049 		 *
10050 		 *		LIST	l2ad_buflist		LIST
10051 		 *		HEAD  <------ (time) ------	TAIL
10052 		 * direction	+-----+-----+-----+-----+-----+    direction
10053 		 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
10054 		 * fill		+-----+-----+-----+-----+-----+
10055 		 *		^				^
10056 		 *		|				|
10057 		 *		|				|
10058 		 *	l2arc_feed_thread		l2arc_rebuild
10059 		 *	will place new bufs here	restores bufs here
10060 		 *
10061 		 * During l2arc_rebuild() the device is not used by
10062 		 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
10063 		 */
10064 		size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
10065 		asize += vdev_psize_to_asize(dev->l2ad_vdev,
10066 		    L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
10067 		l2arc_hdr_restore(&lb->lb_entries[i], dev);
10068 	}
10069 
10070 	/*
10071 	 * Record rebuild stats:
10072 	 *	size		Logical size of restored buffers in the L2ARC
10073 	 *	asize		Aligned size of restored buffers in the L2ARC
10074 	 */
10075 	ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
10076 	ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
10077 	ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
10078 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
10079 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
10080 	ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
10081 }
10082 
10083 /*
10084  * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
10085  * into a state indicating that it has been evicted to L2ARC.
10086  */
10087 static void
10088 l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
10089 {
10090 	arc_buf_hdr_t		*hdr, *exists;
10091 	kmutex_t		*hash_lock;
10092 	arc_buf_contents_t	type = L2BLK_GET_TYPE((le)->le_prop);
10093 	uint64_t		asize;
10094 
10095 	/*
10096 	 * Do all the allocation before grabbing any locks, this lets us
10097 	 * sleep if memory is full and we don't have to deal with failed
10098 	 * allocations.
10099 	 */
10100 	hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
10101 	    dev, le->le_dva, le->le_daddr,
10102 	    L2BLK_GET_PSIZE((le)->le_prop), le->le_birth,
10103 	    L2BLK_GET_COMPRESS((le)->le_prop), le->le_complevel,
10104 	    L2BLK_GET_PROTECTED((le)->le_prop),
10105 	    L2BLK_GET_PREFETCH((le)->le_prop));
10106 	asize = vdev_psize_to_asize(dev->l2ad_vdev,
10107 	    L2BLK_GET_PSIZE((le)->le_prop));
10108 
10109 	/*
10110 	 * vdev_space_update() has to be called before arc_hdr_destroy() to
10111 	 * avoid underflow since the latter also calls the former.
10112 	 */
10113 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10114 
10115 	ARCSTAT_INCR(arcstat_l2_lsize, HDR_GET_LSIZE(hdr));
10116 	ARCSTAT_INCR(arcstat_l2_psize, HDR_GET_PSIZE(hdr));
10117 
10118 	mutex_enter(&dev->l2ad_mtx);
10119 	list_insert_tail(&dev->l2ad_buflist, hdr);
10120 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
10121 	mutex_exit(&dev->l2ad_mtx);
10122 
10123 	exists = buf_hash_insert(hdr, &hash_lock);
10124 	if (exists) {
10125 		/* Buffer was already cached, no need to restore it. */
10126 		arc_hdr_destroy(hdr);
10127 		/*
10128 		 * If the buffer is already cached, check whether it has
10129 		 * L2ARC metadata. If not, enter them and update the flag.
10130 		 * This is important is case of onlining a cache device, since
10131 		 * we previously evicted all L2ARC metadata from ARC.
10132 		 */
10133 		if (!HDR_HAS_L2HDR(exists)) {
10134 			arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
10135 			exists->b_l2hdr.b_dev = dev;
10136 			exists->b_l2hdr.b_daddr = le->le_daddr;
10137 			mutex_enter(&dev->l2ad_mtx);
10138 			list_insert_tail(&dev->l2ad_buflist, exists);
10139 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
10140 			    arc_hdr_size(exists), exists);
10141 			mutex_exit(&dev->l2ad_mtx);
10142 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10143 			ARCSTAT_INCR(arcstat_l2_lsize, HDR_GET_LSIZE(exists));
10144 			ARCSTAT_INCR(arcstat_l2_psize, HDR_GET_PSIZE(exists));
10145 		}
10146 		ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
10147 	}
10148 
10149 	mutex_exit(hash_lock);
10150 }
10151 
10152 /*
10153  * Starts an asynchronous read IO to read a log block. This is used in log
10154  * block reconstruction to start reading the next block before we are done
10155  * decoding and reconstructing the current block, to keep the l2arc device
10156  * nice and hot with read IO to process.
10157  * The returned zio will contain a newly allocated memory buffers for the IO
10158  * data which should then be freed by the caller once the zio is no longer
10159  * needed (i.e. due to it having completed). If you wish to abort this
10160  * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
10161  * care of disposing of the allocated buffers correctly.
10162  */
10163 static zio_t *
10164 l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
10165     l2arc_log_blk_phys_t *lb)
10166 {
10167 	uint32_t		asize;
10168 	zio_t			*pio;
10169 	l2arc_read_callback_t	*cb;
10170 
10171 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
10172 	asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10173 	ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
10174 
10175 	cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
10176 	cb->l2rcb_abd = abd_get_from_buf(lb, asize);
10177 	pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
10178 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
10179 	    ZIO_FLAG_DONT_RETRY);
10180 	(void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
10181 	    cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10182 	    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10183 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
10184 
10185 	return (pio);
10186 }
10187 
10188 /*
10189  * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
10190  * buffers allocated for it.
10191  */
10192 static void
10193 l2arc_log_blk_fetch_abort(zio_t *zio)
10194 {
10195 	(void) zio_wait(zio);
10196 }
10197 
10198 /*
10199  * Creates a zio to update the device header on an l2arc device.
10200  */
10201 void
10202 l2arc_dev_hdr_update(l2arc_dev_t *dev)
10203 {
10204 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10205 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10206 	abd_t			*abd;
10207 	int			err;
10208 
10209 	VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
10210 
10211 	l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
10212 	l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
10213 	l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10214 	l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
10215 	l2dhdr->dh_log_entries = dev->l2ad_log_entries;
10216 	l2dhdr->dh_evict = dev->l2ad_evict;
10217 	l2dhdr->dh_start = dev->l2ad_start;
10218 	l2dhdr->dh_end = dev->l2ad_end;
10219 	l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
10220 	l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
10221 	l2dhdr->dh_flags = 0;
10222 	l2dhdr->dh_trim_action_time = dev->l2ad_vdev->vdev_trim_action_time;
10223 	l2dhdr->dh_trim_state = dev->l2ad_vdev->vdev_trim_state;
10224 	if (dev->l2ad_first)
10225 		l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
10226 
10227 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10228 
10229 	err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
10230 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
10231 	    NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
10232 
10233 	abd_put(abd);
10234 
10235 	if (err != 0) {
10236 		zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
10237 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
10238 	}
10239 }
10240 
10241 /*
10242  * Commits a log block to the L2ARC device. This routine is invoked from
10243  * l2arc_write_buffers when the log block fills up.
10244  * This function allocates some memory to temporarily hold the serialized
10245  * buffer to be written. This is then released in l2arc_write_done.
10246  */
10247 static void
10248 l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
10249 {
10250 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
10251 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10252 	uint64_t		psize, asize;
10253 	zio_t			*wzio;
10254 	l2arc_lb_abd_buf_t	*abd_buf;
10255 	uint8_t			*tmpbuf;
10256 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
10257 
10258 	VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
10259 
10260 	tmpbuf = zio_buf_alloc(sizeof (*lb));
10261 	abd_buf = zio_buf_alloc(sizeof (*abd_buf));
10262 	abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
10263 	lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10264 	lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
10265 
10266 	/* link the buffer into the block chain */
10267 	lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
10268 	lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
10269 
10270 	/*
10271 	 * l2arc_log_blk_commit() may be called multiple times during a single
10272 	 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
10273 	 * so we can free them in l2arc_write_done() later on.
10274 	 */
10275 	list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
10276 
10277 	/* try to compress the buffer */
10278 	psize = zio_compress_data(ZIO_COMPRESS_LZ4,
10279 	    abd_buf->abd, tmpbuf, sizeof (*lb), 0);
10280 
10281 	/* a log block is never entirely zero */
10282 	ASSERT(psize != 0);
10283 	asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
10284 	ASSERT(asize <= sizeof (*lb));
10285 
10286 	/*
10287 	 * Update the start log block pointer in the device header to point
10288 	 * to the log block we're about to write.
10289 	 */
10290 	l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
10291 	l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
10292 	l2dhdr->dh_start_lbps[0].lbp_payload_asize =
10293 	    dev->l2ad_log_blk_payload_asize;
10294 	l2dhdr->dh_start_lbps[0].lbp_payload_start =
10295 	    dev->l2ad_log_blk_payload_start;
10296 	_NOTE(CONSTCOND)
10297 	L2BLK_SET_LSIZE(
10298 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
10299 	L2BLK_SET_PSIZE(
10300 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
10301 	L2BLK_SET_CHECKSUM(
10302 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10303 	    ZIO_CHECKSUM_FLETCHER_4);
10304 	if (asize < sizeof (*lb)) {
10305 		/* compression succeeded */
10306 		bzero(tmpbuf + psize, asize - psize);
10307 		L2BLK_SET_COMPRESS(
10308 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10309 		    ZIO_COMPRESS_LZ4);
10310 	} else {
10311 		/* compression failed */
10312 		bcopy(lb, tmpbuf, sizeof (*lb));
10313 		L2BLK_SET_COMPRESS(
10314 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10315 		    ZIO_COMPRESS_OFF);
10316 	}
10317 
10318 	/* checksum what we're about to write */
10319 	fletcher_4_native(tmpbuf, asize, NULL,
10320 	    &l2dhdr->dh_start_lbps[0].lbp_cksum);
10321 
10322 	abd_put(abd_buf->abd);
10323 
10324 	/* perform the write itself */
10325 	abd_buf->abd = abd_get_from_buf(tmpbuf, sizeof (*lb));
10326 	abd_take_ownership_of_buf(abd_buf->abd, B_TRUE);
10327 	wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
10328 	    asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10329 	    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
10330 	DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
10331 	(void) zio_nowait(wzio);
10332 
10333 	dev->l2ad_hand += asize;
10334 	/*
10335 	 * Include the committed log block's pointer  in the list of pointers
10336 	 * to log blocks present in the L2ARC device.
10337 	 */
10338 	bcopy(&l2dhdr->dh_start_lbps[0], lb_ptr_buf->lb_ptr,
10339 	    sizeof (l2arc_log_blkptr_t));
10340 	mutex_enter(&dev->l2ad_mtx);
10341 	list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
10342 	ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10343 	ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10344 	zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10345 	zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
10346 	mutex_exit(&dev->l2ad_mtx);
10347 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10348 
10349 	/* bump the kstats */
10350 	ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
10351 	ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
10352 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
10353 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
10354 	    dev->l2ad_log_blk_payload_asize / asize);
10355 
10356 	/* start a new log block */
10357 	dev->l2ad_log_ent_idx = 0;
10358 	dev->l2ad_log_blk_payload_asize = 0;
10359 	dev->l2ad_log_blk_payload_start = 0;
10360 }
10361 
10362 /*
10363  * Validates an L2ARC log block address to make sure that it can be read
10364  * from the provided L2ARC device.
10365  */
10366 boolean_t
10367 l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
10368 {
10369 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
10370 	uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10371 	uint64_t end = lbp->lbp_daddr + asize - 1;
10372 	uint64_t start = lbp->lbp_payload_start;
10373 	boolean_t evicted = B_FALSE;
10374 
10375 	/*
10376 	 * A log block is valid if all of the following conditions are true:
10377 	 * - it fits entirely (including its payload) between l2ad_start and
10378 	 *   l2ad_end
10379 	 * - it has a valid size
10380 	 * - neither the log block itself nor part of its payload was evicted
10381 	 *   by l2arc_evict():
10382 	 *
10383 	 *		l2ad_hand          l2ad_evict
10384 	 *		|			 |	lbp_daddr
10385 	 *		|     start		 |	|  end
10386 	 *		|     |			 |	|  |
10387 	 *		V     V		         V	V  V
10388 	 *   l2ad_start ============================================ l2ad_end
10389 	 *                    --------------------------||||
10390 	 *				^		 ^
10391 	 *				|		log block
10392 	 *				payload
10393 	 */
10394 
10395 	evicted =
10396 	    l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
10397 	    l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
10398 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
10399 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
10400 
10401 	return (start >= dev->l2ad_start && end <= dev->l2ad_end &&
10402 	    asize > 0 && asize <= sizeof (l2arc_log_blk_phys_t) &&
10403 	    (!evicted || dev->l2ad_first));
10404 }
10405 
10406 /*
10407  * Inserts ARC buffer header `hdr' into the current L2ARC log block on
10408  * the device. The buffer being inserted must be present in L2ARC.
10409  * Returns B_TRUE if the L2ARC log block is full and needs to be committed
10410  * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
10411  */
10412 static boolean_t
10413 l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
10414 {
10415 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
10416 	l2arc_log_ent_phys_t	*le;
10417 
10418 	if (dev->l2ad_log_entries == 0)
10419 		return (B_FALSE);
10420 
10421 	int index = dev->l2ad_log_ent_idx++;
10422 
10423 	ASSERT3S(index, <, dev->l2ad_log_entries);
10424 	ASSERT(HDR_HAS_L2HDR(hdr));
10425 
10426 	le = &lb->lb_entries[index];
10427 	bzero(le, sizeof (*le));
10428 	le->le_dva = hdr->b_dva;
10429 	le->le_birth = hdr->b_birth;
10430 	le->le_daddr = hdr->b_l2hdr.b_daddr;
10431 	if (index == 0)
10432 		dev->l2ad_log_blk_payload_start = le->le_daddr;
10433 	L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
10434 	L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
10435 	L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
10436 	le->le_complevel = hdr->b_complevel;
10437 	L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
10438 	L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
10439 	L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
10440 
10441 	dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
10442 	    HDR_GET_PSIZE(hdr));
10443 
10444 	return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
10445 }
10446 
10447 /*
10448  * Checks whether a given L2ARC device address sits in a time-sequential
10449  * range. The trick here is that the L2ARC is a rotary buffer, so we can't
10450  * just do a range comparison, we need to handle the situation in which the
10451  * range wraps around the end of the L2ARC device. Arguments:
10452  *	bottom -- Lower end of the range to check (written to earlier).
10453  *	top    -- Upper end of the range to check (written to later).
10454  *	check  -- The address for which we want to determine if it sits in
10455  *		  between the top and bottom.
10456  *
10457  * The 3-way conditional below represents the following cases:
10458  *
10459  *	bottom < top : Sequentially ordered case:
10460  *	  <check>--------+-------------------+
10461  *	                 |  (overlap here?)  |
10462  *	 L2ARC dev       V                   V
10463  *	 |---------------<bottom>============<top>--------------|
10464  *
10465  *	bottom > top: Looped-around case:
10466  *	                      <check>--------+------------------+
10467  *	                                     |  (overlap here?) |
10468  *	 L2ARC dev                           V                  V
10469  *	 |===============<top>---------------<bottom>===========|
10470  *	 ^               ^
10471  *	 |  (or here?)   |
10472  *	 +---------------+---------<check>
10473  *
10474  *	top == bottom : Just a single address comparison.
10475  */
10476 boolean_t
10477 l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
10478 {
10479 	if (bottom < top)
10480 		return (bottom <= check && check <= top);
10481 	else if (bottom > top)
10482 		return (check <= top || bottom <= check);
10483 	else
10484 		return (check == top);
10485 }
10486 
10487 EXPORT_SYMBOL(arc_buf_size);
10488 EXPORT_SYMBOL(arc_write);
10489 EXPORT_SYMBOL(arc_read);
10490 EXPORT_SYMBOL(arc_buf_info);
10491 EXPORT_SYMBOL(arc_getbuf_func);
10492 EXPORT_SYMBOL(arc_add_prune_callback);
10493 EXPORT_SYMBOL(arc_remove_prune_callback);
10494 
10495 /* BEGIN CSTYLED */
10496 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min, param_set_arc_long,
10497 	param_get_long, ZMOD_RW, "Min arc size");
10498 
10499 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, max, param_set_arc_long,
10500 	param_get_long, ZMOD_RW, "Max arc size");
10501 
10502 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_limit, param_set_arc_long,
10503 	param_get_long, ZMOD_RW, "Metadata limit for arc size");
10504 
10505 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_limit_percent,
10506 	param_set_arc_long, param_get_long, ZMOD_RW,
10507 	"Percent of arc size for arc meta limit");
10508 
10509 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_min, param_set_arc_long,
10510 	param_get_long, ZMOD_RW, "Min arc metadata");
10511 
10512 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_prune, INT, ZMOD_RW,
10513 	"Meta objects to scan for prune");
10514 
10515 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_adjust_restarts, INT, ZMOD_RW,
10516 	"Limit number of restarts in arc_evict_meta");
10517 
10518 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_strategy, INT, ZMOD_RW,
10519 	"Meta reclaim strategy");
10520 
10521 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, grow_retry, param_set_arc_int,
10522 	param_get_int, ZMOD_RW, "Seconds before growing arc size");
10523 
10524 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, p_dampener_disable, INT, ZMOD_RW,
10525 	"Disable arc_p adapt dampener");
10526 
10527 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, shrink_shift, param_set_arc_int,
10528 	param_get_int, ZMOD_RW, "log2(fraction of arc to reclaim)");
10529 
10530 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, pc_percent, UINT, ZMOD_RW,
10531 	"Percent of pagecache to reclaim arc to");
10532 
10533 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, p_min_shift, param_set_arc_int,
10534 	param_get_int, ZMOD_RW, "arc_c shift to calc min/max arc_p");
10535 
10536 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, average_blocksize, INT, ZMOD_RD,
10537 	"Target average block size");
10538 
10539 ZFS_MODULE_PARAM(zfs, zfs_, compressed_arc_enabled, INT, ZMOD_RW,
10540 	"Disable compressed arc buffers");
10541 
10542 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prefetch_ms, param_set_arc_int,
10543 	param_get_int, ZMOD_RW, "Min life of prefetch block in ms");
10544 
10545 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prescient_prefetch_ms,
10546 	param_set_arc_int, param_get_int, ZMOD_RW,
10547 	"Min life of prescient prefetched block in ms");
10548 
10549 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_max, ULONG, ZMOD_RW,
10550 	"Max write bytes per interval");
10551 
10552 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_boost, ULONG, ZMOD_RW,
10553 	"Extra write bytes during device warmup");
10554 
10555 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom, ULONG, ZMOD_RW,
10556 	"Number of max device writes to precache");
10557 
10558 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom_boost, ULONG, ZMOD_RW,
10559 	"Compressed l2arc_headroom multiplier");
10560 
10561 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, trim_ahead, ULONG, ZMOD_RW,
10562 	"TRIM ahead L2ARC write size multiplier");
10563 
10564 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_secs, ULONG, ZMOD_RW,
10565 	"Seconds between L2ARC writing");
10566 
10567 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_min_ms, ULONG, ZMOD_RW,
10568 	"Min feed interval in milliseconds");
10569 
10570 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, noprefetch, INT, ZMOD_RW,
10571 	"Skip caching prefetched buffers");
10572 
10573 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_again, INT, ZMOD_RW,
10574 	"Turbo L2ARC warmup");
10575 
10576 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, norw, INT, ZMOD_RW,
10577 	"No reads during writes");
10578 
10579 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, meta_percent, INT, ZMOD_RW,
10580 	"Percent of ARC size allowed for L2ARC-only headers");
10581 
10582 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_enabled, INT, ZMOD_RW,
10583 	"Rebuild the L2ARC when importing a pool");
10584 
10585 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_blocks_min_l2size, ULONG, ZMOD_RW,
10586 	"Min size in bytes to write rebuild log blocks in L2ARC");
10587 
10588 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, mfuonly, INT, ZMOD_RW,
10589 	"Cache only MFU data from ARC into L2ARC");
10590 
10591 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, lotsfree_percent, param_set_arc_int,
10592 	param_get_int, ZMOD_RW, "System free memory I/O throttle in bytes");
10593 
10594 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, sys_free, param_set_arc_long,
10595 	param_get_long, ZMOD_RW, "System free memory target size in bytes");
10596 
10597 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit, param_set_arc_long,
10598 	param_get_long, ZMOD_RW, "Minimum bytes of dnodes in arc");
10599 
10600 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit_percent,
10601 	param_set_arc_long, param_get_long, ZMOD_RW,
10602 	"Percent of ARC meta buffers for dnodes");
10603 
10604 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, dnode_reduce_percent, ULONG, ZMOD_RW,
10605 	"Percentage of excess dnodes to try to unpin");
10606 
10607 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, eviction_pct, INT, ZMOD_RW,
10608        "When full, ARC allocation waits for eviction of this % of alloc size");
10609 /* END CSTYLED */
10610