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