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