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