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