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