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