xref: /freebsd/sys/contrib/openzfs/module/zfs/arc.c (revision ba27dd8be821792e15bdabfac69fd6cab0cf9dd3)
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/zio_checksum.h>
298 #include <sys/multilist.h>
299 #include <sys/abd.h>
300 #include <sys/zil.h>
301 #include <sys/fm/fs/zfs.h>
302 #include <sys/callb.h>
303 #include <sys/kstat.h>
304 #include <sys/zthr.h>
305 #include <zfs_fletcher.h>
306 #include <sys/arc_impl.h>
307 #include <sys/trace_zfs.h>
308 #include <sys/aggsum.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 aggsum_t astat_data_size;
697 aggsum_t astat_metadata_size;
698 aggsum_t astat_dbuf_size;
699 aggsum_t astat_dnode_size;
700 aggsum_t astat_bonus_size;
701 aggsum_t astat_hdr_size;
702 aggsum_t astat_l2_hdr_size;
703 aggsum_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 		aggsum_add(&astat_data_size, space);
2650 		break;
2651 	case ARC_SPACE_META:
2652 		aggsum_add(&astat_metadata_size, space);
2653 		break;
2654 	case ARC_SPACE_BONUS:
2655 		aggsum_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 		aggsum_add(&astat_dbuf_size, space);
2662 		break;
2663 	case ARC_SPACE_HDRS:
2664 		aggsum_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 		aggsum_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 		aggsum_add(&astat_data_size, -space);
2696 		break;
2697 	case ARC_SPACE_META:
2698 		aggsum_add(&astat_metadata_size, -space);
2699 		break;
2700 	case ARC_SPACE_BONUS:
2701 		aggsum_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 		aggsum_add(&astat_dbuf_size, -space);
2708 		break;
2709 	case ARC_SPACE_HDRS:
2710 		aggsum_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 		aggsum_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 	unsigned nsize, osize;
3473 
3474 	/*
3475 	 * This function requires that hdr is in the arc_anon state.
3476 	 * Therefore it won't have any L2ARC data for us to worry
3477 	 * about copying.
3478 	 */
3479 	ASSERT(HDR_HAS_L1HDR(hdr));
3480 	ASSERT(!HDR_HAS_L2HDR(hdr));
3481 	ASSERT3U(!!HDR_PROTECTED(hdr), !=, need_crypt);
3482 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3483 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3484 	ASSERT(!list_link_active(&hdr->b_l2hdr.b_l2node));
3485 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3486 
3487 	if (need_crypt) {
3488 		ncache = hdr_full_crypt_cache;
3489 		nsize = sizeof (hdr->b_crypt_hdr);
3490 		ocache = hdr_full_cache;
3491 		osize = HDR_FULL_SIZE;
3492 	} else {
3493 		ncache = hdr_full_cache;
3494 		nsize = HDR_FULL_SIZE;
3495 		ocache = hdr_full_crypt_cache;
3496 		osize = sizeof (hdr->b_crypt_hdr);
3497 	}
3498 
3499 	nhdr = kmem_cache_alloc(ncache, KM_PUSHPAGE);
3500 
3501 	/*
3502 	 * Copy all members that aren't locks or condvars to the new header.
3503 	 * No lists are pointing to us (as we asserted above), so we don't
3504 	 * need to worry about the list nodes.
3505 	 */
3506 	nhdr->b_dva = hdr->b_dva;
3507 	nhdr->b_birth = hdr->b_birth;
3508 	nhdr->b_type = hdr->b_type;
3509 	nhdr->b_flags = hdr->b_flags;
3510 	nhdr->b_psize = hdr->b_psize;
3511 	nhdr->b_lsize = hdr->b_lsize;
3512 	nhdr->b_spa = hdr->b_spa;
3513 	nhdr->b_l1hdr.b_freeze_cksum = hdr->b_l1hdr.b_freeze_cksum;
3514 	nhdr->b_l1hdr.b_bufcnt = hdr->b_l1hdr.b_bufcnt;
3515 	nhdr->b_l1hdr.b_byteswap = hdr->b_l1hdr.b_byteswap;
3516 	nhdr->b_l1hdr.b_state = hdr->b_l1hdr.b_state;
3517 	nhdr->b_l1hdr.b_arc_access = hdr->b_l1hdr.b_arc_access;
3518 	nhdr->b_l1hdr.b_mru_hits = hdr->b_l1hdr.b_mru_hits;
3519 	nhdr->b_l1hdr.b_mru_ghost_hits = hdr->b_l1hdr.b_mru_ghost_hits;
3520 	nhdr->b_l1hdr.b_mfu_hits = hdr->b_l1hdr.b_mfu_hits;
3521 	nhdr->b_l1hdr.b_mfu_ghost_hits = hdr->b_l1hdr.b_mfu_ghost_hits;
3522 	nhdr->b_l1hdr.b_l2_hits = hdr->b_l1hdr.b_l2_hits;
3523 	nhdr->b_l1hdr.b_acb = hdr->b_l1hdr.b_acb;
3524 	nhdr->b_l1hdr.b_pabd = hdr->b_l1hdr.b_pabd;
3525 
3526 	/*
3527 	 * This zfs_refcount_add() exists only to ensure that the individual
3528 	 * arc buffers always point to a header that is referenced, avoiding
3529 	 * a small race condition that could trigger ASSERTs.
3530 	 */
3531 	(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, FTAG);
3532 	nhdr->b_l1hdr.b_buf = hdr->b_l1hdr.b_buf;
3533 	for (buf = nhdr->b_l1hdr.b_buf; buf != NULL; buf = buf->b_next) {
3534 		mutex_enter(&buf->b_evict_lock);
3535 		buf->b_hdr = nhdr;
3536 		mutex_exit(&buf->b_evict_lock);
3537 	}
3538 
3539 	zfs_refcount_transfer(&nhdr->b_l1hdr.b_refcnt, &hdr->b_l1hdr.b_refcnt);
3540 	(void) zfs_refcount_remove(&nhdr->b_l1hdr.b_refcnt, FTAG);
3541 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3542 
3543 	if (need_crypt) {
3544 		arc_hdr_set_flags(nhdr, ARC_FLAG_PROTECTED);
3545 	} else {
3546 		arc_hdr_clear_flags(nhdr, ARC_FLAG_PROTECTED);
3547 	}
3548 
3549 	/* unset all members of the original hdr */
3550 	bzero(&hdr->b_dva, sizeof (dva_t));
3551 	hdr->b_birth = 0;
3552 	hdr->b_type = ARC_BUFC_INVALID;
3553 	hdr->b_flags = 0;
3554 	hdr->b_psize = 0;
3555 	hdr->b_lsize = 0;
3556 	hdr->b_spa = 0;
3557 	hdr->b_l1hdr.b_freeze_cksum = NULL;
3558 	hdr->b_l1hdr.b_buf = NULL;
3559 	hdr->b_l1hdr.b_bufcnt = 0;
3560 	hdr->b_l1hdr.b_byteswap = 0;
3561 	hdr->b_l1hdr.b_state = NULL;
3562 	hdr->b_l1hdr.b_arc_access = 0;
3563 	hdr->b_l1hdr.b_mru_hits = 0;
3564 	hdr->b_l1hdr.b_mru_ghost_hits = 0;
3565 	hdr->b_l1hdr.b_mfu_hits = 0;
3566 	hdr->b_l1hdr.b_mfu_ghost_hits = 0;
3567 	hdr->b_l1hdr.b_l2_hits = 0;
3568 	hdr->b_l1hdr.b_acb = NULL;
3569 	hdr->b_l1hdr.b_pabd = NULL;
3570 
3571 	if (ocache == hdr_full_crypt_cache) {
3572 		ASSERT(!HDR_HAS_RABD(hdr));
3573 		hdr->b_crypt_hdr.b_ot = DMU_OT_NONE;
3574 		hdr->b_crypt_hdr.b_ebufcnt = 0;
3575 		hdr->b_crypt_hdr.b_dsobj = 0;
3576 		bzero(hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
3577 		bzero(hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
3578 		bzero(hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
3579 	}
3580 
3581 	buf_discard_identity(hdr);
3582 	kmem_cache_free(ocache, hdr);
3583 
3584 	return (nhdr);
3585 }
3586 
3587 /*
3588  * This function is used by the send / receive code to convert a newly
3589  * allocated arc_buf_t to one that is suitable for a raw encrypted write. It
3590  * is also used to allow the root objset block to be updated without altering
3591  * its embedded MACs. Both block types will always be uncompressed so we do not
3592  * have to worry about compression type or psize.
3593  */
3594 void
3595 arc_convert_to_raw(arc_buf_t *buf, uint64_t dsobj, boolean_t byteorder,
3596     dmu_object_type_t ot, const uint8_t *salt, const uint8_t *iv,
3597     const uint8_t *mac)
3598 {
3599 	arc_buf_hdr_t *hdr = buf->b_hdr;
3600 
3601 	ASSERT(ot == DMU_OT_DNODE || ot == DMU_OT_OBJSET);
3602 	ASSERT(HDR_HAS_L1HDR(hdr));
3603 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3604 
3605 	buf->b_flags |= (ARC_BUF_FLAG_COMPRESSED | ARC_BUF_FLAG_ENCRYPTED);
3606 	if (!HDR_PROTECTED(hdr))
3607 		hdr = arc_hdr_realloc_crypt(hdr, B_TRUE);
3608 	hdr->b_crypt_hdr.b_dsobj = dsobj;
3609 	hdr->b_crypt_hdr.b_ot = ot;
3610 	hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3611 	    DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3612 	if (!arc_hdr_has_uncompressed_buf(hdr))
3613 		arc_cksum_free(hdr);
3614 
3615 	if (salt != NULL)
3616 		bcopy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
3617 	if (iv != NULL)
3618 		bcopy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
3619 	if (mac != NULL)
3620 		bcopy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
3621 }
3622 
3623 /*
3624  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3625  * The buf is returned thawed since we expect the consumer to modify it.
3626  */
3627 arc_buf_t *
3628 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3629 {
3630 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3631 	    B_FALSE, ZIO_COMPRESS_OFF, 0, type, B_FALSE);
3632 
3633 	arc_buf_t *buf = NULL;
3634 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE, B_FALSE,
3635 	    B_FALSE, B_FALSE, &buf));
3636 	arc_buf_thaw(buf);
3637 
3638 	return (buf);
3639 }
3640 
3641 /*
3642  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3643  * for bufs containing metadata.
3644  */
3645 arc_buf_t *
3646 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3647     enum zio_compress compression_type, uint8_t complevel)
3648 {
3649 	ASSERT3U(lsize, >, 0);
3650 	ASSERT3U(lsize, >=, psize);
3651 	ASSERT3U(compression_type, >, ZIO_COMPRESS_OFF);
3652 	ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3653 
3654 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3655 	    B_FALSE, compression_type, complevel, ARC_BUFC_DATA, B_FALSE);
3656 
3657 	arc_buf_t *buf = NULL;
3658 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_FALSE,
3659 	    B_TRUE, B_FALSE, B_FALSE, &buf));
3660 	arc_buf_thaw(buf);
3661 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3662 
3663 	if (!arc_buf_is_shared(buf)) {
3664 		/*
3665 		 * To ensure that the hdr has the correct data in it if we call
3666 		 * arc_untransform() on this buf before it's been written to
3667 		 * disk, it's easiest if we just set up sharing between the
3668 		 * buf and the hdr.
3669 		 */
3670 		arc_hdr_free_abd(hdr, B_FALSE);
3671 		arc_share_buf(hdr, buf);
3672 	}
3673 
3674 	return (buf);
3675 }
3676 
3677 arc_buf_t *
3678 arc_alloc_raw_buf(spa_t *spa, void *tag, uint64_t dsobj, boolean_t byteorder,
3679     const uint8_t *salt, const uint8_t *iv, const uint8_t *mac,
3680     dmu_object_type_t ot, uint64_t psize, uint64_t lsize,
3681     enum zio_compress compression_type, uint8_t complevel)
3682 {
3683 	arc_buf_hdr_t *hdr;
3684 	arc_buf_t *buf;
3685 	arc_buf_contents_t type = DMU_OT_IS_METADATA(ot) ?
3686 	    ARC_BUFC_METADATA : ARC_BUFC_DATA;
3687 
3688 	ASSERT3U(lsize, >, 0);
3689 	ASSERT3U(lsize, >=, psize);
3690 	ASSERT3U(compression_type, >=, ZIO_COMPRESS_OFF);
3691 	ASSERT3U(compression_type, <, ZIO_COMPRESS_FUNCTIONS);
3692 
3693 	hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize, B_TRUE,
3694 	    compression_type, complevel, type, B_TRUE);
3695 
3696 	hdr->b_crypt_hdr.b_dsobj = dsobj;
3697 	hdr->b_crypt_hdr.b_ot = ot;
3698 	hdr->b_l1hdr.b_byteswap = (byteorder == ZFS_HOST_BYTEORDER) ?
3699 	    DMU_BSWAP_NUMFUNCS : DMU_OT_BYTESWAP(ot);
3700 	bcopy(salt, hdr->b_crypt_hdr.b_salt, ZIO_DATA_SALT_LEN);
3701 	bcopy(iv, hdr->b_crypt_hdr.b_iv, ZIO_DATA_IV_LEN);
3702 	bcopy(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN);
3703 
3704 	/*
3705 	 * This buffer will be considered encrypted even if the ot is not an
3706 	 * encrypted type. It will become authenticated instead in
3707 	 * arc_write_ready().
3708 	 */
3709 	buf = NULL;
3710 	VERIFY0(arc_buf_alloc_impl(hdr, spa, NULL, tag, B_TRUE, B_TRUE,
3711 	    B_FALSE, B_FALSE, &buf));
3712 	arc_buf_thaw(buf);
3713 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3714 
3715 	return (buf);
3716 }
3717 
3718 static void
3719 l2arc_hdr_arcstats_update(arc_buf_hdr_t *hdr, boolean_t incr,
3720     boolean_t state_only)
3721 {
3722 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3723 	l2arc_dev_t *dev = l2hdr->b_dev;
3724 	uint64_t lsize = HDR_GET_LSIZE(hdr);
3725 	uint64_t psize = HDR_GET_PSIZE(hdr);
3726 	uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
3727 	arc_buf_contents_t type = hdr->b_type;
3728 	int64_t lsize_s;
3729 	int64_t psize_s;
3730 	int64_t asize_s;
3731 
3732 	if (incr) {
3733 		lsize_s = lsize;
3734 		psize_s = psize;
3735 		asize_s = asize;
3736 	} else {
3737 		lsize_s = -lsize;
3738 		psize_s = -psize;
3739 		asize_s = -asize;
3740 	}
3741 
3742 	/* If the buffer is a prefetch, count it as such. */
3743 	if (HDR_PREFETCH(hdr)) {
3744 		ARCSTAT_INCR(arcstat_l2_prefetch_asize, asize_s);
3745 	} else {
3746 		/*
3747 		 * We use the value stored in the L2 header upon initial
3748 		 * caching in L2ARC. This value will be updated in case
3749 		 * an MRU/MRU_ghost buffer transitions to MFU but the L2ARC
3750 		 * metadata (log entry) cannot currently be updated. Having
3751 		 * the ARC state in the L2 header solves the problem of a
3752 		 * possibly absent L1 header (apparent in buffers restored
3753 		 * from persistent L2ARC).
3754 		 */
3755 		switch (hdr->b_l2hdr.b_arcs_state) {
3756 			case ARC_STATE_MRU_GHOST:
3757 			case ARC_STATE_MRU:
3758 				ARCSTAT_INCR(arcstat_l2_mru_asize, asize_s);
3759 				break;
3760 			case ARC_STATE_MFU_GHOST:
3761 			case ARC_STATE_MFU:
3762 				ARCSTAT_INCR(arcstat_l2_mfu_asize, asize_s);
3763 				break;
3764 			default:
3765 				break;
3766 		}
3767 	}
3768 
3769 	if (state_only)
3770 		return;
3771 
3772 	ARCSTAT_INCR(arcstat_l2_psize, psize_s);
3773 	ARCSTAT_INCR(arcstat_l2_lsize, lsize_s);
3774 
3775 	switch (type) {
3776 		case ARC_BUFC_DATA:
3777 			ARCSTAT_INCR(arcstat_l2_bufc_data_asize, asize_s);
3778 			break;
3779 		case ARC_BUFC_METADATA:
3780 			ARCSTAT_INCR(arcstat_l2_bufc_metadata_asize, asize_s);
3781 			break;
3782 		default:
3783 			break;
3784 	}
3785 }
3786 
3787 
3788 static void
3789 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3790 {
3791 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3792 	l2arc_dev_t *dev = l2hdr->b_dev;
3793 	uint64_t psize = HDR_GET_PSIZE(hdr);
3794 	uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
3795 
3796 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3797 	ASSERT(HDR_HAS_L2HDR(hdr));
3798 
3799 	list_remove(&dev->l2ad_buflist, hdr);
3800 
3801 	l2arc_hdr_arcstats_decrement(hdr);
3802 	vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
3803 
3804 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3805 	    hdr);
3806 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3807 }
3808 
3809 static void
3810 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3811 {
3812 	if (HDR_HAS_L1HDR(hdr)) {
3813 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3814 		    hdr->b_l1hdr.b_bufcnt > 0);
3815 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3816 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3817 	}
3818 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3819 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
3820 
3821 	if (HDR_HAS_L2HDR(hdr)) {
3822 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3823 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3824 
3825 		if (!buflist_held)
3826 			mutex_enter(&dev->l2ad_mtx);
3827 
3828 		/*
3829 		 * Even though we checked this conditional above, we
3830 		 * need to check this again now that we have the
3831 		 * l2ad_mtx. This is because we could be racing with
3832 		 * another thread calling l2arc_evict() which might have
3833 		 * destroyed this header's L2 portion as we were waiting
3834 		 * to acquire the l2ad_mtx. If that happens, we don't
3835 		 * want to re-destroy the header's L2 portion.
3836 		 */
3837 		if (HDR_HAS_L2HDR(hdr))
3838 			arc_hdr_l2hdr_destroy(hdr);
3839 
3840 		if (!buflist_held)
3841 			mutex_exit(&dev->l2ad_mtx);
3842 	}
3843 
3844 	/*
3845 	 * The header's identify can only be safely discarded once it is no
3846 	 * longer discoverable.  This requires removing it from the hash table
3847 	 * and the l2arc header list.  After this point the hash lock can not
3848 	 * be used to protect the header.
3849 	 */
3850 	if (!HDR_EMPTY(hdr))
3851 		buf_discard_identity(hdr);
3852 
3853 	if (HDR_HAS_L1HDR(hdr)) {
3854 		arc_cksum_free(hdr);
3855 
3856 		while (hdr->b_l1hdr.b_buf != NULL)
3857 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3858 
3859 		if (hdr->b_l1hdr.b_pabd != NULL)
3860 			arc_hdr_free_abd(hdr, B_FALSE);
3861 
3862 		if (HDR_HAS_RABD(hdr))
3863 			arc_hdr_free_abd(hdr, B_TRUE);
3864 	}
3865 
3866 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3867 	if (HDR_HAS_L1HDR(hdr)) {
3868 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3869 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3870 
3871 		if (!HDR_PROTECTED(hdr)) {
3872 			kmem_cache_free(hdr_full_cache, hdr);
3873 		} else {
3874 			kmem_cache_free(hdr_full_crypt_cache, hdr);
3875 		}
3876 	} else {
3877 		kmem_cache_free(hdr_l2only_cache, hdr);
3878 	}
3879 }
3880 
3881 void
3882 arc_buf_destroy(arc_buf_t *buf, void* tag)
3883 {
3884 	arc_buf_hdr_t *hdr = buf->b_hdr;
3885 
3886 	if (hdr->b_l1hdr.b_state == arc_anon) {
3887 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3888 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3889 		VERIFY0(remove_reference(hdr, NULL, tag));
3890 		arc_hdr_destroy(hdr);
3891 		return;
3892 	}
3893 
3894 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3895 	mutex_enter(hash_lock);
3896 
3897 	ASSERT3P(hdr, ==, buf->b_hdr);
3898 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3899 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3900 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3901 	ASSERT3P(buf->b_data, !=, NULL);
3902 
3903 	(void) remove_reference(hdr, hash_lock, tag);
3904 	arc_buf_destroy_impl(buf);
3905 	mutex_exit(hash_lock);
3906 }
3907 
3908 /*
3909  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3910  * state of the header is dependent on its state prior to entering this
3911  * function. The following transitions are possible:
3912  *
3913  *    - arc_mru -> arc_mru_ghost
3914  *    - arc_mfu -> arc_mfu_ghost
3915  *    - arc_mru_ghost -> arc_l2c_only
3916  *    - arc_mru_ghost -> deleted
3917  *    - arc_mfu_ghost -> arc_l2c_only
3918  *    - arc_mfu_ghost -> deleted
3919  */
3920 static int64_t
3921 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3922 {
3923 	arc_state_t *evicted_state, *state;
3924 	int64_t bytes_evicted = 0;
3925 	int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3926 	    arc_min_prescient_prefetch_ms : arc_min_prefetch_ms;
3927 
3928 	ASSERT(MUTEX_HELD(hash_lock));
3929 	ASSERT(HDR_HAS_L1HDR(hdr));
3930 
3931 	state = hdr->b_l1hdr.b_state;
3932 	if (GHOST_STATE(state)) {
3933 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3934 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3935 
3936 		/*
3937 		 * l2arc_write_buffers() relies on a header's L1 portion
3938 		 * (i.e. its b_pabd field) during it's write phase.
3939 		 * Thus, we cannot push a header onto the arc_l2c_only
3940 		 * state (removing its L1 piece) until the header is
3941 		 * done being written to the l2arc.
3942 		 */
3943 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3944 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3945 			return (bytes_evicted);
3946 		}
3947 
3948 		ARCSTAT_BUMP(arcstat_deleted);
3949 		bytes_evicted += HDR_GET_LSIZE(hdr);
3950 
3951 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3952 
3953 		if (HDR_HAS_L2HDR(hdr)) {
3954 			ASSERT(hdr->b_l1hdr.b_pabd == NULL);
3955 			ASSERT(!HDR_HAS_RABD(hdr));
3956 			/*
3957 			 * This buffer is cached on the 2nd Level ARC;
3958 			 * don't destroy the header.
3959 			 */
3960 			arc_change_state(arc_l2c_only, hdr, hash_lock);
3961 			/*
3962 			 * dropping from L1+L2 cached to L2-only,
3963 			 * realloc to remove the L1 header.
3964 			 */
3965 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3966 			    hdr_l2only_cache);
3967 		} else {
3968 			arc_change_state(arc_anon, hdr, hash_lock);
3969 			arc_hdr_destroy(hdr);
3970 		}
3971 		return (bytes_evicted);
3972 	}
3973 
3974 	ASSERT(state == arc_mru || state == arc_mfu);
3975 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3976 
3977 	/* prefetch buffers have a minimum lifespan */
3978 	if (HDR_IO_IN_PROGRESS(hdr) ||
3979 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3980 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3981 	    MSEC_TO_TICK(min_lifetime))) {
3982 		ARCSTAT_BUMP(arcstat_evict_skip);
3983 		return (bytes_evicted);
3984 	}
3985 
3986 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3987 	while (hdr->b_l1hdr.b_buf) {
3988 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3989 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3990 			ARCSTAT_BUMP(arcstat_mutex_miss);
3991 			break;
3992 		}
3993 		if (buf->b_data != NULL)
3994 			bytes_evicted += HDR_GET_LSIZE(hdr);
3995 		mutex_exit(&buf->b_evict_lock);
3996 		arc_buf_destroy_impl(buf);
3997 	}
3998 
3999 	if (HDR_HAS_L2HDR(hdr)) {
4000 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
4001 	} else {
4002 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
4003 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
4004 			    HDR_GET_LSIZE(hdr));
4005 
4006 			switch (state->arcs_state) {
4007 				case ARC_STATE_MRU:
4008 					ARCSTAT_INCR(
4009 					    arcstat_evict_l2_eligible_mru,
4010 					    HDR_GET_LSIZE(hdr));
4011 					break;
4012 				case ARC_STATE_MFU:
4013 					ARCSTAT_INCR(
4014 					    arcstat_evict_l2_eligible_mfu,
4015 					    HDR_GET_LSIZE(hdr));
4016 					break;
4017 				default:
4018 					break;
4019 			}
4020 		} else {
4021 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
4022 			    HDR_GET_LSIZE(hdr));
4023 		}
4024 	}
4025 
4026 	if (hdr->b_l1hdr.b_bufcnt == 0) {
4027 		arc_cksum_free(hdr);
4028 
4029 		bytes_evicted += arc_hdr_size(hdr);
4030 
4031 		/*
4032 		 * If this hdr is being evicted and has a compressed
4033 		 * buffer then we discard it here before we change states.
4034 		 * This ensures that the accounting is updated correctly
4035 		 * in arc_free_data_impl().
4036 		 */
4037 		if (hdr->b_l1hdr.b_pabd != NULL)
4038 			arc_hdr_free_abd(hdr, B_FALSE);
4039 
4040 		if (HDR_HAS_RABD(hdr))
4041 			arc_hdr_free_abd(hdr, B_TRUE);
4042 
4043 		arc_change_state(evicted_state, hdr, hash_lock);
4044 		ASSERT(HDR_IN_HASH_TABLE(hdr));
4045 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
4046 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
4047 	}
4048 
4049 	return (bytes_evicted);
4050 }
4051 
4052 static void
4053 arc_set_need_free(void)
4054 {
4055 	ASSERT(MUTEX_HELD(&arc_evict_lock));
4056 	int64_t remaining = arc_free_memory() - arc_sys_free / 2;
4057 	arc_evict_waiter_t *aw = list_tail(&arc_evict_waiters);
4058 	if (aw == NULL) {
4059 		arc_need_free = MAX(-remaining, 0);
4060 	} else {
4061 		arc_need_free =
4062 		    MAX(-remaining, (int64_t)(aw->aew_count - arc_evict_count));
4063 	}
4064 }
4065 
4066 static uint64_t
4067 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
4068     uint64_t spa, int64_t bytes)
4069 {
4070 	multilist_sublist_t *mls;
4071 	uint64_t bytes_evicted = 0;
4072 	arc_buf_hdr_t *hdr;
4073 	kmutex_t *hash_lock;
4074 	int evict_count = 0;
4075 
4076 	ASSERT3P(marker, !=, NULL);
4077 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
4078 
4079 	mls = multilist_sublist_lock(ml, idx);
4080 
4081 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
4082 	    hdr = multilist_sublist_prev(mls, marker)) {
4083 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
4084 		    (evict_count >= zfs_arc_evict_batch_limit))
4085 			break;
4086 
4087 		/*
4088 		 * To keep our iteration location, move the marker
4089 		 * forward. Since we're not holding hdr's hash lock, we
4090 		 * must be very careful and not remove 'hdr' from the
4091 		 * sublist. Otherwise, other consumers might mistake the
4092 		 * 'hdr' as not being on a sublist when they call the
4093 		 * multilist_link_active() function (they all rely on
4094 		 * the hash lock protecting concurrent insertions and
4095 		 * removals). multilist_sublist_move_forward() was
4096 		 * specifically implemented to ensure this is the case
4097 		 * (only 'marker' will be removed and re-inserted).
4098 		 */
4099 		multilist_sublist_move_forward(mls, marker);
4100 
4101 		/*
4102 		 * The only case where the b_spa field should ever be
4103 		 * zero, is the marker headers inserted by
4104 		 * arc_evict_state(). It's possible for multiple threads
4105 		 * to be calling arc_evict_state() concurrently (e.g.
4106 		 * dsl_pool_close() and zio_inject_fault()), so we must
4107 		 * skip any markers we see from these other threads.
4108 		 */
4109 		if (hdr->b_spa == 0)
4110 			continue;
4111 
4112 		/* we're only interested in evicting buffers of a certain spa */
4113 		if (spa != 0 && hdr->b_spa != spa) {
4114 			ARCSTAT_BUMP(arcstat_evict_skip);
4115 			continue;
4116 		}
4117 
4118 		hash_lock = HDR_LOCK(hdr);
4119 
4120 		/*
4121 		 * We aren't calling this function from any code path
4122 		 * that would already be holding a hash lock, so we're
4123 		 * asserting on this assumption to be defensive in case
4124 		 * this ever changes. Without this check, it would be
4125 		 * possible to incorrectly increment arcstat_mutex_miss
4126 		 * below (e.g. if the code changed such that we called
4127 		 * this function with a hash lock held).
4128 		 */
4129 		ASSERT(!MUTEX_HELD(hash_lock));
4130 
4131 		if (mutex_tryenter(hash_lock)) {
4132 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
4133 			mutex_exit(hash_lock);
4134 
4135 			bytes_evicted += evicted;
4136 
4137 			/*
4138 			 * If evicted is zero, arc_evict_hdr() must have
4139 			 * decided to skip this header, don't increment
4140 			 * evict_count in this case.
4141 			 */
4142 			if (evicted != 0)
4143 				evict_count++;
4144 
4145 		} else {
4146 			ARCSTAT_BUMP(arcstat_mutex_miss);
4147 		}
4148 	}
4149 
4150 	multilist_sublist_unlock(mls);
4151 
4152 	/*
4153 	 * Increment the count of evicted bytes, and wake up any threads that
4154 	 * are waiting for the count to reach this value.  Since the list is
4155 	 * ordered by ascending aew_count, we pop off the beginning of the
4156 	 * list until we reach the end, or a waiter that's past the current
4157 	 * "count".  Doing this outside the loop reduces the number of times
4158 	 * we need to acquire the global arc_evict_lock.
4159 	 *
4160 	 * Only wake when there's sufficient free memory in the system
4161 	 * (specifically, arc_sys_free/2, which by default is a bit more than
4162 	 * 1/64th of RAM).  See the comments in arc_wait_for_eviction().
4163 	 */
4164 	mutex_enter(&arc_evict_lock);
4165 	arc_evict_count += bytes_evicted;
4166 
4167 	if (arc_free_memory() > arc_sys_free / 2) {
4168 		arc_evict_waiter_t *aw;
4169 		while ((aw = list_head(&arc_evict_waiters)) != NULL &&
4170 		    aw->aew_count <= arc_evict_count) {
4171 			list_remove(&arc_evict_waiters, aw);
4172 			cv_broadcast(&aw->aew_cv);
4173 		}
4174 	}
4175 	arc_set_need_free();
4176 	mutex_exit(&arc_evict_lock);
4177 
4178 	/*
4179 	 * If the ARC size is reduced from arc_c_max to arc_c_min (especially
4180 	 * if the average cached block is small), eviction can be on-CPU for
4181 	 * many seconds.  To ensure that other threads that may be bound to
4182 	 * this CPU are able to make progress, make a voluntary preemption
4183 	 * call here.
4184 	 */
4185 	cond_resched();
4186 
4187 	return (bytes_evicted);
4188 }
4189 
4190 /*
4191  * Evict buffers from the given arc state, until we've removed the
4192  * specified number of bytes. Move the removed buffers to the
4193  * appropriate evict state.
4194  *
4195  * This function makes a "best effort". It skips over any buffers
4196  * it can't get a hash_lock on, and so, may not catch all candidates.
4197  * It may also return without evicting as much space as requested.
4198  *
4199  * If bytes is specified using the special value ARC_EVICT_ALL, this
4200  * will evict all available (i.e. unlocked and evictable) buffers from
4201  * the given arc state; which is used by arc_flush().
4202  */
4203 static uint64_t
4204 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
4205     arc_buf_contents_t type)
4206 {
4207 	uint64_t total_evicted = 0;
4208 	multilist_t *ml = state->arcs_list[type];
4209 	int num_sublists;
4210 	arc_buf_hdr_t **markers;
4211 
4212 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
4213 
4214 	num_sublists = multilist_get_num_sublists(ml);
4215 
4216 	/*
4217 	 * If we've tried to evict from each sublist, made some
4218 	 * progress, but still have not hit the target number of bytes
4219 	 * to evict, we want to keep trying. The markers allow us to
4220 	 * pick up where we left off for each individual sublist, rather
4221 	 * than starting from the tail each time.
4222 	 */
4223 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
4224 	for (int i = 0; i < num_sublists; i++) {
4225 		multilist_sublist_t *mls;
4226 
4227 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
4228 
4229 		/*
4230 		 * A b_spa of 0 is used to indicate that this header is
4231 		 * a marker. This fact is used in arc_evict_type() and
4232 		 * arc_evict_state_impl().
4233 		 */
4234 		markers[i]->b_spa = 0;
4235 
4236 		mls = multilist_sublist_lock(ml, i);
4237 		multilist_sublist_insert_tail(mls, markers[i]);
4238 		multilist_sublist_unlock(mls);
4239 	}
4240 
4241 	/*
4242 	 * While we haven't hit our target number of bytes to evict, or
4243 	 * we're evicting all available buffers.
4244 	 */
4245 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
4246 		int sublist_idx = multilist_get_random_index(ml);
4247 		uint64_t scan_evicted = 0;
4248 
4249 		/*
4250 		 * Try to reduce pinned dnodes with a floor of arc_dnode_limit.
4251 		 * Request that 10% of the LRUs be scanned by the superblock
4252 		 * shrinker.
4253 		 */
4254 		if (type == ARC_BUFC_DATA && aggsum_compare(&astat_dnode_size,
4255 		    arc_dnode_size_limit) > 0) {
4256 			arc_prune_async((aggsum_upper_bound(&astat_dnode_size) -
4257 			    arc_dnode_size_limit) / sizeof (dnode_t) /
4258 			    zfs_arc_dnode_reduce_percent);
4259 		}
4260 
4261 		/*
4262 		 * Start eviction using a randomly selected sublist,
4263 		 * this is to try and evenly balance eviction across all
4264 		 * sublists. Always starting at the same sublist
4265 		 * (e.g. index 0) would cause evictions to favor certain
4266 		 * sublists over others.
4267 		 */
4268 		for (int i = 0; i < num_sublists; i++) {
4269 			uint64_t bytes_remaining;
4270 			uint64_t bytes_evicted;
4271 
4272 			if (bytes == ARC_EVICT_ALL)
4273 				bytes_remaining = ARC_EVICT_ALL;
4274 			else if (total_evicted < bytes)
4275 				bytes_remaining = bytes - total_evicted;
4276 			else
4277 				break;
4278 
4279 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
4280 			    markers[sublist_idx], spa, bytes_remaining);
4281 
4282 			scan_evicted += bytes_evicted;
4283 			total_evicted += bytes_evicted;
4284 
4285 			/* we've reached the end, wrap to the beginning */
4286 			if (++sublist_idx >= num_sublists)
4287 				sublist_idx = 0;
4288 		}
4289 
4290 		/*
4291 		 * If we didn't evict anything during this scan, we have
4292 		 * no reason to believe we'll evict more during another
4293 		 * scan, so break the loop.
4294 		 */
4295 		if (scan_evicted == 0) {
4296 			/* This isn't possible, let's make that obvious */
4297 			ASSERT3S(bytes, !=, 0);
4298 
4299 			/*
4300 			 * When bytes is ARC_EVICT_ALL, the only way to
4301 			 * break the loop is when scan_evicted is zero.
4302 			 * In that case, we actually have evicted enough,
4303 			 * so we don't want to increment the kstat.
4304 			 */
4305 			if (bytes != ARC_EVICT_ALL) {
4306 				ASSERT3S(total_evicted, <, bytes);
4307 				ARCSTAT_BUMP(arcstat_evict_not_enough);
4308 			}
4309 
4310 			break;
4311 		}
4312 	}
4313 
4314 	for (int i = 0; i < num_sublists; i++) {
4315 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4316 		multilist_sublist_remove(mls, markers[i]);
4317 		multilist_sublist_unlock(mls);
4318 
4319 		kmem_cache_free(hdr_full_cache, markers[i]);
4320 	}
4321 	kmem_free(markers, sizeof (*markers) * num_sublists);
4322 
4323 	return (total_evicted);
4324 }
4325 
4326 /*
4327  * Flush all "evictable" data of the given type from the arc state
4328  * specified. This will not evict any "active" buffers (i.e. referenced).
4329  *
4330  * When 'retry' is set to B_FALSE, the function will make a single pass
4331  * over the state and evict any buffers that it can. Since it doesn't
4332  * continually retry the eviction, it might end up leaving some buffers
4333  * in the ARC due to lock misses.
4334  *
4335  * When 'retry' is set to B_TRUE, the function will continually retry the
4336  * eviction until *all* evictable buffers have been removed from the
4337  * state. As a result, if concurrent insertions into the state are
4338  * allowed (e.g. if the ARC isn't shutting down), this function might
4339  * wind up in an infinite loop, continually trying to evict buffers.
4340  */
4341 static uint64_t
4342 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4343     boolean_t retry)
4344 {
4345 	uint64_t evicted = 0;
4346 
4347 	while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
4348 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
4349 
4350 		if (!retry)
4351 			break;
4352 	}
4353 
4354 	return (evicted);
4355 }
4356 
4357 /*
4358  * Evict the specified number of bytes from the state specified,
4359  * restricting eviction to the spa and type given. This function
4360  * prevents us from trying to evict more from a state's list than
4361  * is "evictable", and to skip evicting altogether when passed a
4362  * negative value for "bytes". In contrast, arc_evict_state() will
4363  * evict everything it can, when passed a negative value for "bytes".
4364  */
4365 static uint64_t
4366 arc_evict_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
4367     arc_buf_contents_t type)
4368 {
4369 	int64_t delta;
4370 
4371 	if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
4372 		delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
4373 		    bytes);
4374 		return (arc_evict_state(state, spa, delta, type));
4375 	}
4376 
4377 	return (0);
4378 }
4379 
4380 /*
4381  * The goal of this function is to evict enough meta data buffers from the
4382  * ARC in order to enforce the arc_meta_limit.  Achieving this is slightly
4383  * more complicated than it appears because it is common for data buffers
4384  * to have holds on meta data buffers.  In addition, dnode meta data buffers
4385  * will be held by the dnodes in the block preventing them from being freed.
4386  * This means we can't simply traverse the ARC and expect to always find
4387  * enough unheld meta data buffer to release.
4388  *
4389  * Therefore, this function has been updated to make alternating passes
4390  * over the ARC releasing data buffers and then newly unheld meta data
4391  * buffers.  This ensures forward progress is maintained and meta_used
4392  * will decrease.  Normally this is sufficient, but if required the ARC
4393  * will call the registered prune callbacks causing dentry and inodes to
4394  * be dropped from the VFS cache.  This will make dnode meta data buffers
4395  * available for reclaim.
4396  */
4397 static uint64_t
4398 arc_evict_meta_balanced(uint64_t meta_used)
4399 {
4400 	int64_t delta, prune = 0, adjustmnt;
4401 	uint64_t total_evicted = 0;
4402 	arc_buf_contents_t type = ARC_BUFC_DATA;
4403 	int restarts = MAX(zfs_arc_meta_adjust_restarts, 0);
4404 
4405 restart:
4406 	/*
4407 	 * This slightly differs than the way we evict from the mru in
4408 	 * arc_evict because we don't have a "target" value (i.e. no
4409 	 * "meta" arc_p). As a result, I think we can completely
4410 	 * cannibalize the metadata in the MRU before we evict the
4411 	 * metadata from the MFU. I think we probably need to implement a
4412 	 * "metadata arc_p" value to do this properly.
4413 	 */
4414 	adjustmnt = meta_used - arc_meta_limit;
4415 
4416 	if (adjustmnt > 0 &&
4417 	    zfs_refcount_count(&arc_mru->arcs_esize[type]) > 0) {
4418 		delta = MIN(zfs_refcount_count(&arc_mru->arcs_esize[type]),
4419 		    adjustmnt);
4420 		total_evicted += arc_evict_impl(arc_mru, 0, delta, type);
4421 		adjustmnt -= delta;
4422 	}
4423 
4424 	/*
4425 	 * We can't afford to recalculate adjustmnt here. If we do,
4426 	 * new metadata buffers can sneak into the MRU or ANON lists,
4427 	 * thus penalize the MFU metadata. Although the fudge factor is
4428 	 * small, it has been empirically shown to be significant for
4429 	 * certain workloads (e.g. creating many empty directories). As
4430 	 * such, we use the original calculation for adjustmnt, and
4431 	 * simply decrement the amount of data evicted from the MRU.
4432 	 */
4433 
4434 	if (adjustmnt > 0 &&
4435 	    zfs_refcount_count(&arc_mfu->arcs_esize[type]) > 0) {
4436 		delta = MIN(zfs_refcount_count(&arc_mfu->arcs_esize[type]),
4437 		    adjustmnt);
4438 		total_evicted += arc_evict_impl(arc_mfu, 0, delta, type);
4439 	}
4440 
4441 	adjustmnt = meta_used - arc_meta_limit;
4442 
4443 	if (adjustmnt > 0 &&
4444 	    zfs_refcount_count(&arc_mru_ghost->arcs_esize[type]) > 0) {
4445 		delta = MIN(adjustmnt,
4446 		    zfs_refcount_count(&arc_mru_ghost->arcs_esize[type]));
4447 		total_evicted += arc_evict_impl(arc_mru_ghost, 0, delta, type);
4448 		adjustmnt -= delta;
4449 	}
4450 
4451 	if (adjustmnt > 0 &&
4452 	    zfs_refcount_count(&arc_mfu_ghost->arcs_esize[type]) > 0) {
4453 		delta = MIN(adjustmnt,
4454 		    zfs_refcount_count(&arc_mfu_ghost->arcs_esize[type]));
4455 		total_evicted += arc_evict_impl(arc_mfu_ghost, 0, delta, type);
4456 	}
4457 
4458 	/*
4459 	 * If after attempting to make the requested adjustment to the ARC
4460 	 * the meta limit is still being exceeded then request that the
4461 	 * higher layers drop some cached objects which have holds on ARC
4462 	 * meta buffers.  Requests to the upper layers will be made with
4463 	 * increasingly large scan sizes until the ARC is below the limit.
4464 	 */
4465 	if (meta_used > arc_meta_limit) {
4466 		if (type == ARC_BUFC_DATA) {
4467 			type = ARC_BUFC_METADATA;
4468 		} else {
4469 			type = ARC_BUFC_DATA;
4470 
4471 			if (zfs_arc_meta_prune) {
4472 				prune += zfs_arc_meta_prune;
4473 				arc_prune_async(prune);
4474 			}
4475 		}
4476 
4477 		if (restarts > 0) {
4478 			restarts--;
4479 			goto restart;
4480 		}
4481 	}
4482 	return (total_evicted);
4483 }
4484 
4485 /*
4486  * Evict metadata buffers from the cache, such that arc_meta_used is
4487  * capped by the arc_meta_limit tunable.
4488  */
4489 static uint64_t
4490 arc_evict_meta_only(uint64_t meta_used)
4491 {
4492 	uint64_t total_evicted = 0;
4493 	int64_t target;
4494 
4495 	/*
4496 	 * If we're over the meta limit, we want to evict enough
4497 	 * metadata to get back under the meta limit. We don't want to
4498 	 * evict so much that we drop the MRU below arc_p, though. If
4499 	 * we're over the meta limit more than we're over arc_p, we
4500 	 * evict some from the MRU here, and some from the MFU below.
4501 	 */
4502 	target = MIN((int64_t)(meta_used - arc_meta_limit),
4503 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4504 	    zfs_refcount_count(&arc_mru->arcs_size) - arc_p));
4505 
4506 	total_evicted += arc_evict_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4507 
4508 	/*
4509 	 * Similar to the above, we want to evict enough bytes to get us
4510 	 * below the meta limit, but not so much as to drop us below the
4511 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
4512 	 */
4513 	target = MIN((int64_t)(meta_used - arc_meta_limit),
4514 	    (int64_t)(zfs_refcount_count(&arc_mfu->arcs_size) -
4515 	    (arc_c - arc_p)));
4516 
4517 	total_evicted += arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4518 
4519 	return (total_evicted);
4520 }
4521 
4522 static uint64_t
4523 arc_evict_meta(uint64_t meta_used)
4524 {
4525 	if (zfs_arc_meta_strategy == ARC_STRATEGY_META_ONLY)
4526 		return (arc_evict_meta_only(meta_used));
4527 	else
4528 		return (arc_evict_meta_balanced(meta_used));
4529 }
4530 
4531 /*
4532  * Return the type of the oldest buffer in the given arc state
4533  *
4534  * This function will select a random sublist of type ARC_BUFC_DATA and
4535  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
4536  * is compared, and the type which contains the "older" buffer will be
4537  * returned.
4538  */
4539 static arc_buf_contents_t
4540 arc_evict_type(arc_state_t *state)
4541 {
4542 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
4543 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
4544 	int data_idx = multilist_get_random_index(data_ml);
4545 	int meta_idx = multilist_get_random_index(meta_ml);
4546 	multilist_sublist_t *data_mls;
4547 	multilist_sublist_t *meta_mls;
4548 	arc_buf_contents_t type;
4549 	arc_buf_hdr_t *data_hdr;
4550 	arc_buf_hdr_t *meta_hdr;
4551 
4552 	/*
4553 	 * We keep the sublist lock until we're finished, to prevent
4554 	 * the headers from being destroyed via arc_evict_state().
4555 	 */
4556 	data_mls = multilist_sublist_lock(data_ml, data_idx);
4557 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4558 
4559 	/*
4560 	 * These two loops are to ensure we skip any markers that
4561 	 * might be at the tail of the lists due to arc_evict_state().
4562 	 */
4563 
4564 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4565 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4566 		if (data_hdr->b_spa != 0)
4567 			break;
4568 	}
4569 
4570 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4571 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4572 		if (meta_hdr->b_spa != 0)
4573 			break;
4574 	}
4575 
4576 	if (data_hdr == NULL && meta_hdr == NULL) {
4577 		type = ARC_BUFC_DATA;
4578 	} else if (data_hdr == NULL) {
4579 		ASSERT3P(meta_hdr, !=, NULL);
4580 		type = ARC_BUFC_METADATA;
4581 	} else if (meta_hdr == NULL) {
4582 		ASSERT3P(data_hdr, !=, NULL);
4583 		type = ARC_BUFC_DATA;
4584 	} else {
4585 		ASSERT3P(data_hdr, !=, NULL);
4586 		ASSERT3P(meta_hdr, !=, NULL);
4587 
4588 		/* The headers can't be on the sublist without an L1 header */
4589 		ASSERT(HDR_HAS_L1HDR(data_hdr));
4590 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
4591 
4592 		if (data_hdr->b_l1hdr.b_arc_access <
4593 		    meta_hdr->b_l1hdr.b_arc_access) {
4594 			type = ARC_BUFC_DATA;
4595 		} else {
4596 			type = ARC_BUFC_METADATA;
4597 		}
4598 	}
4599 
4600 	multilist_sublist_unlock(meta_mls);
4601 	multilist_sublist_unlock(data_mls);
4602 
4603 	return (type);
4604 }
4605 
4606 /*
4607  * Evict buffers from the cache, such that arc_size is capped by arc_c.
4608  */
4609 static uint64_t
4610 arc_evict(void)
4611 {
4612 	uint64_t total_evicted = 0;
4613 	uint64_t bytes;
4614 	int64_t target;
4615 	uint64_t asize = aggsum_value(&arc_size);
4616 	uint64_t ameta = aggsum_value(&arc_meta_used);
4617 
4618 	/*
4619 	 * If we're over arc_meta_limit, we want to correct that before
4620 	 * potentially evicting data buffers below.
4621 	 */
4622 	total_evicted += arc_evict_meta(ameta);
4623 
4624 	/*
4625 	 * Adjust MRU size
4626 	 *
4627 	 * If we're over the target cache size, we want to evict enough
4628 	 * from the list to get back to our target size. We don't want
4629 	 * to evict too much from the MRU, such that it drops below
4630 	 * arc_p. So, if we're over our target cache size more than
4631 	 * the MRU is over arc_p, we'll evict enough to get back to
4632 	 * arc_p here, and then evict more from the MFU below.
4633 	 */
4634 	target = MIN((int64_t)(asize - arc_c),
4635 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
4636 	    zfs_refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4637 
4638 	/*
4639 	 * If we're below arc_meta_min, always prefer to evict data.
4640 	 * Otherwise, try to satisfy the requested number of bytes to
4641 	 * evict from the type which contains older buffers; in an
4642 	 * effort to keep newer buffers in the cache regardless of their
4643 	 * type. If we cannot satisfy the number of bytes from this
4644 	 * type, spill over into the next type.
4645 	 */
4646 	if (arc_evict_type(arc_mru) == ARC_BUFC_METADATA &&
4647 	    ameta > arc_meta_min) {
4648 		bytes = arc_evict_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4649 		total_evicted += bytes;
4650 
4651 		/*
4652 		 * If we couldn't evict our target number of bytes from
4653 		 * metadata, we try to get the rest from data.
4654 		 */
4655 		target -= bytes;
4656 
4657 		total_evicted +=
4658 		    arc_evict_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4659 	} else {
4660 		bytes = arc_evict_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4661 		total_evicted += bytes;
4662 
4663 		/*
4664 		 * If we couldn't evict our target number of bytes from
4665 		 * data, we try to get the rest from metadata.
4666 		 */
4667 		target -= bytes;
4668 
4669 		total_evicted +=
4670 		    arc_evict_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4671 	}
4672 
4673 	/*
4674 	 * Re-sum ARC stats after the first round of evictions.
4675 	 */
4676 	asize = aggsum_value(&arc_size);
4677 	ameta = aggsum_value(&arc_meta_used);
4678 
4679 
4680 	/*
4681 	 * Adjust MFU size
4682 	 *
4683 	 * Now that we've tried to evict enough from the MRU to get its
4684 	 * size back to arc_p, if we're still above the target cache
4685 	 * size, we evict the rest from the MFU.
4686 	 */
4687 	target = asize - arc_c;
4688 
4689 	if (arc_evict_type(arc_mfu) == ARC_BUFC_METADATA &&
4690 	    ameta > arc_meta_min) {
4691 		bytes = arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4692 		total_evicted += bytes;
4693 
4694 		/*
4695 		 * If we couldn't evict our target number of bytes from
4696 		 * metadata, we try to get the rest from data.
4697 		 */
4698 		target -= bytes;
4699 
4700 		total_evicted +=
4701 		    arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4702 	} else {
4703 		bytes = arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4704 		total_evicted += bytes;
4705 
4706 		/*
4707 		 * If we couldn't evict our target number of bytes from
4708 		 * data, we try to get the rest from data.
4709 		 */
4710 		target -= bytes;
4711 
4712 		total_evicted +=
4713 		    arc_evict_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4714 	}
4715 
4716 	/*
4717 	 * Adjust ghost lists
4718 	 *
4719 	 * In addition to the above, the ARC also defines target values
4720 	 * for the ghost lists. The sum of the mru list and mru ghost
4721 	 * list should never exceed the target size of the cache, and
4722 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
4723 	 * ghost list should never exceed twice the target size of the
4724 	 * cache. The following logic enforces these limits on the ghost
4725 	 * caches, and evicts from them as needed.
4726 	 */
4727 	target = zfs_refcount_count(&arc_mru->arcs_size) +
4728 	    zfs_refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4729 
4730 	bytes = arc_evict_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4731 	total_evicted += bytes;
4732 
4733 	target -= bytes;
4734 
4735 	total_evicted +=
4736 	    arc_evict_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4737 
4738 	/*
4739 	 * We assume the sum of the mru list and mfu list is less than
4740 	 * or equal to arc_c (we enforced this above), which means we
4741 	 * can use the simpler of the two equations below:
4742 	 *
4743 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4744 	 *		    mru ghost + mfu ghost <= arc_c
4745 	 */
4746 	target = zfs_refcount_count(&arc_mru_ghost->arcs_size) +
4747 	    zfs_refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4748 
4749 	bytes = arc_evict_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4750 	total_evicted += bytes;
4751 
4752 	target -= bytes;
4753 
4754 	total_evicted +=
4755 	    arc_evict_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4756 
4757 	return (total_evicted);
4758 }
4759 
4760 void
4761 arc_flush(spa_t *spa, boolean_t retry)
4762 {
4763 	uint64_t guid = 0;
4764 
4765 	/*
4766 	 * If retry is B_TRUE, a spa must not be specified since we have
4767 	 * no good way to determine if all of a spa's buffers have been
4768 	 * evicted from an arc state.
4769 	 */
4770 	ASSERT(!retry || spa == 0);
4771 
4772 	if (spa != NULL)
4773 		guid = spa_load_guid(spa);
4774 
4775 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4776 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4777 
4778 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4779 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4780 
4781 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4782 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4783 
4784 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4785 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4786 }
4787 
4788 void
4789 arc_reduce_target_size(int64_t to_free)
4790 {
4791 	uint64_t asize = aggsum_value(&arc_size);
4792 
4793 	/*
4794 	 * All callers want the ARC to actually evict (at least) this much
4795 	 * memory.  Therefore we reduce from the lower of the current size and
4796 	 * the target size.  This way, even if arc_c is much higher than
4797 	 * arc_size (as can be the case after many calls to arc_freed(), we will
4798 	 * immediately have arc_c < arc_size and therefore the arc_evict_zthr
4799 	 * will evict.
4800 	 */
4801 	uint64_t c = MIN(arc_c, asize);
4802 
4803 	if (c > to_free && c - to_free > arc_c_min) {
4804 		arc_c = c - to_free;
4805 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4806 		if (arc_p > arc_c)
4807 			arc_p = (arc_c >> 1);
4808 		ASSERT(arc_c >= arc_c_min);
4809 		ASSERT((int64_t)arc_p >= 0);
4810 	} else {
4811 		arc_c = arc_c_min;
4812 	}
4813 
4814 	if (asize > arc_c) {
4815 		/* See comment in arc_evict_cb_check() on why lock+flag */
4816 		mutex_enter(&arc_evict_lock);
4817 		arc_evict_needed = B_TRUE;
4818 		mutex_exit(&arc_evict_lock);
4819 		zthr_wakeup(arc_evict_zthr);
4820 	}
4821 }
4822 
4823 /*
4824  * Determine if the system is under memory pressure and is asking
4825  * to reclaim memory. A return value of B_TRUE indicates that the system
4826  * is under memory pressure and that the arc should adjust accordingly.
4827  */
4828 boolean_t
4829 arc_reclaim_needed(void)
4830 {
4831 	return (arc_available_memory() < 0);
4832 }
4833 
4834 void
4835 arc_kmem_reap_soon(void)
4836 {
4837 	size_t			i;
4838 	kmem_cache_t		*prev_cache = NULL;
4839 	kmem_cache_t		*prev_data_cache = NULL;
4840 	extern kmem_cache_t	*zio_buf_cache[];
4841 	extern kmem_cache_t	*zio_data_buf_cache[];
4842 
4843 #ifdef _KERNEL
4844 	if ((aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) &&
4845 	    zfs_arc_meta_prune) {
4846 		/*
4847 		 * We are exceeding our meta-data cache limit.
4848 		 * Prune some entries to release holds on meta-data.
4849 		 */
4850 		arc_prune_async(zfs_arc_meta_prune);
4851 	}
4852 #if defined(_ILP32)
4853 	/*
4854 	 * Reclaim unused memory from all kmem caches.
4855 	 */
4856 	kmem_reap();
4857 #endif
4858 #endif
4859 
4860 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4861 #if defined(_ILP32)
4862 		/* reach upper limit of cache size on 32-bit */
4863 		if (zio_buf_cache[i] == NULL)
4864 			break;
4865 #endif
4866 		if (zio_buf_cache[i] != prev_cache) {
4867 			prev_cache = zio_buf_cache[i];
4868 			kmem_cache_reap_now(zio_buf_cache[i]);
4869 		}
4870 		if (zio_data_buf_cache[i] != prev_data_cache) {
4871 			prev_data_cache = zio_data_buf_cache[i];
4872 			kmem_cache_reap_now(zio_data_buf_cache[i]);
4873 		}
4874 	}
4875 	kmem_cache_reap_now(buf_cache);
4876 	kmem_cache_reap_now(hdr_full_cache);
4877 	kmem_cache_reap_now(hdr_l2only_cache);
4878 	kmem_cache_reap_now(zfs_btree_leaf_cache);
4879 	abd_cache_reap_now();
4880 }
4881 
4882 /* ARGSUSED */
4883 static boolean_t
4884 arc_evict_cb_check(void *arg, zthr_t *zthr)
4885 {
4886 #ifdef ZFS_DEBUG
4887 	/*
4888 	 * This is necessary in order to keep the kstat information
4889 	 * up to date for tools that display kstat data such as the
4890 	 * mdb ::arc dcmd and the Linux crash utility.  These tools
4891 	 * typically do not call kstat's update function, but simply
4892 	 * dump out stats from the most recent update.  Without
4893 	 * this call, these commands may show stale stats for the
4894 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists.  Even
4895 	 * with this call, the data might be out of date if the
4896 	 * evict thread hasn't been woken recently; but that should
4897 	 * suffice.  The arc_state_t structures can be queried
4898 	 * directly if more accurate information is needed.
4899 	 */
4900 	if (arc_ksp != NULL)
4901 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4902 #endif
4903 
4904 	/*
4905 	 * We have to rely on arc_wait_for_eviction() to tell us when to
4906 	 * evict, rather than checking if we are overflowing here, so that we
4907 	 * are sure to not leave arc_wait_for_eviction() waiting on aew_cv.
4908 	 * If we have become "not overflowing" since arc_wait_for_eviction()
4909 	 * checked, we need to wake it up.  We could broadcast the CV here,
4910 	 * but arc_wait_for_eviction() may have not yet gone to sleep.  We
4911 	 * would need to use a mutex to ensure that this function doesn't
4912 	 * broadcast until arc_wait_for_eviction() has gone to sleep (e.g.
4913 	 * the arc_evict_lock).  However, the lock ordering of such a lock
4914 	 * would necessarily be incorrect with respect to the zthr_lock,
4915 	 * which is held before this function is called, and is held by
4916 	 * arc_wait_for_eviction() when it calls zthr_wakeup().
4917 	 */
4918 	return (arc_evict_needed);
4919 }
4920 
4921 /*
4922  * Keep arc_size under arc_c by running arc_evict which evicts data
4923  * from the ARC.
4924  */
4925 /* ARGSUSED */
4926 static void
4927 arc_evict_cb(void *arg, zthr_t *zthr)
4928 {
4929 	uint64_t evicted = 0;
4930 	fstrans_cookie_t cookie = spl_fstrans_mark();
4931 
4932 	/* Evict from cache */
4933 	evicted = arc_evict();
4934 
4935 	/*
4936 	 * If evicted is zero, we couldn't evict anything
4937 	 * via arc_evict(). This could be due to hash lock
4938 	 * collisions, but more likely due to the majority of
4939 	 * arc buffers being unevictable. Therefore, even if
4940 	 * arc_size is above arc_c, another pass is unlikely to
4941 	 * be helpful and could potentially cause us to enter an
4942 	 * infinite loop.  Additionally, zthr_iscancelled() is
4943 	 * checked here so that if the arc is shutting down, the
4944 	 * broadcast will wake any remaining arc evict waiters.
4945 	 */
4946 	mutex_enter(&arc_evict_lock);
4947 	arc_evict_needed = !zthr_iscancelled(arc_evict_zthr) &&
4948 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4949 	if (!arc_evict_needed) {
4950 		/*
4951 		 * We're either no longer overflowing, or we
4952 		 * can't evict anything more, so we should wake
4953 		 * arc_get_data_impl() sooner.
4954 		 */
4955 		arc_evict_waiter_t *aw;
4956 		while ((aw = list_remove_head(&arc_evict_waiters)) != NULL) {
4957 			cv_broadcast(&aw->aew_cv);
4958 		}
4959 		arc_set_need_free();
4960 	}
4961 	mutex_exit(&arc_evict_lock);
4962 	spl_fstrans_unmark(cookie);
4963 }
4964 
4965 /* ARGSUSED */
4966 static boolean_t
4967 arc_reap_cb_check(void *arg, zthr_t *zthr)
4968 {
4969 	int64_t free_memory = arc_available_memory();
4970 	static int reap_cb_check_counter = 0;
4971 
4972 	/*
4973 	 * If a kmem reap is already active, don't schedule more.  We must
4974 	 * check for this because kmem_cache_reap_soon() won't actually
4975 	 * block on the cache being reaped (this is to prevent callers from
4976 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4977 	 * on a system with many, many full magazines, can take minutes).
4978 	 */
4979 	if (!kmem_cache_reap_active() && free_memory < 0) {
4980 
4981 		arc_no_grow = B_TRUE;
4982 		arc_warm = B_TRUE;
4983 		/*
4984 		 * Wait at least zfs_grow_retry (default 5) seconds
4985 		 * before considering growing.
4986 		 */
4987 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4988 		return (B_TRUE);
4989 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4990 		arc_no_grow = B_TRUE;
4991 	} else if (gethrtime() >= arc_growtime) {
4992 		arc_no_grow = B_FALSE;
4993 	}
4994 
4995 	/*
4996 	 * Called unconditionally every 60 seconds to reclaim unused
4997 	 * zstd compression and decompression context. This is done
4998 	 * here to avoid the need for an independent thread.
4999 	 */
5000 	if (!((reap_cb_check_counter++) % 60))
5001 		zfs_zstd_cache_reap_now();
5002 
5003 	return (B_FALSE);
5004 }
5005 
5006 /*
5007  * Keep enough free memory in the system by reaping the ARC's kmem
5008  * caches.  To cause more slabs to be reapable, we may reduce the
5009  * target size of the cache (arc_c), causing the arc_evict_cb()
5010  * to free more buffers.
5011  */
5012 /* ARGSUSED */
5013 static void
5014 arc_reap_cb(void *arg, zthr_t *zthr)
5015 {
5016 	int64_t free_memory;
5017 	fstrans_cookie_t cookie = spl_fstrans_mark();
5018 
5019 	/*
5020 	 * Kick off asynchronous kmem_reap()'s of all our caches.
5021 	 */
5022 	arc_kmem_reap_soon();
5023 
5024 	/*
5025 	 * Wait at least arc_kmem_cache_reap_retry_ms between
5026 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
5027 	 * end up in a situation where we spend lots of time reaping
5028 	 * caches, while we're near arc_c_min.  Waiting here also gives the
5029 	 * subsequent free memory check a chance of finding that the
5030 	 * asynchronous reap has already freed enough memory, and we don't
5031 	 * need to call arc_reduce_target_size().
5032 	 */
5033 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
5034 
5035 	/*
5036 	 * Reduce the target size as needed to maintain the amount of free
5037 	 * memory in the system at a fraction of the arc_size (1/128th by
5038 	 * default).  If oversubscribed (free_memory < 0) then reduce the
5039 	 * target arc_size by the deficit amount plus the fractional
5040 	 * amount.  If free memory is positive but less then the fractional
5041 	 * amount, reduce by what is needed to hit the fractional amount.
5042 	 */
5043 	free_memory = arc_available_memory();
5044 
5045 	int64_t to_free =
5046 	    (arc_c >> arc_shrink_shift) - free_memory;
5047 	if (to_free > 0) {
5048 		arc_reduce_target_size(to_free);
5049 	}
5050 	spl_fstrans_unmark(cookie);
5051 }
5052 
5053 #ifdef _KERNEL
5054 /*
5055  * Determine the amount of memory eligible for eviction contained in the
5056  * ARC. All clean data reported by the ghost lists can always be safely
5057  * evicted. Due to arc_c_min, the same does not hold for all clean data
5058  * contained by the regular mru and mfu lists.
5059  *
5060  * In the case of the regular mru and mfu lists, we need to report as
5061  * much clean data as possible, such that evicting that same reported
5062  * data will not bring arc_size below arc_c_min. Thus, in certain
5063  * circumstances, the total amount of clean data in the mru and mfu
5064  * lists might not actually be evictable.
5065  *
5066  * The following two distinct cases are accounted for:
5067  *
5068  * 1. The sum of the amount of dirty data contained by both the mru and
5069  *    mfu lists, plus the ARC's other accounting (e.g. the anon list),
5070  *    is greater than or equal to arc_c_min.
5071  *    (i.e. amount of dirty data >= arc_c_min)
5072  *
5073  *    This is the easy case; all clean data contained by the mru and mfu
5074  *    lists is evictable. Evicting all clean data can only drop arc_size
5075  *    to the amount of dirty data, which is greater than arc_c_min.
5076  *
5077  * 2. The sum of the amount of dirty data contained by both the mru and
5078  *    mfu lists, plus the ARC's other accounting (e.g. the anon list),
5079  *    is less than arc_c_min.
5080  *    (i.e. arc_c_min > amount of dirty data)
5081  *
5082  *    2.1. arc_size is greater than or equal arc_c_min.
5083  *         (i.e. arc_size >= arc_c_min > amount of dirty data)
5084  *
5085  *         In this case, not all clean data from the regular mru and mfu
5086  *         lists is actually evictable; we must leave enough clean data
5087  *         to keep arc_size above arc_c_min. Thus, the maximum amount of
5088  *         evictable data from the two lists combined, is exactly the
5089  *         difference between arc_size and arc_c_min.
5090  *
5091  *    2.2. arc_size is less than arc_c_min
5092  *         (i.e. arc_c_min > arc_size > amount of dirty data)
5093  *
5094  *         In this case, none of the data contained in the mru and mfu
5095  *         lists is evictable, even if it's clean. Since arc_size is
5096  *         already below arc_c_min, evicting any more would only
5097  *         increase this negative difference.
5098  */
5099 
5100 #endif /* _KERNEL */
5101 
5102 /*
5103  * Adapt arc info given the number of bytes we are trying to add and
5104  * the state that we are coming from.  This function is only called
5105  * when we are adding new content to the cache.
5106  */
5107 static void
5108 arc_adapt(int bytes, arc_state_t *state)
5109 {
5110 	int mult;
5111 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
5112 	int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
5113 	int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
5114 
5115 	ASSERT(bytes > 0);
5116 	/*
5117 	 * Adapt the target size of the MRU list:
5118 	 *	- if we just hit in the MRU ghost list, then increase
5119 	 *	  the target size of the MRU list.
5120 	 *	- if we just hit in the MFU ghost list, then increase
5121 	 *	  the target size of the MFU list by decreasing the
5122 	 *	  target size of the MRU list.
5123 	 */
5124 	if (state == arc_mru_ghost) {
5125 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
5126 		if (!zfs_arc_p_dampener_disable)
5127 			mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
5128 
5129 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
5130 	} else if (state == arc_mfu_ghost) {
5131 		uint64_t delta;
5132 
5133 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
5134 		if (!zfs_arc_p_dampener_disable)
5135 			mult = MIN(mult, 10);
5136 
5137 		delta = MIN(bytes * mult, arc_p);
5138 		arc_p = MAX(arc_p_min, arc_p - delta);
5139 	}
5140 	ASSERT((int64_t)arc_p >= 0);
5141 
5142 	/*
5143 	 * Wake reap thread if we do not have any available memory
5144 	 */
5145 	if (arc_reclaim_needed()) {
5146 		zthr_wakeup(arc_reap_zthr);
5147 		return;
5148 	}
5149 
5150 	if (arc_no_grow)
5151 		return;
5152 
5153 	if (arc_c >= arc_c_max)
5154 		return;
5155 
5156 	/*
5157 	 * If we're within (2 * maxblocksize) bytes of the target
5158 	 * cache size, increment the target cache size
5159 	 */
5160 	ASSERT3U(arc_c, >=, 2ULL << SPA_MAXBLOCKSHIFT);
5161 	if (aggsum_upper_bound(&arc_size) >=
5162 	    arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
5163 		atomic_add_64(&arc_c, (int64_t)bytes);
5164 		if (arc_c > arc_c_max)
5165 			arc_c = arc_c_max;
5166 		else if (state == arc_anon)
5167 			atomic_add_64(&arc_p, (int64_t)bytes);
5168 		if (arc_p > arc_c)
5169 			arc_p = arc_c;
5170 	}
5171 	ASSERT((int64_t)arc_p >= 0);
5172 }
5173 
5174 /*
5175  * Check if arc_size has grown past our upper threshold, determined by
5176  * zfs_arc_overflow_shift.
5177  */
5178 boolean_t
5179 arc_is_overflowing(void)
5180 {
5181 	/* Always allow at least one block of overflow */
5182 	int64_t overflow = MAX(SPA_MAXBLOCKSIZE,
5183 	    arc_c >> zfs_arc_overflow_shift);
5184 
5185 	/*
5186 	 * We just compare the lower bound here for performance reasons. Our
5187 	 * primary goals are to make sure that the arc never grows without
5188 	 * bound, and that it can reach its maximum size. This check
5189 	 * accomplishes both goals. The maximum amount we could run over by is
5190 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
5191 	 * in the ARC. In practice, that's in the tens of MB, which is low
5192 	 * enough to be safe.
5193 	 */
5194 	return (aggsum_lower_bound(&arc_size) >= (int64_t)arc_c + overflow);
5195 }
5196 
5197 static abd_t *
5198 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag,
5199     boolean_t do_adapt)
5200 {
5201 	arc_buf_contents_t type = arc_buf_type(hdr);
5202 
5203 	arc_get_data_impl(hdr, size, tag, do_adapt);
5204 	if (type == ARC_BUFC_METADATA) {
5205 		return (abd_alloc(size, B_TRUE));
5206 	} else {
5207 		ASSERT(type == ARC_BUFC_DATA);
5208 		return (abd_alloc(size, B_FALSE));
5209 	}
5210 }
5211 
5212 static void *
5213 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5214 {
5215 	arc_buf_contents_t type = arc_buf_type(hdr);
5216 
5217 	arc_get_data_impl(hdr, size, tag, B_TRUE);
5218 	if (type == ARC_BUFC_METADATA) {
5219 		return (zio_buf_alloc(size));
5220 	} else {
5221 		ASSERT(type == ARC_BUFC_DATA);
5222 		return (zio_data_buf_alloc(size));
5223 	}
5224 }
5225 
5226 /*
5227  * Wait for the specified amount of data (in bytes) to be evicted from the
5228  * ARC, and for there to be sufficient free memory in the system.  Waiting for
5229  * eviction ensures that the memory used by the ARC decreases.  Waiting for
5230  * free memory ensures that the system won't run out of free pages, regardless
5231  * of ARC behavior and settings.  See arc_lowmem_init().
5232  */
5233 void
5234 arc_wait_for_eviction(uint64_t amount)
5235 {
5236 	mutex_enter(&arc_evict_lock);
5237 	if (arc_is_overflowing()) {
5238 		arc_evict_needed = B_TRUE;
5239 		zthr_wakeup(arc_evict_zthr);
5240 
5241 		if (amount != 0) {
5242 			arc_evict_waiter_t aw;
5243 			list_link_init(&aw.aew_node);
5244 			cv_init(&aw.aew_cv, NULL, CV_DEFAULT, NULL);
5245 
5246 			uint64_t last_count = 0;
5247 			if (!list_is_empty(&arc_evict_waiters)) {
5248 				arc_evict_waiter_t *last =
5249 				    list_tail(&arc_evict_waiters);
5250 				last_count = last->aew_count;
5251 			}
5252 			/*
5253 			 * Note, the last waiter's count may be less than
5254 			 * arc_evict_count if we are low on memory in which
5255 			 * case arc_evict_state_impl() may have deferred
5256 			 * wakeups (but still incremented arc_evict_count).
5257 			 */
5258 			aw.aew_count =
5259 			    MAX(last_count, arc_evict_count) + amount;
5260 
5261 			list_insert_tail(&arc_evict_waiters, &aw);
5262 
5263 			arc_set_need_free();
5264 
5265 			DTRACE_PROBE3(arc__wait__for__eviction,
5266 			    uint64_t, amount,
5267 			    uint64_t, arc_evict_count,
5268 			    uint64_t, aw.aew_count);
5269 
5270 			/*
5271 			 * We will be woken up either when arc_evict_count
5272 			 * reaches aew_count, or when the ARC is no longer
5273 			 * overflowing and eviction completes.
5274 			 */
5275 			cv_wait(&aw.aew_cv, &arc_evict_lock);
5276 
5277 			/*
5278 			 * In case of "false" wakeup, we will still be on the
5279 			 * list.
5280 			 */
5281 			if (list_link_active(&aw.aew_node))
5282 				list_remove(&arc_evict_waiters, &aw);
5283 
5284 			cv_destroy(&aw.aew_cv);
5285 		}
5286 	}
5287 	mutex_exit(&arc_evict_lock);
5288 }
5289 
5290 /*
5291  * Allocate a block and return it to the caller. If we are hitting the
5292  * hard limit for the cache size, we must sleep, waiting for the eviction
5293  * thread to catch up. If we're past the target size but below the hard
5294  * limit, we'll only signal the reclaim thread and continue on.
5295  */
5296 static void
5297 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag,
5298     boolean_t do_adapt)
5299 {
5300 	arc_state_t *state = hdr->b_l1hdr.b_state;
5301 	arc_buf_contents_t type = arc_buf_type(hdr);
5302 
5303 	if (do_adapt)
5304 		arc_adapt(size, state);
5305 
5306 	/*
5307 	 * If arc_size is currently overflowing, we must be adding data
5308 	 * faster than we are evicting.  To ensure we don't compound the
5309 	 * problem by adding more data and forcing arc_size to grow even
5310 	 * further past it's target size, we wait for the eviction thread to
5311 	 * make some progress.  We also wait for there to be sufficient free
5312 	 * memory in the system, as measured by arc_free_memory().
5313 	 *
5314 	 * Specifically, we wait for zfs_arc_eviction_pct percent of the
5315 	 * requested size to be evicted.  This should be more than 100%, to
5316 	 * ensure that that progress is also made towards getting arc_size
5317 	 * under arc_c.  See the comment above zfs_arc_eviction_pct.
5318 	 *
5319 	 * We do the overflowing check without holding the arc_evict_lock to
5320 	 * reduce lock contention in this hot path.  Note that
5321 	 * arc_wait_for_eviction() will acquire the lock and check again to
5322 	 * ensure we are truly overflowing before blocking.
5323 	 */
5324 	if (arc_is_overflowing()) {
5325 		arc_wait_for_eviction(size *
5326 		    zfs_arc_eviction_pct / 100);
5327 	}
5328 
5329 	VERIFY3U(hdr->b_type, ==, type);
5330 	if (type == ARC_BUFC_METADATA) {
5331 		arc_space_consume(size, ARC_SPACE_META);
5332 	} else {
5333 		arc_space_consume(size, ARC_SPACE_DATA);
5334 	}
5335 
5336 	/*
5337 	 * Update the state size.  Note that ghost states have a
5338 	 * "ghost size" and so don't need to be updated.
5339 	 */
5340 	if (!GHOST_STATE(state)) {
5341 
5342 		(void) zfs_refcount_add_many(&state->arcs_size, size, tag);
5343 
5344 		/*
5345 		 * If this is reached via arc_read, the link is
5346 		 * protected by the hash lock. If reached via
5347 		 * arc_buf_alloc, the header should not be accessed by
5348 		 * any other thread. And, if reached via arc_read_done,
5349 		 * the hash lock will protect it if it's found in the
5350 		 * hash table; otherwise no other thread should be
5351 		 * trying to [add|remove]_reference it.
5352 		 */
5353 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5354 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5355 			(void) zfs_refcount_add_many(&state->arcs_esize[type],
5356 			    size, tag);
5357 		}
5358 
5359 		/*
5360 		 * If we are growing the cache, and we are adding anonymous
5361 		 * data, and we have outgrown arc_p, update arc_p
5362 		 */
5363 		if (aggsum_upper_bound(&arc_size) < arc_c &&
5364 		    hdr->b_l1hdr.b_state == arc_anon &&
5365 		    (zfs_refcount_count(&arc_anon->arcs_size) +
5366 		    zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
5367 			arc_p = MIN(arc_c, arc_p + size);
5368 	}
5369 }
5370 
5371 static void
5372 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5373 {
5374 	arc_free_data_impl(hdr, size, tag);
5375 	abd_free(abd);
5376 }
5377 
5378 static void
5379 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5380 {
5381 	arc_buf_contents_t type = arc_buf_type(hdr);
5382 
5383 	arc_free_data_impl(hdr, size, tag);
5384 	if (type == ARC_BUFC_METADATA) {
5385 		zio_buf_free(buf, size);
5386 	} else {
5387 		ASSERT(type == ARC_BUFC_DATA);
5388 		zio_data_buf_free(buf, size);
5389 	}
5390 }
5391 
5392 /*
5393  * Free the arc data buffer.
5394  */
5395 static void
5396 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5397 {
5398 	arc_state_t *state = hdr->b_l1hdr.b_state;
5399 	arc_buf_contents_t type = arc_buf_type(hdr);
5400 
5401 	/* protected by hash lock, if in the hash table */
5402 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5403 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5404 		ASSERT(state != arc_anon && state != arc_l2c_only);
5405 
5406 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
5407 		    size, tag);
5408 	}
5409 	(void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
5410 
5411 	VERIFY3U(hdr->b_type, ==, type);
5412 	if (type == ARC_BUFC_METADATA) {
5413 		arc_space_return(size, ARC_SPACE_META);
5414 	} else {
5415 		ASSERT(type == ARC_BUFC_DATA);
5416 		arc_space_return(size, ARC_SPACE_DATA);
5417 	}
5418 }
5419 
5420 /*
5421  * This routine is called whenever a buffer is accessed.
5422  * NOTE: the hash lock is dropped in this function.
5423  */
5424 static void
5425 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5426 {
5427 	clock_t now;
5428 
5429 	ASSERT(MUTEX_HELD(hash_lock));
5430 	ASSERT(HDR_HAS_L1HDR(hdr));
5431 
5432 	if (hdr->b_l1hdr.b_state == arc_anon) {
5433 		/*
5434 		 * This buffer is not in the cache, and does not
5435 		 * appear in our "ghost" list.  Add the new buffer
5436 		 * to the MRU state.
5437 		 */
5438 
5439 		ASSERT0(hdr->b_l1hdr.b_arc_access);
5440 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5441 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5442 		arc_change_state(arc_mru, hdr, hash_lock);
5443 
5444 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
5445 		now = ddi_get_lbolt();
5446 
5447 		/*
5448 		 * If this buffer is here because of a prefetch, then either:
5449 		 * - clear the flag if this is a "referencing" read
5450 		 *   (any subsequent access will bump this into the MFU state).
5451 		 * or
5452 		 * - move the buffer to the head of the list if this is
5453 		 *   another prefetch (to make it less likely to be evicted).
5454 		 */
5455 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5456 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5457 				/* link protected by hash lock */
5458 				ASSERT(multilist_link_active(
5459 				    &hdr->b_l1hdr.b_arc_node));
5460 			} else {
5461 				if (HDR_HAS_L2HDR(hdr))
5462 					l2arc_hdr_arcstats_decrement_state(hdr);
5463 				arc_hdr_clear_flags(hdr,
5464 				    ARC_FLAG_PREFETCH |
5465 				    ARC_FLAG_PRESCIENT_PREFETCH);
5466 				atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
5467 				ARCSTAT_BUMP(arcstat_mru_hits);
5468 				if (HDR_HAS_L2HDR(hdr))
5469 					l2arc_hdr_arcstats_increment_state(hdr);
5470 			}
5471 			hdr->b_l1hdr.b_arc_access = now;
5472 			return;
5473 		}
5474 
5475 		/*
5476 		 * This buffer has been "accessed" only once so far,
5477 		 * but it is still in the cache. Move it to the MFU
5478 		 * state.
5479 		 */
5480 		if (ddi_time_after(now, hdr->b_l1hdr.b_arc_access +
5481 		    ARC_MINTIME)) {
5482 			/*
5483 			 * More than 125ms have passed since we
5484 			 * instantiated this buffer.  Move it to the
5485 			 * most frequently used state.
5486 			 */
5487 			hdr->b_l1hdr.b_arc_access = now;
5488 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5489 			arc_change_state(arc_mfu, hdr, hash_lock);
5490 		}
5491 		atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
5492 		ARCSTAT_BUMP(arcstat_mru_hits);
5493 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5494 		arc_state_t	*new_state;
5495 		/*
5496 		 * This buffer has been "accessed" recently, but
5497 		 * was evicted from the cache.  Move it to the
5498 		 * MFU state.
5499 		 */
5500 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5501 			new_state = arc_mru;
5502 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5503 				if (HDR_HAS_L2HDR(hdr))
5504 					l2arc_hdr_arcstats_decrement_state(hdr);
5505 				arc_hdr_clear_flags(hdr,
5506 				    ARC_FLAG_PREFETCH |
5507 				    ARC_FLAG_PRESCIENT_PREFETCH);
5508 				if (HDR_HAS_L2HDR(hdr))
5509 					l2arc_hdr_arcstats_increment_state(hdr);
5510 			}
5511 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5512 		} else {
5513 			new_state = arc_mfu;
5514 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5515 		}
5516 
5517 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5518 		arc_change_state(new_state, hdr, hash_lock);
5519 
5520 		atomic_inc_32(&hdr->b_l1hdr.b_mru_ghost_hits);
5521 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5522 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
5523 		/*
5524 		 * This buffer has been accessed more than once and is
5525 		 * still in the cache.  Keep it in the MFU state.
5526 		 *
5527 		 * NOTE: an add_reference() that occurred when we did
5528 		 * the arc_read() will have kicked this off the list.
5529 		 * If it was a prefetch, we will explicitly move it to
5530 		 * the head of the list now.
5531 		 */
5532 
5533 		atomic_inc_32(&hdr->b_l1hdr.b_mfu_hits);
5534 		ARCSTAT_BUMP(arcstat_mfu_hits);
5535 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5536 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5537 		arc_state_t	*new_state = arc_mfu;
5538 		/*
5539 		 * This buffer has been accessed more than once but has
5540 		 * been evicted from the cache.  Move it back to the
5541 		 * MFU state.
5542 		 */
5543 
5544 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5545 			/*
5546 			 * This is a prefetch access...
5547 			 * move this block back to the MRU state.
5548 			 */
5549 			new_state = arc_mru;
5550 		}
5551 
5552 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5553 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5554 		arc_change_state(new_state, hdr, hash_lock);
5555 
5556 		atomic_inc_32(&hdr->b_l1hdr.b_mfu_ghost_hits);
5557 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5558 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5559 		/*
5560 		 * This buffer is on the 2nd Level ARC.
5561 		 */
5562 
5563 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5564 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5565 		arc_change_state(arc_mfu, hdr, hash_lock);
5566 	} else {
5567 		cmn_err(CE_PANIC, "invalid arc state 0x%p",
5568 		    hdr->b_l1hdr.b_state);
5569 	}
5570 }
5571 
5572 /*
5573  * This routine is called by dbuf_hold() to update the arc_access() state
5574  * which otherwise would be skipped for entries in the dbuf cache.
5575  */
5576 void
5577 arc_buf_access(arc_buf_t *buf)
5578 {
5579 	mutex_enter(&buf->b_evict_lock);
5580 	arc_buf_hdr_t *hdr = buf->b_hdr;
5581 
5582 	/*
5583 	 * Avoid taking the hash_lock when possible as an optimization.
5584 	 * The header must be checked again under the hash_lock in order
5585 	 * to handle the case where it is concurrently being released.
5586 	 */
5587 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5588 		mutex_exit(&buf->b_evict_lock);
5589 		return;
5590 	}
5591 
5592 	kmutex_t *hash_lock = HDR_LOCK(hdr);
5593 	mutex_enter(hash_lock);
5594 
5595 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5596 		mutex_exit(hash_lock);
5597 		mutex_exit(&buf->b_evict_lock);
5598 		ARCSTAT_BUMP(arcstat_access_skip);
5599 		return;
5600 	}
5601 
5602 	mutex_exit(&buf->b_evict_lock);
5603 
5604 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5605 	    hdr->b_l1hdr.b_state == arc_mfu);
5606 
5607 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5608 	arc_access(hdr, hash_lock);
5609 	mutex_exit(hash_lock);
5610 
5611 	ARCSTAT_BUMP(arcstat_hits);
5612 	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr) && !HDR_PRESCIENT_PREFETCH(hdr),
5613 	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5614 }
5615 
5616 /* a generic arc_read_done_func_t which you can use */
5617 /* ARGSUSED */
5618 void
5619 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5620     arc_buf_t *buf, void *arg)
5621 {
5622 	if (buf == NULL)
5623 		return;
5624 
5625 	bcopy(buf->b_data, arg, arc_buf_size(buf));
5626 	arc_buf_destroy(buf, arg);
5627 }
5628 
5629 /* a generic arc_read_done_func_t */
5630 /* ARGSUSED */
5631 void
5632 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5633     arc_buf_t *buf, void *arg)
5634 {
5635 	arc_buf_t **bufp = arg;
5636 
5637 	if (buf == NULL) {
5638 		ASSERT(zio == NULL || zio->io_error != 0);
5639 		*bufp = NULL;
5640 	} else {
5641 		ASSERT(zio == NULL || zio->io_error == 0);
5642 		*bufp = buf;
5643 		ASSERT(buf->b_data != NULL);
5644 	}
5645 }
5646 
5647 static void
5648 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5649 {
5650 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5651 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5652 		ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
5653 	} else {
5654 		if (HDR_COMPRESSION_ENABLED(hdr)) {
5655 			ASSERT3U(arc_hdr_get_compress(hdr), ==,
5656 			    BP_GET_COMPRESS(bp));
5657 		}
5658 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5659 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5660 		ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
5661 	}
5662 }
5663 
5664 static void
5665 arc_read_done(zio_t *zio)
5666 {
5667 	blkptr_t 	*bp = zio->io_bp;
5668 	arc_buf_hdr_t	*hdr = zio->io_private;
5669 	kmutex_t	*hash_lock = NULL;
5670 	arc_callback_t	*callback_list;
5671 	arc_callback_t	*acb;
5672 	boolean_t	freeable = B_FALSE;
5673 
5674 	/*
5675 	 * The hdr was inserted into hash-table and removed from lists
5676 	 * prior to starting I/O.  We should find this header, since
5677 	 * it's in the hash table, and it should be legit since it's
5678 	 * not possible to evict it during the I/O.  The only possible
5679 	 * reason for it not to be found is if we were freed during the
5680 	 * read.
5681 	 */
5682 	if (HDR_IN_HASH_TABLE(hdr)) {
5683 		arc_buf_hdr_t *found;
5684 
5685 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5686 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
5687 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
5688 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
5689 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
5690 
5691 		found = buf_hash_find(hdr->b_spa, zio->io_bp, &hash_lock);
5692 
5693 		ASSERT((found == hdr &&
5694 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5695 		    (found == hdr && HDR_L2_READING(hdr)));
5696 		ASSERT3P(hash_lock, !=, NULL);
5697 	}
5698 
5699 	if (BP_IS_PROTECTED(bp)) {
5700 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5701 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5702 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5703 		    hdr->b_crypt_hdr.b_iv);
5704 
5705 		if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5706 			void *tmpbuf;
5707 
5708 			tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5709 			    sizeof (zil_chain_t));
5710 			zio_crypt_decode_mac_zil(tmpbuf,
5711 			    hdr->b_crypt_hdr.b_mac);
5712 			abd_return_buf(zio->io_abd, tmpbuf,
5713 			    sizeof (zil_chain_t));
5714 		} else {
5715 			zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
5716 		}
5717 	}
5718 
5719 	if (zio->io_error == 0) {
5720 		/* byteswap if necessary */
5721 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5722 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
5723 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5724 			} else {
5725 				hdr->b_l1hdr.b_byteswap =
5726 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5727 			}
5728 		} else {
5729 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5730 		}
5731 		if (!HDR_L2_READING(hdr)) {
5732 			hdr->b_complevel = zio->io_prop.zp_complevel;
5733 		}
5734 	}
5735 
5736 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5737 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5738 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5739 
5740 	callback_list = hdr->b_l1hdr.b_acb;
5741 	ASSERT3P(callback_list, !=, NULL);
5742 
5743 	if (hash_lock && zio->io_error == 0 &&
5744 	    hdr->b_l1hdr.b_state == arc_anon) {
5745 		/*
5746 		 * Only call arc_access on anonymous buffers.  This is because
5747 		 * if we've issued an I/O for an evicted buffer, we've already
5748 		 * called arc_access (to prevent any simultaneous readers from
5749 		 * getting confused).
5750 		 */
5751 		arc_access(hdr, hash_lock);
5752 	}
5753 
5754 	/*
5755 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
5756 	 * make a buf containing the data according to the parameters which were
5757 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5758 	 * aren't needlessly decompressing the data multiple times.
5759 	 */
5760 	int callback_cnt = 0;
5761 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5762 		if (!acb->acb_done || acb->acb_nobuf)
5763 			continue;
5764 
5765 		callback_cnt++;
5766 
5767 		if (zio->io_error != 0)
5768 			continue;
5769 
5770 		int error = arc_buf_alloc_impl(hdr, zio->io_spa,
5771 		    &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
5772 		    acb->acb_compressed, acb->acb_noauth, B_TRUE,
5773 		    &acb->acb_buf);
5774 
5775 		/*
5776 		 * Assert non-speculative zios didn't fail because an
5777 		 * encryption key wasn't loaded
5778 		 */
5779 		ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
5780 		    error != EACCES);
5781 
5782 		/*
5783 		 * If we failed to decrypt, report an error now (as the zio
5784 		 * layer would have done if it had done the transforms).
5785 		 */
5786 		if (error == ECKSUM) {
5787 			ASSERT(BP_IS_PROTECTED(bp));
5788 			error = SET_ERROR(EIO);
5789 			if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5790 				spa_log_error(zio->io_spa, &acb->acb_zb);
5791 				(void) zfs_ereport_post(
5792 				    FM_EREPORT_ZFS_AUTHENTICATION,
5793 				    zio->io_spa, NULL, &acb->acb_zb, zio, 0);
5794 			}
5795 		}
5796 
5797 		if (error != 0) {
5798 			/*
5799 			 * Decompression or decryption failed.  Set
5800 			 * io_error so that when we call acb_done
5801 			 * (below), we will indicate that the read
5802 			 * failed. Note that in the unusual case
5803 			 * where one callback is compressed and another
5804 			 * uncompressed, we will mark all of them
5805 			 * as failed, even though the uncompressed
5806 			 * one can't actually fail.  In this case,
5807 			 * the hdr will not be anonymous, because
5808 			 * if there are multiple callbacks, it's
5809 			 * because multiple threads found the same
5810 			 * arc buf in the hash table.
5811 			 */
5812 			zio->io_error = error;
5813 		}
5814 	}
5815 
5816 	/*
5817 	 * If there are multiple callbacks, we must have the hash lock,
5818 	 * because the only way for multiple threads to find this hdr is
5819 	 * in the hash table.  This ensures that if there are multiple
5820 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
5821 	 * we couldn't use arc_buf_destroy() in the error case below.
5822 	 */
5823 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
5824 
5825 	hdr->b_l1hdr.b_acb = NULL;
5826 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5827 	if (callback_cnt == 0)
5828 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
5829 
5830 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5831 	    callback_list != NULL);
5832 
5833 	if (zio->io_error == 0) {
5834 		arc_hdr_verify(hdr, zio->io_bp);
5835 	} else {
5836 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5837 		if (hdr->b_l1hdr.b_state != arc_anon)
5838 			arc_change_state(arc_anon, hdr, hash_lock);
5839 		if (HDR_IN_HASH_TABLE(hdr))
5840 			buf_hash_remove(hdr);
5841 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5842 	}
5843 
5844 	/*
5845 	 * Broadcast before we drop the hash_lock to avoid the possibility
5846 	 * that the hdr (and hence the cv) might be freed before we get to
5847 	 * the cv_broadcast().
5848 	 */
5849 	cv_broadcast(&hdr->b_l1hdr.b_cv);
5850 
5851 	if (hash_lock != NULL) {
5852 		mutex_exit(hash_lock);
5853 	} else {
5854 		/*
5855 		 * This block was freed while we waited for the read to
5856 		 * complete.  It has been removed from the hash table and
5857 		 * moved to the anonymous state (so that it won't show up
5858 		 * in the cache).
5859 		 */
5860 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5861 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5862 	}
5863 
5864 	/* execute each callback and free its structure */
5865 	while ((acb = callback_list) != NULL) {
5866 		if (acb->acb_done != NULL) {
5867 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
5868 				/*
5869 				 * If arc_buf_alloc_impl() fails during
5870 				 * decompression, the buf will still be
5871 				 * allocated, and needs to be freed here.
5872 				 */
5873 				arc_buf_destroy(acb->acb_buf,
5874 				    acb->acb_private);
5875 				acb->acb_buf = NULL;
5876 			}
5877 			acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5878 			    acb->acb_buf, acb->acb_private);
5879 		}
5880 
5881 		if (acb->acb_zio_dummy != NULL) {
5882 			acb->acb_zio_dummy->io_error = zio->io_error;
5883 			zio_nowait(acb->acb_zio_dummy);
5884 		}
5885 
5886 		callback_list = acb->acb_next;
5887 		kmem_free(acb, sizeof (arc_callback_t));
5888 	}
5889 
5890 	if (freeable)
5891 		arc_hdr_destroy(hdr);
5892 }
5893 
5894 /*
5895  * "Read" the block at the specified DVA (in bp) via the
5896  * cache.  If the block is found in the cache, invoke the provided
5897  * callback immediately and return.  Note that the `zio' parameter
5898  * in the callback will be NULL in this case, since no IO was
5899  * required.  If the block is not in the cache pass the read request
5900  * on to the spa with a substitute callback function, so that the
5901  * requested block will be added to the cache.
5902  *
5903  * If a read request arrives for a block that has a read in-progress,
5904  * either wait for the in-progress read to complete (and return the
5905  * results); or, if this is a read with a "done" func, add a record
5906  * to the read to invoke the "done" func when the read completes,
5907  * and return; or just return.
5908  *
5909  * arc_read_done() will invoke all the requested "done" functions
5910  * for readers of this block.
5911  */
5912 int
5913 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp,
5914     arc_read_done_func_t *done, void *private, zio_priority_t priority,
5915     int zio_flags, arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5916 {
5917 	arc_buf_hdr_t *hdr = NULL;
5918 	kmutex_t *hash_lock = NULL;
5919 	zio_t *rzio;
5920 	uint64_t guid = spa_load_guid(spa);
5921 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5922 	boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5923 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5924 	boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5925 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5926 	boolean_t embedded_bp = !!BP_IS_EMBEDDED(bp);
5927 	boolean_t no_buf = *arc_flags & ARC_FLAG_NO_BUF;
5928 	int rc = 0;
5929 
5930 	ASSERT(!embedded_bp ||
5931 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5932 	ASSERT(!BP_IS_HOLE(bp));
5933 	ASSERT(!BP_IS_REDACTED(bp));
5934 
5935 	/*
5936 	 * Normally SPL_FSTRANS will already be set since kernel threads which
5937 	 * expect to call the DMU interfaces will set it when created.  System
5938 	 * calls are similarly handled by setting/cleaning the bit in the
5939 	 * registered callback (module/os/.../zfs/zpl_*).
5940 	 *
5941 	 * External consumers such as Lustre which call the exported DMU
5942 	 * interfaces may not have set SPL_FSTRANS.  To avoid a deadlock
5943 	 * on the hash_lock always set and clear the bit.
5944 	 */
5945 	fstrans_cookie_t cookie = spl_fstrans_mark();
5946 top:
5947 	if (!embedded_bp) {
5948 		/*
5949 		 * Embedded BP's have no DVA and require no I/O to "read".
5950 		 * Create an anonymous arc buf to back it.
5951 		 */
5952 		hdr = buf_hash_find(guid, bp, &hash_lock);
5953 	}
5954 
5955 	/*
5956 	 * Determine if we have an L1 cache hit or a cache miss. For simplicity
5957 	 * we maintain encrypted data separately from compressed / uncompressed
5958 	 * data. If the user is requesting raw encrypted data and we don't have
5959 	 * that in the header we will read from disk to guarantee that we can
5960 	 * get it even if the encryption keys aren't loaded.
5961 	 */
5962 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
5963 	    (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
5964 		arc_buf_t *buf = NULL;
5965 		*arc_flags |= ARC_FLAG_CACHED;
5966 
5967 		if (HDR_IO_IN_PROGRESS(hdr)) {
5968 			zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5969 
5970 			if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
5971 				mutex_exit(hash_lock);
5972 				ARCSTAT_BUMP(arcstat_cached_only_in_progress);
5973 				rc = SET_ERROR(ENOENT);
5974 				goto out;
5975 			}
5976 
5977 			ASSERT3P(head_zio, !=, NULL);
5978 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5979 			    priority == ZIO_PRIORITY_SYNC_READ) {
5980 				/*
5981 				 * This is a sync read that needs to wait for
5982 				 * an in-flight async read. Request that the
5983 				 * zio have its priority upgraded.
5984 				 */
5985 				zio_change_priority(head_zio, priority);
5986 				DTRACE_PROBE1(arc__async__upgrade__sync,
5987 				    arc_buf_hdr_t *, hdr);
5988 				ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5989 			}
5990 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5991 				arc_hdr_clear_flags(hdr,
5992 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5993 			}
5994 
5995 			if (*arc_flags & ARC_FLAG_WAIT) {
5996 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5997 				mutex_exit(hash_lock);
5998 				goto top;
5999 			}
6000 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6001 
6002 			if (done) {
6003 				arc_callback_t *acb = NULL;
6004 
6005 				acb = kmem_zalloc(sizeof (arc_callback_t),
6006 				    KM_SLEEP);
6007 				acb->acb_done = done;
6008 				acb->acb_private = private;
6009 				acb->acb_compressed = compressed_read;
6010 				acb->acb_encrypted = encrypted_read;
6011 				acb->acb_noauth = noauth_read;
6012 				acb->acb_nobuf = no_buf;
6013 				acb->acb_zb = *zb;
6014 				if (pio != NULL)
6015 					acb->acb_zio_dummy = zio_null(pio,
6016 					    spa, NULL, NULL, NULL, zio_flags);
6017 
6018 				ASSERT3P(acb->acb_done, !=, NULL);
6019 				acb->acb_zio_head = head_zio;
6020 				acb->acb_next = hdr->b_l1hdr.b_acb;
6021 				hdr->b_l1hdr.b_acb = acb;
6022 			}
6023 			mutex_exit(hash_lock);
6024 			goto out;
6025 		}
6026 
6027 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
6028 		    hdr->b_l1hdr.b_state == arc_mfu);
6029 
6030 		if (done && !no_buf) {
6031 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
6032 				/*
6033 				 * This is a demand read which does not have to
6034 				 * wait for i/o because we did a predictive
6035 				 * prefetch i/o for it, which has completed.
6036 				 */
6037 				DTRACE_PROBE1(
6038 				    arc__demand__hit__predictive__prefetch,
6039 				    arc_buf_hdr_t *, hdr);
6040 				ARCSTAT_BUMP(
6041 				    arcstat_demand_hit_predictive_prefetch);
6042 				arc_hdr_clear_flags(hdr,
6043 				    ARC_FLAG_PREDICTIVE_PREFETCH);
6044 			}
6045 
6046 			if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
6047 				ARCSTAT_BUMP(
6048 				    arcstat_demand_hit_prescient_prefetch);
6049 				arc_hdr_clear_flags(hdr,
6050 				    ARC_FLAG_PRESCIENT_PREFETCH);
6051 			}
6052 
6053 			ASSERT(!embedded_bp || !BP_IS_HOLE(bp));
6054 
6055 			/* Get a buf with the desired data in it. */
6056 			rc = arc_buf_alloc_impl(hdr, spa, zb, private,
6057 			    encrypted_read, compressed_read, noauth_read,
6058 			    B_TRUE, &buf);
6059 			if (rc == ECKSUM) {
6060 				/*
6061 				 * Convert authentication and decryption errors
6062 				 * to EIO (and generate an ereport if needed)
6063 				 * before leaving the ARC.
6064 				 */
6065 				rc = SET_ERROR(EIO);
6066 				if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
6067 					spa_log_error(spa, zb);
6068 					(void) zfs_ereport_post(
6069 					    FM_EREPORT_ZFS_AUTHENTICATION,
6070 					    spa, NULL, zb, NULL, 0);
6071 				}
6072 			}
6073 			if (rc != 0) {
6074 				(void) remove_reference(hdr, hash_lock,
6075 				    private);
6076 				arc_buf_destroy_impl(buf);
6077 				buf = NULL;
6078 			}
6079 
6080 			/* assert any errors weren't due to unloaded keys */
6081 			ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
6082 			    rc != EACCES);
6083 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
6084 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6085 			if (HDR_HAS_L2HDR(hdr))
6086 				l2arc_hdr_arcstats_decrement_state(hdr);
6087 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6088 			if (HDR_HAS_L2HDR(hdr))
6089 				l2arc_hdr_arcstats_increment_state(hdr);
6090 		}
6091 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
6092 		arc_access(hdr, hash_lock);
6093 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6094 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
6095 		if (*arc_flags & ARC_FLAG_L2CACHE)
6096 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6097 		mutex_exit(hash_lock);
6098 		ARCSTAT_BUMP(arcstat_hits);
6099 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
6100 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
6101 		    data, metadata, hits);
6102 
6103 		if (done)
6104 			done(NULL, zb, bp, buf, private);
6105 	} else {
6106 		uint64_t lsize = BP_GET_LSIZE(bp);
6107 		uint64_t psize = BP_GET_PSIZE(bp);
6108 		arc_callback_t *acb;
6109 		vdev_t *vd = NULL;
6110 		uint64_t addr = 0;
6111 		boolean_t devw = B_FALSE;
6112 		uint64_t size;
6113 		abd_t *hdr_abd;
6114 		int alloc_flags = encrypted_read ? ARC_HDR_ALLOC_RDATA : 0;
6115 
6116 		if (*arc_flags & ARC_FLAG_CACHED_ONLY) {
6117 			rc = SET_ERROR(ENOENT);
6118 			if (hash_lock != NULL)
6119 				mutex_exit(hash_lock);
6120 			goto out;
6121 		}
6122 
6123 		/*
6124 		 * Gracefully handle a damaged logical block size as a
6125 		 * checksum error.
6126 		 */
6127 		if (lsize > spa_maxblocksize(spa)) {
6128 			rc = SET_ERROR(ECKSUM);
6129 			if (hash_lock != NULL)
6130 				mutex_exit(hash_lock);
6131 			goto out;
6132 		}
6133 
6134 		if (hdr == NULL) {
6135 			/*
6136 			 * This block is not in the cache or it has
6137 			 * embedded data.
6138 			 */
6139 			arc_buf_hdr_t *exists = NULL;
6140 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
6141 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
6142 			    BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), 0, type,
6143 			    encrypted_read);
6144 
6145 			if (!embedded_bp) {
6146 				hdr->b_dva = *BP_IDENTITY(bp);
6147 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
6148 				exists = buf_hash_insert(hdr, &hash_lock);
6149 			}
6150 			if (exists != NULL) {
6151 				/* somebody beat us to the hash insert */
6152 				mutex_exit(hash_lock);
6153 				buf_discard_identity(hdr);
6154 				arc_hdr_destroy(hdr);
6155 				goto top; /* restart the IO request */
6156 			}
6157 		} else {
6158 			/*
6159 			 * This block is in the ghost cache or encrypted data
6160 			 * was requested and we didn't have it. If it was
6161 			 * L2-only (and thus didn't have an L1 hdr),
6162 			 * we realloc the header to add an L1 hdr.
6163 			 */
6164 			if (!HDR_HAS_L1HDR(hdr)) {
6165 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
6166 				    hdr_full_cache);
6167 			}
6168 
6169 			if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
6170 				ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6171 				ASSERT(!HDR_HAS_RABD(hdr));
6172 				ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6173 				ASSERT0(zfs_refcount_count(
6174 				    &hdr->b_l1hdr.b_refcnt));
6175 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
6176 				ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
6177 			} else if (HDR_IO_IN_PROGRESS(hdr)) {
6178 				/*
6179 				 * If this header already had an IO in progress
6180 				 * and we are performing another IO to fetch
6181 				 * encrypted data we must wait until the first
6182 				 * IO completes so as not to confuse
6183 				 * arc_read_done(). This should be very rare
6184 				 * and so the performance impact shouldn't
6185 				 * matter.
6186 				 */
6187 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
6188 				mutex_exit(hash_lock);
6189 				goto top;
6190 			}
6191 
6192 			/*
6193 			 * This is a delicate dance that we play here.
6194 			 * This hdr might be in the ghost list so we access
6195 			 * it to move it out of the ghost list before we
6196 			 * initiate the read. If it's a prefetch then
6197 			 * it won't have a callback so we'll remove the
6198 			 * reference that arc_buf_alloc_impl() created. We
6199 			 * do this after we've called arc_access() to
6200 			 * avoid hitting an assert in remove_reference().
6201 			 */
6202 			arc_adapt(arc_hdr_size(hdr), hdr->b_l1hdr.b_state);
6203 			arc_access(hdr, hash_lock);
6204 			arc_hdr_alloc_abd(hdr, alloc_flags);
6205 		}
6206 
6207 		if (encrypted_read) {
6208 			ASSERT(HDR_HAS_RABD(hdr));
6209 			size = HDR_GET_PSIZE(hdr);
6210 			hdr_abd = hdr->b_crypt_hdr.b_rabd;
6211 			zio_flags |= ZIO_FLAG_RAW;
6212 		} else {
6213 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6214 			size = arc_hdr_size(hdr);
6215 			hdr_abd = hdr->b_l1hdr.b_pabd;
6216 
6217 			if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
6218 				zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6219 			}
6220 
6221 			/*
6222 			 * For authenticated bp's, we do not ask the ZIO layer
6223 			 * to authenticate them since this will cause the entire
6224 			 * IO to fail if the key isn't loaded. Instead, we
6225 			 * defer authentication until arc_buf_fill(), which will
6226 			 * verify the data when the key is available.
6227 			 */
6228 			if (BP_IS_AUTHENTICATED(bp))
6229 				zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
6230 		}
6231 
6232 		if (*arc_flags & ARC_FLAG_PREFETCH &&
6233 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6234 			if (HDR_HAS_L2HDR(hdr))
6235 				l2arc_hdr_arcstats_decrement_state(hdr);
6236 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
6237 			if (HDR_HAS_L2HDR(hdr))
6238 				l2arc_hdr_arcstats_increment_state(hdr);
6239 		}
6240 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
6241 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
6242 		if (*arc_flags & ARC_FLAG_L2CACHE)
6243 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6244 		if (BP_IS_AUTHENTICATED(bp))
6245 			arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6246 		if (BP_GET_LEVEL(bp) > 0)
6247 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
6248 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
6249 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
6250 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
6251 
6252 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
6253 		acb->acb_done = done;
6254 		acb->acb_private = private;
6255 		acb->acb_compressed = compressed_read;
6256 		acb->acb_encrypted = encrypted_read;
6257 		acb->acb_noauth = noauth_read;
6258 		acb->acb_zb = *zb;
6259 
6260 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6261 		hdr->b_l1hdr.b_acb = acb;
6262 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6263 
6264 		if (HDR_HAS_L2HDR(hdr) &&
6265 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
6266 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
6267 			addr = hdr->b_l2hdr.b_daddr;
6268 			/*
6269 			 * Lock out L2ARC device removal.
6270 			 */
6271 			if (vdev_is_dead(vd) ||
6272 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
6273 				vd = NULL;
6274 		}
6275 
6276 		/*
6277 		 * We count both async reads and scrub IOs as asynchronous so
6278 		 * that both can be upgraded in the event of a cache hit while
6279 		 * the read IO is still in-flight.
6280 		 */
6281 		if (priority == ZIO_PRIORITY_ASYNC_READ ||
6282 		    priority == ZIO_PRIORITY_SCRUB)
6283 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6284 		else
6285 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
6286 
6287 		/*
6288 		 * At this point, we have a level 1 cache miss or a blkptr
6289 		 * with embedded data.  Try again in L2ARC if possible.
6290 		 */
6291 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
6292 
6293 		/*
6294 		 * Skip ARC stat bump for block pointers with embedded
6295 		 * data. The data are read from the blkptr itself via
6296 		 * decode_embedded_bp_compressed().
6297 		 */
6298 		if (!embedded_bp) {
6299 			DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr,
6300 			    blkptr_t *, bp, uint64_t, lsize,
6301 			    zbookmark_phys_t *, zb);
6302 			ARCSTAT_BUMP(arcstat_misses);
6303 			ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
6304 			    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data,
6305 			    metadata, misses);
6306 			zfs_racct_read(size, 1);
6307 		}
6308 
6309 		/* Check if the spa even has l2 configured */
6310 		const boolean_t spa_has_l2 = l2arc_ndev != 0 &&
6311 		    spa->spa_l2cache.sav_count > 0;
6312 
6313 		if (vd != NULL && spa_has_l2 && !(l2arc_norw && devw)) {
6314 			/*
6315 			 * Read from the L2ARC if the following are true:
6316 			 * 1. The L2ARC vdev was previously cached.
6317 			 * 2. This buffer still has L2ARC metadata.
6318 			 * 3. This buffer isn't currently writing to the L2ARC.
6319 			 * 4. The L2ARC entry wasn't evicted, which may
6320 			 *    also have invalidated the vdev.
6321 			 * 5. This isn't prefetch or l2arc_noprefetch is 0.
6322 			 */
6323 			if (HDR_HAS_L2HDR(hdr) &&
6324 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
6325 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
6326 				l2arc_read_callback_t *cb;
6327 				abd_t *abd;
6328 				uint64_t asize;
6329 
6330 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6331 				ARCSTAT_BUMP(arcstat_l2_hits);
6332 				atomic_inc_32(&hdr->b_l2hdr.b_hits);
6333 
6334 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6335 				    KM_SLEEP);
6336 				cb->l2rcb_hdr = hdr;
6337 				cb->l2rcb_bp = *bp;
6338 				cb->l2rcb_zb = *zb;
6339 				cb->l2rcb_flags = zio_flags;
6340 
6341 				/*
6342 				 * When Compressed ARC is disabled, but the
6343 				 * L2ARC block is compressed, arc_hdr_size()
6344 				 * will have returned LSIZE rather than PSIZE.
6345 				 */
6346 				if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
6347 				    !HDR_COMPRESSION_ENABLED(hdr) &&
6348 				    HDR_GET_PSIZE(hdr) != 0) {
6349 					size = HDR_GET_PSIZE(hdr);
6350 				}
6351 
6352 				asize = vdev_psize_to_asize(vd, size);
6353 				if (asize != size) {
6354 					abd = abd_alloc_for_io(asize,
6355 					    HDR_ISTYPE_METADATA(hdr));
6356 					cb->l2rcb_abd = abd;
6357 				} else {
6358 					abd = hdr_abd;
6359 				}
6360 
6361 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6362 				    addr + asize <= vd->vdev_psize -
6363 				    VDEV_LABEL_END_SIZE);
6364 
6365 				/*
6366 				 * l2arc read.  The SCL_L2ARC lock will be
6367 				 * released by l2arc_read_done().
6368 				 * Issue a null zio if the underlying buffer
6369 				 * was squashed to zero size by compression.
6370 				 */
6371 				ASSERT3U(arc_hdr_get_compress(hdr), !=,
6372 				    ZIO_COMPRESS_EMPTY);
6373 				rzio = zio_read_phys(pio, vd, addr,
6374 				    asize, abd,
6375 				    ZIO_CHECKSUM_OFF,
6376 				    l2arc_read_done, cb, priority,
6377 				    zio_flags | ZIO_FLAG_DONT_CACHE |
6378 				    ZIO_FLAG_CANFAIL |
6379 				    ZIO_FLAG_DONT_PROPAGATE |
6380 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
6381 				acb->acb_zio_head = rzio;
6382 
6383 				if (hash_lock != NULL)
6384 					mutex_exit(hash_lock);
6385 
6386 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6387 				    zio_t *, rzio);
6388 				ARCSTAT_INCR(arcstat_l2_read_bytes,
6389 				    HDR_GET_PSIZE(hdr));
6390 
6391 				if (*arc_flags & ARC_FLAG_NOWAIT) {
6392 					zio_nowait(rzio);
6393 					goto out;
6394 				}
6395 
6396 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
6397 				if (zio_wait(rzio) == 0)
6398 					goto out;
6399 
6400 				/* l2arc read error; goto zio_read() */
6401 				if (hash_lock != NULL)
6402 					mutex_enter(hash_lock);
6403 			} else {
6404 				DTRACE_PROBE1(l2arc__miss,
6405 				    arc_buf_hdr_t *, hdr);
6406 				ARCSTAT_BUMP(arcstat_l2_misses);
6407 				if (HDR_L2_WRITING(hdr))
6408 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
6409 				spa_config_exit(spa, SCL_L2ARC, vd);
6410 			}
6411 		} else {
6412 			if (vd != NULL)
6413 				spa_config_exit(spa, SCL_L2ARC, vd);
6414 
6415 			/*
6416 			 * Only a spa with l2 should contribute to l2
6417 			 * miss stats.  (Including the case of having a
6418 			 * faulted cache device - that's also a miss.)
6419 			 */
6420 			if (spa_has_l2) {
6421 				/*
6422 				 * Skip ARC stat bump for block pointers with
6423 				 * embedded data. The data are read from the
6424 				 * blkptr itself via
6425 				 * decode_embedded_bp_compressed().
6426 				 */
6427 				if (!embedded_bp) {
6428 					DTRACE_PROBE1(l2arc__miss,
6429 					    arc_buf_hdr_t *, hdr);
6430 					ARCSTAT_BUMP(arcstat_l2_misses);
6431 				}
6432 			}
6433 		}
6434 
6435 		rzio = zio_read(pio, spa, bp, hdr_abd, size,
6436 		    arc_read_done, hdr, priority, zio_flags, zb);
6437 		acb->acb_zio_head = rzio;
6438 
6439 		if (hash_lock != NULL)
6440 			mutex_exit(hash_lock);
6441 
6442 		if (*arc_flags & ARC_FLAG_WAIT) {
6443 			rc = zio_wait(rzio);
6444 			goto out;
6445 		}
6446 
6447 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6448 		zio_nowait(rzio);
6449 	}
6450 
6451 out:
6452 	/* embedded bps don't actually go to disk */
6453 	if (!embedded_bp)
6454 		spa_read_history_add(spa, zb, *arc_flags);
6455 	spl_fstrans_unmark(cookie);
6456 	return (rc);
6457 }
6458 
6459 arc_prune_t *
6460 arc_add_prune_callback(arc_prune_func_t *func, void *private)
6461 {
6462 	arc_prune_t *p;
6463 
6464 	p = kmem_alloc(sizeof (*p), KM_SLEEP);
6465 	p->p_pfunc = func;
6466 	p->p_private = private;
6467 	list_link_init(&p->p_node);
6468 	zfs_refcount_create(&p->p_refcnt);
6469 
6470 	mutex_enter(&arc_prune_mtx);
6471 	zfs_refcount_add(&p->p_refcnt, &arc_prune_list);
6472 	list_insert_head(&arc_prune_list, p);
6473 	mutex_exit(&arc_prune_mtx);
6474 
6475 	return (p);
6476 }
6477 
6478 void
6479 arc_remove_prune_callback(arc_prune_t *p)
6480 {
6481 	boolean_t wait = B_FALSE;
6482 	mutex_enter(&arc_prune_mtx);
6483 	list_remove(&arc_prune_list, p);
6484 	if (zfs_refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
6485 		wait = B_TRUE;
6486 	mutex_exit(&arc_prune_mtx);
6487 
6488 	/* wait for arc_prune_task to finish */
6489 	if (wait)
6490 		taskq_wait_outstanding(arc_prune_taskq, 0);
6491 	ASSERT0(zfs_refcount_count(&p->p_refcnt));
6492 	zfs_refcount_destroy(&p->p_refcnt);
6493 	kmem_free(p, sizeof (*p));
6494 }
6495 
6496 /*
6497  * Notify the arc that a block was freed, and thus will never be used again.
6498  */
6499 void
6500 arc_freed(spa_t *spa, const blkptr_t *bp)
6501 {
6502 	arc_buf_hdr_t *hdr;
6503 	kmutex_t *hash_lock;
6504 	uint64_t guid = spa_load_guid(spa);
6505 
6506 	ASSERT(!BP_IS_EMBEDDED(bp));
6507 
6508 	hdr = buf_hash_find(guid, bp, &hash_lock);
6509 	if (hdr == NULL)
6510 		return;
6511 
6512 	/*
6513 	 * We might be trying to free a block that is still doing I/O
6514 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6515 	 * dmu_sync-ed block). If this block is being prefetched, then it
6516 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6517 	 * until the I/O completes. A block may also have a reference if it is
6518 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6519 	 * have written the new block to its final resting place on disk but
6520 	 * without the dedup flag set. This would have left the hdr in the MRU
6521 	 * state and discoverable. When the txg finally syncs it detects that
6522 	 * the block was overridden in open context and issues an override I/O.
6523 	 * Since this is a dedup block, the override I/O will determine if the
6524 	 * block is already in the DDT. If so, then it will replace the io_bp
6525 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
6526 	 * reaches the done callback, dbuf_write_override_done, it will
6527 	 * check to see if the io_bp and io_bp_override are identical.
6528 	 * If they are not, then it indicates that the bp was replaced with
6529 	 * the bp in the DDT and the override bp is freed. This allows
6530 	 * us to arrive here with a reference on a block that is being
6531 	 * freed. So if we have an I/O in progress, or a reference to
6532 	 * this hdr, then we don't destroy the hdr.
6533 	 */
6534 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6535 	    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6536 		arc_change_state(arc_anon, hdr, hash_lock);
6537 		arc_hdr_destroy(hdr);
6538 		mutex_exit(hash_lock);
6539 	} else {
6540 		mutex_exit(hash_lock);
6541 	}
6542 
6543 }
6544 
6545 /*
6546  * Release this buffer from the cache, making it an anonymous buffer.  This
6547  * must be done after a read and prior to modifying the buffer contents.
6548  * If the buffer has more than one reference, we must make
6549  * a new hdr for the buffer.
6550  */
6551 void
6552 arc_release(arc_buf_t *buf, void *tag)
6553 {
6554 	arc_buf_hdr_t *hdr = buf->b_hdr;
6555 
6556 	/*
6557 	 * It would be nice to assert that if its DMU metadata (level >
6558 	 * 0 || it's the dnode file), then it must be syncing context.
6559 	 * But we don't know that information at this level.
6560 	 */
6561 
6562 	mutex_enter(&buf->b_evict_lock);
6563 
6564 	ASSERT(HDR_HAS_L1HDR(hdr));
6565 
6566 	/*
6567 	 * We don't grab the hash lock prior to this check, because if
6568 	 * the buffer's header is in the arc_anon state, it won't be
6569 	 * linked into the hash table.
6570 	 */
6571 	if (hdr->b_l1hdr.b_state == arc_anon) {
6572 		mutex_exit(&buf->b_evict_lock);
6573 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6574 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
6575 		ASSERT(!HDR_HAS_L2HDR(hdr));
6576 		ASSERT(HDR_EMPTY(hdr));
6577 
6578 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6579 		ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6580 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6581 
6582 		hdr->b_l1hdr.b_arc_access = 0;
6583 
6584 		/*
6585 		 * If the buf is being overridden then it may already
6586 		 * have a hdr that is not empty.
6587 		 */
6588 		buf_discard_identity(hdr);
6589 		arc_buf_thaw(buf);
6590 
6591 		return;
6592 	}
6593 
6594 	kmutex_t *hash_lock = HDR_LOCK(hdr);
6595 	mutex_enter(hash_lock);
6596 
6597 	/*
6598 	 * This assignment is only valid as long as the hash_lock is
6599 	 * held, we must be careful not to reference state or the
6600 	 * b_state field after dropping the lock.
6601 	 */
6602 	arc_state_t *state = hdr->b_l1hdr.b_state;
6603 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6604 	ASSERT3P(state, !=, arc_anon);
6605 
6606 	/* this buffer is not on any list */
6607 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6608 
6609 	if (HDR_HAS_L2HDR(hdr)) {
6610 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6611 
6612 		/*
6613 		 * We have to recheck this conditional again now that
6614 		 * we're holding the l2ad_mtx to prevent a race with
6615 		 * another thread which might be concurrently calling
6616 		 * l2arc_evict(). In that case, l2arc_evict() might have
6617 		 * destroyed the header's L2 portion as we were waiting
6618 		 * to acquire the l2ad_mtx.
6619 		 */
6620 		if (HDR_HAS_L2HDR(hdr))
6621 			arc_hdr_l2hdr_destroy(hdr);
6622 
6623 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6624 	}
6625 
6626 	/*
6627 	 * Do we have more than one buf?
6628 	 */
6629 	if (hdr->b_l1hdr.b_bufcnt > 1) {
6630 		arc_buf_hdr_t *nhdr;
6631 		uint64_t spa = hdr->b_spa;
6632 		uint64_t psize = HDR_GET_PSIZE(hdr);
6633 		uint64_t lsize = HDR_GET_LSIZE(hdr);
6634 		boolean_t protected = HDR_PROTECTED(hdr);
6635 		enum zio_compress compress = arc_hdr_get_compress(hdr);
6636 		arc_buf_contents_t type = arc_buf_type(hdr);
6637 		VERIFY3U(hdr->b_type, ==, type);
6638 
6639 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6640 		(void) remove_reference(hdr, hash_lock, tag);
6641 
6642 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6643 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6644 			ASSERT(ARC_BUF_LAST(buf));
6645 		}
6646 
6647 		/*
6648 		 * Pull the data off of this hdr and attach it to
6649 		 * a new anonymous hdr. Also find the last buffer
6650 		 * in the hdr's buffer list.
6651 		 */
6652 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6653 		ASSERT3P(lastbuf, !=, NULL);
6654 
6655 		/*
6656 		 * If the current arc_buf_t and the hdr are sharing their data
6657 		 * buffer, then we must stop sharing that block.
6658 		 */
6659 		if (arc_buf_is_shared(buf)) {
6660 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6661 			VERIFY(!arc_buf_is_shared(lastbuf));
6662 
6663 			/*
6664 			 * First, sever the block sharing relationship between
6665 			 * buf and the arc_buf_hdr_t.
6666 			 */
6667 			arc_unshare_buf(hdr, buf);
6668 
6669 			/*
6670 			 * Now we need to recreate the hdr's b_pabd. Since we
6671 			 * have lastbuf handy, we try to share with it, but if
6672 			 * we can't then we allocate a new b_pabd and copy the
6673 			 * data from buf into it.
6674 			 */
6675 			if (arc_can_share(hdr, lastbuf)) {
6676 				arc_share_buf(hdr, lastbuf);
6677 			} else {
6678 				arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6679 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6680 				    buf->b_data, psize);
6681 			}
6682 			VERIFY3P(lastbuf->b_data, !=, NULL);
6683 		} else if (HDR_SHARED_DATA(hdr)) {
6684 			/*
6685 			 * Uncompressed shared buffers are always at the end
6686 			 * of the list. Compressed buffers don't have the
6687 			 * same requirements. This makes it hard to
6688 			 * simply assert that the lastbuf is shared so
6689 			 * we rely on the hdr's compression flags to determine
6690 			 * if we have a compressed, shared buffer.
6691 			 */
6692 			ASSERT(arc_buf_is_shared(lastbuf) ||
6693 			    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
6694 			ASSERT(!ARC_BUF_SHARED(buf));
6695 		}
6696 
6697 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
6698 		ASSERT3P(state, !=, arc_l2c_only);
6699 
6700 		(void) zfs_refcount_remove_many(&state->arcs_size,
6701 		    arc_buf_size(buf), buf);
6702 
6703 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6704 			ASSERT3P(state, !=, arc_l2c_only);
6705 			(void) zfs_refcount_remove_many(
6706 			    &state->arcs_esize[type],
6707 			    arc_buf_size(buf), buf);
6708 		}
6709 
6710 		hdr->b_l1hdr.b_bufcnt -= 1;
6711 		if (ARC_BUF_ENCRYPTED(buf))
6712 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
6713 
6714 		arc_cksum_verify(buf);
6715 		arc_buf_unwatch(buf);
6716 
6717 		/* if this is the last uncompressed buf free the checksum */
6718 		if (!arc_hdr_has_uncompressed_buf(hdr))
6719 			arc_cksum_free(hdr);
6720 
6721 		mutex_exit(hash_lock);
6722 
6723 		/*
6724 		 * Allocate a new hdr. The new hdr will contain a b_pabd
6725 		 * buffer which will be freed in arc_write().
6726 		 */
6727 		nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6728 		    compress, hdr->b_complevel, type, HDR_HAS_RABD(hdr));
6729 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6730 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6731 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6732 		VERIFY3U(nhdr->b_type, ==, type);
6733 		ASSERT(!HDR_SHARED_DATA(nhdr));
6734 
6735 		nhdr->b_l1hdr.b_buf = buf;
6736 		nhdr->b_l1hdr.b_bufcnt = 1;
6737 		if (ARC_BUF_ENCRYPTED(buf))
6738 			nhdr->b_crypt_hdr.b_ebufcnt = 1;
6739 		nhdr->b_l1hdr.b_mru_hits = 0;
6740 		nhdr->b_l1hdr.b_mru_ghost_hits = 0;
6741 		nhdr->b_l1hdr.b_mfu_hits = 0;
6742 		nhdr->b_l1hdr.b_mfu_ghost_hits = 0;
6743 		nhdr->b_l1hdr.b_l2_hits = 0;
6744 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6745 		buf->b_hdr = nhdr;
6746 
6747 		mutex_exit(&buf->b_evict_lock);
6748 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
6749 		    arc_buf_size(buf), buf);
6750 	} else {
6751 		mutex_exit(&buf->b_evict_lock);
6752 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6753 		/* protected by hash lock, or hdr is on arc_anon */
6754 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6755 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6756 		hdr->b_l1hdr.b_mru_hits = 0;
6757 		hdr->b_l1hdr.b_mru_ghost_hits = 0;
6758 		hdr->b_l1hdr.b_mfu_hits = 0;
6759 		hdr->b_l1hdr.b_mfu_ghost_hits = 0;
6760 		hdr->b_l1hdr.b_l2_hits = 0;
6761 		arc_change_state(arc_anon, hdr, hash_lock);
6762 		hdr->b_l1hdr.b_arc_access = 0;
6763 
6764 		mutex_exit(hash_lock);
6765 		buf_discard_identity(hdr);
6766 		arc_buf_thaw(buf);
6767 	}
6768 }
6769 
6770 int
6771 arc_released(arc_buf_t *buf)
6772 {
6773 	int released;
6774 
6775 	mutex_enter(&buf->b_evict_lock);
6776 	released = (buf->b_data != NULL &&
6777 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
6778 	mutex_exit(&buf->b_evict_lock);
6779 	return (released);
6780 }
6781 
6782 #ifdef ZFS_DEBUG
6783 int
6784 arc_referenced(arc_buf_t *buf)
6785 {
6786 	int referenced;
6787 
6788 	mutex_enter(&buf->b_evict_lock);
6789 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6790 	mutex_exit(&buf->b_evict_lock);
6791 	return (referenced);
6792 }
6793 #endif
6794 
6795 static void
6796 arc_write_ready(zio_t *zio)
6797 {
6798 	arc_write_callback_t *callback = zio->io_private;
6799 	arc_buf_t *buf = callback->awcb_buf;
6800 	arc_buf_hdr_t *hdr = buf->b_hdr;
6801 	blkptr_t *bp = zio->io_bp;
6802 	uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6803 	fstrans_cookie_t cookie = spl_fstrans_mark();
6804 
6805 	ASSERT(HDR_HAS_L1HDR(hdr));
6806 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6807 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6808 
6809 	/*
6810 	 * If we're reexecuting this zio because the pool suspended, then
6811 	 * cleanup any state that was previously set the first time the
6812 	 * callback was invoked.
6813 	 */
6814 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6815 		arc_cksum_free(hdr);
6816 		arc_buf_unwatch(buf);
6817 		if (hdr->b_l1hdr.b_pabd != NULL) {
6818 			if (arc_buf_is_shared(buf)) {
6819 				arc_unshare_buf(hdr, buf);
6820 			} else {
6821 				arc_hdr_free_abd(hdr, B_FALSE);
6822 			}
6823 		}
6824 
6825 		if (HDR_HAS_RABD(hdr))
6826 			arc_hdr_free_abd(hdr, B_TRUE);
6827 	}
6828 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6829 	ASSERT(!HDR_HAS_RABD(hdr));
6830 	ASSERT(!HDR_SHARED_DATA(hdr));
6831 	ASSERT(!arc_buf_is_shared(buf));
6832 
6833 	callback->awcb_ready(zio, buf, callback->awcb_private);
6834 
6835 	if (HDR_IO_IN_PROGRESS(hdr))
6836 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6837 
6838 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6839 
6840 	if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6841 		hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6842 
6843 	if (BP_IS_PROTECTED(bp)) {
6844 		/* ZIL blocks are written through zio_rewrite */
6845 		ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6846 		ASSERT(HDR_PROTECTED(hdr));
6847 
6848 		if (BP_SHOULD_BYTESWAP(bp)) {
6849 			if (BP_GET_LEVEL(bp) > 0) {
6850 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6851 			} else {
6852 				hdr->b_l1hdr.b_byteswap =
6853 				    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6854 			}
6855 		} else {
6856 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6857 		}
6858 
6859 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6860 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6861 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6862 		    hdr->b_crypt_hdr.b_iv);
6863 		zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6864 	}
6865 
6866 	/*
6867 	 * If this block was written for raw encryption but the zio layer
6868 	 * ended up only authenticating it, adjust the buffer flags now.
6869 	 */
6870 	if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6871 		arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6872 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6873 		if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6874 			buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6875 	} else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6876 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6877 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6878 	}
6879 
6880 	/* this must be done after the buffer flags are adjusted */
6881 	arc_cksum_compute(buf);
6882 
6883 	enum zio_compress compress;
6884 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6885 		compress = ZIO_COMPRESS_OFF;
6886 	} else {
6887 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6888 		compress = BP_GET_COMPRESS(bp);
6889 	}
6890 	HDR_SET_PSIZE(hdr, psize);
6891 	arc_hdr_set_compress(hdr, compress);
6892 	hdr->b_complevel = zio->io_prop.zp_complevel;
6893 
6894 	if (zio->io_error != 0 || psize == 0)
6895 		goto out;
6896 
6897 	/*
6898 	 * Fill the hdr with data. If the buffer is encrypted we have no choice
6899 	 * but to copy the data into b_radb. If the hdr is compressed, the data
6900 	 * we want is available from the zio, otherwise we can take it from
6901 	 * the buf.
6902 	 *
6903 	 * We might be able to share the buf's data with the hdr here. However,
6904 	 * doing so would cause the ARC to be full of linear ABDs if we write a
6905 	 * lot of shareable data. As a compromise, we check whether scattered
6906 	 * ABDs are allowed, and assume that if they are then the user wants
6907 	 * the ARC to be primarily filled with them regardless of the data being
6908 	 * written. Therefore, if they're allowed then we allocate one and copy
6909 	 * the data into it; otherwise, we share the data directly if we can.
6910 	 */
6911 	if (ARC_BUF_ENCRYPTED(buf)) {
6912 		ASSERT3U(psize, >, 0);
6913 		ASSERT(ARC_BUF_COMPRESSED(buf));
6914 		arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6915 		abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6916 	} else if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6917 		/*
6918 		 * Ideally, we would always copy the io_abd into b_pabd, but the
6919 		 * user may have disabled compressed ARC, thus we must check the
6920 		 * hdr's compression setting rather than the io_bp's.
6921 		 */
6922 		if (BP_IS_ENCRYPTED(bp)) {
6923 			ASSERT3U(psize, >, 0);
6924 			arc_hdr_alloc_abd(hdr,
6925 			    ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6926 			abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6927 		} else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6928 		    !ARC_BUF_COMPRESSED(buf)) {
6929 			ASSERT3U(psize, >, 0);
6930 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6931 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6932 		} else {
6933 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6934 			arc_hdr_alloc_abd(hdr, ARC_HDR_DO_ADAPT);
6935 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6936 			    arc_buf_size(buf));
6937 		}
6938 	} else {
6939 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6940 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6941 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6942 
6943 		arc_share_buf(hdr, buf);
6944 	}
6945 
6946 out:
6947 	arc_hdr_verify(hdr, bp);
6948 	spl_fstrans_unmark(cookie);
6949 }
6950 
6951 static void
6952 arc_write_children_ready(zio_t *zio)
6953 {
6954 	arc_write_callback_t *callback = zio->io_private;
6955 	arc_buf_t *buf = callback->awcb_buf;
6956 
6957 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
6958 }
6959 
6960 /*
6961  * The SPA calls this callback for each physical write that happens on behalf
6962  * of a logical write.  See the comment in dbuf_write_physdone() for details.
6963  */
6964 static void
6965 arc_write_physdone(zio_t *zio)
6966 {
6967 	arc_write_callback_t *cb = zio->io_private;
6968 	if (cb->awcb_physdone != NULL)
6969 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6970 }
6971 
6972 static void
6973 arc_write_done(zio_t *zio)
6974 {
6975 	arc_write_callback_t *callback = zio->io_private;
6976 	arc_buf_t *buf = callback->awcb_buf;
6977 	arc_buf_hdr_t *hdr = buf->b_hdr;
6978 
6979 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6980 
6981 	if (zio->io_error == 0) {
6982 		arc_hdr_verify(hdr, zio->io_bp);
6983 
6984 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6985 			buf_discard_identity(hdr);
6986 		} else {
6987 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6988 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6989 		}
6990 	} else {
6991 		ASSERT(HDR_EMPTY(hdr));
6992 	}
6993 
6994 	/*
6995 	 * If the block to be written was all-zero or compressed enough to be
6996 	 * embedded in the BP, no write was performed so there will be no
6997 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
6998 	 * (and uncached).
6999 	 */
7000 	if (!HDR_EMPTY(hdr)) {
7001 		arc_buf_hdr_t *exists;
7002 		kmutex_t *hash_lock;
7003 
7004 		ASSERT3U(zio->io_error, ==, 0);
7005 
7006 		arc_cksum_verify(buf);
7007 
7008 		exists = buf_hash_insert(hdr, &hash_lock);
7009 		if (exists != NULL) {
7010 			/*
7011 			 * This can only happen if we overwrite for
7012 			 * sync-to-convergence, because we remove
7013 			 * buffers from the hash table when we arc_free().
7014 			 */
7015 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
7016 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
7017 					panic("bad overwrite, hdr=%p exists=%p",
7018 					    (void *)hdr, (void *)exists);
7019 				ASSERT(zfs_refcount_is_zero(
7020 				    &exists->b_l1hdr.b_refcnt));
7021 				arc_change_state(arc_anon, exists, hash_lock);
7022 				arc_hdr_destroy(exists);
7023 				mutex_exit(hash_lock);
7024 				exists = buf_hash_insert(hdr, &hash_lock);
7025 				ASSERT3P(exists, ==, NULL);
7026 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
7027 				/* nopwrite */
7028 				ASSERT(zio->io_prop.zp_nopwrite);
7029 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
7030 					panic("bad nopwrite, hdr=%p exists=%p",
7031 					    (void *)hdr, (void *)exists);
7032 			} else {
7033 				/* Dedup */
7034 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
7035 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
7036 				ASSERT(BP_GET_DEDUP(zio->io_bp));
7037 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
7038 			}
7039 		}
7040 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
7041 		/* if it's not anon, we are doing a scrub */
7042 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
7043 			arc_access(hdr, hash_lock);
7044 		mutex_exit(hash_lock);
7045 	} else {
7046 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
7047 	}
7048 
7049 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
7050 	callback->awcb_done(zio, buf, callback->awcb_private);
7051 
7052 	abd_free(zio->io_abd);
7053 	kmem_free(callback, sizeof (arc_write_callback_t));
7054 }
7055 
7056 zio_t *
7057 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
7058     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc,
7059     const zio_prop_t *zp, arc_write_done_func_t *ready,
7060     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
7061     arc_write_done_func_t *done, void *private, zio_priority_t priority,
7062     int zio_flags, const zbookmark_phys_t *zb)
7063 {
7064 	arc_buf_hdr_t *hdr = buf->b_hdr;
7065 	arc_write_callback_t *callback;
7066 	zio_t *zio;
7067 	zio_prop_t localprop = *zp;
7068 
7069 	ASSERT3P(ready, !=, NULL);
7070 	ASSERT3P(done, !=, NULL);
7071 	ASSERT(!HDR_IO_ERROR(hdr));
7072 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
7073 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
7074 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
7075 	if (l2arc)
7076 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
7077 
7078 	if (ARC_BUF_ENCRYPTED(buf)) {
7079 		ASSERT(ARC_BUF_COMPRESSED(buf));
7080 		localprop.zp_encrypt = B_TRUE;
7081 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
7082 		localprop.zp_complevel = hdr->b_complevel;
7083 		localprop.zp_byteorder =
7084 		    (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
7085 		    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
7086 		bcopy(hdr->b_crypt_hdr.b_salt, localprop.zp_salt,
7087 		    ZIO_DATA_SALT_LEN);
7088 		bcopy(hdr->b_crypt_hdr.b_iv, localprop.zp_iv,
7089 		    ZIO_DATA_IV_LEN);
7090 		bcopy(hdr->b_crypt_hdr.b_mac, localprop.zp_mac,
7091 		    ZIO_DATA_MAC_LEN);
7092 		if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
7093 			localprop.zp_nopwrite = B_FALSE;
7094 			localprop.zp_copies =
7095 			    MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
7096 		}
7097 		zio_flags |= ZIO_FLAG_RAW;
7098 	} else if (ARC_BUF_COMPRESSED(buf)) {
7099 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
7100 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
7101 		localprop.zp_complevel = hdr->b_complevel;
7102 		zio_flags |= ZIO_FLAG_RAW_COMPRESS;
7103 	}
7104 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
7105 	callback->awcb_ready = ready;
7106 	callback->awcb_children_ready = children_ready;
7107 	callback->awcb_physdone = physdone;
7108 	callback->awcb_done = done;
7109 	callback->awcb_private = private;
7110 	callback->awcb_buf = buf;
7111 
7112 	/*
7113 	 * The hdr's b_pabd is now stale, free it now. A new data block
7114 	 * will be allocated when the zio pipeline calls arc_write_ready().
7115 	 */
7116 	if (hdr->b_l1hdr.b_pabd != NULL) {
7117 		/*
7118 		 * If the buf is currently sharing the data block with
7119 		 * the hdr then we need to break that relationship here.
7120 		 * The hdr will remain with a NULL data pointer and the
7121 		 * buf will take sole ownership of the block.
7122 		 */
7123 		if (arc_buf_is_shared(buf)) {
7124 			arc_unshare_buf(hdr, buf);
7125 		} else {
7126 			arc_hdr_free_abd(hdr, B_FALSE);
7127 		}
7128 		VERIFY3P(buf->b_data, !=, NULL);
7129 	}
7130 
7131 	if (HDR_HAS_RABD(hdr))
7132 		arc_hdr_free_abd(hdr, B_TRUE);
7133 
7134 	if (!(zio_flags & ZIO_FLAG_RAW))
7135 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
7136 
7137 	ASSERT(!arc_buf_is_shared(buf));
7138 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
7139 
7140 	zio = zio_write(pio, spa, txg, bp,
7141 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
7142 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
7143 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
7144 	    arc_write_physdone, arc_write_done, callback,
7145 	    priority, zio_flags, zb);
7146 
7147 	return (zio);
7148 }
7149 
7150 void
7151 arc_tempreserve_clear(uint64_t reserve)
7152 {
7153 	atomic_add_64(&arc_tempreserve, -reserve);
7154 	ASSERT((int64_t)arc_tempreserve >= 0);
7155 }
7156 
7157 int
7158 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
7159 {
7160 	int error;
7161 	uint64_t anon_size;
7162 
7163 	if (!arc_no_grow &&
7164 	    reserve > arc_c/4 &&
7165 	    reserve * 4 > (2ULL << SPA_MAXBLOCKSHIFT))
7166 		arc_c = MIN(arc_c_max, reserve * 4);
7167 
7168 	/*
7169 	 * Throttle when the calculated memory footprint for the TXG
7170 	 * exceeds the target ARC size.
7171 	 */
7172 	if (reserve > arc_c) {
7173 		DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
7174 		return (SET_ERROR(ERESTART));
7175 	}
7176 
7177 	/*
7178 	 * Don't count loaned bufs as in flight dirty data to prevent long
7179 	 * network delays from blocking transactions that are ready to be
7180 	 * assigned to a txg.
7181 	 */
7182 
7183 	/* assert that it has not wrapped around */
7184 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
7185 
7186 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
7187 	    arc_loaned_bytes), 0);
7188 
7189 	/*
7190 	 * Writes will, almost always, require additional memory allocations
7191 	 * in order to compress/encrypt/etc the data.  We therefore need to
7192 	 * make sure that there is sufficient available memory for this.
7193 	 */
7194 	error = arc_memory_throttle(spa, reserve, txg);
7195 	if (error != 0)
7196 		return (error);
7197 
7198 	/*
7199 	 * Throttle writes when the amount of dirty data in the cache
7200 	 * gets too large.  We try to keep the cache less than half full
7201 	 * of dirty blocks so that our sync times don't grow too large.
7202 	 *
7203 	 * In the case of one pool being built on another pool, we want
7204 	 * to make sure we don't end up throttling the lower (backing)
7205 	 * pool when the upper pool is the majority contributor to dirty
7206 	 * data. To insure we make forward progress during throttling, we
7207 	 * also check the current pool's net dirty data and only throttle
7208 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
7209 	 * data in the cache.
7210 	 *
7211 	 * Note: if two requests come in concurrently, we might let them
7212 	 * both succeed, when one of them should fail.  Not a huge deal.
7213 	 */
7214 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
7215 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
7216 	uint64_t rarc_c = arc_warm ? arc_c : arc_c_max;
7217 	if (total_dirty > rarc_c * zfs_arc_dirty_limit_percent / 100 &&
7218 	    anon_size > rarc_c * zfs_arc_anon_limit_percent / 100 &&
7219 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
7220 #ifdef ZFS_DEBUG
7221 		uint64_t meta_esize = zfs_refcount_count(
7222 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7223 		uint64_t data_esize =
7224 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7225 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
7226 		    "anon_data=%lluK tempreserve=%lluK rarc_c=%lluK\n",
7227 		    arc_tempreserve >> 10, meta_esize >> 10,
7228 		    data_esize >> 10, reserve >> 10, rarc_c >> 10);
7229 #endif
7230 		DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
7231 		return (SET_ERROR(ERESTART));
7232 	}
7233 	atomic_add_64(&arc_tempreserve, reserve);
7234 	return (0);
7235 }
7236 
7237 static void
7238 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
7239     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
7240 {
7241 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
7242 	evict_data->value.ui64 =
7243 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
7244 	evict_metadata->value.ui64 =
7245 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
7246 }
7247 
7248 static int
7249 arc_kstat_update(kstat_t *ksp, int rw)
7250 {
7251 	arc_stats_t *as = ksp->ks_data;
7252 
7253 	if (rw == KSTAT_WRITE) {
7254 		return (SET_ERROR(EACCES));
7255 	} else {
7256 		arc_kstat_update_state(arc_anon,
7257 		    &as->arcstat_anon_size,
7258 		    &as->arcstat_anon_evictable_data,
7259 		    &as->arcstat_anon_evictable_metadata);
7260 		arc_kstat_update_state(arc_mru,
7261 		    &as->arcstat_mru_size,
7262 		    &as->arcstat_mru_evictable_data,
7263 		    &as->arcstat_mru_evictable_metadata);
7264 		arc_kstat_update_state(arc_mru_ghost,
7265 		    &as->arcstat_mru_ghost_size,
7266 		    &as->arcstat_mru_ghost_evictable_data,
7267 		    &as->arcstat_mru_ghost_evictable_metadata);
7268 		arc_kstat_update_state(arc_mfu,
7269 		    &as->arcstat_mfu_size,
7270 		    &as->arcstat_mfu_evictable_data,
7271 		    &as->arcstat_mfu_evictable_metadata);
7272 		arc_kstat_update_state(arc_mfu_ghost,
7273 		    &as->arcstat_mfu_ghost_size,
7274 		    &as->arcstat_mfu_ghost_evictable_data,
7275 		    &as->arcstat_mfu_ghost_evictable_metadata);
7276 
7277 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
7278 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
7279 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
7280 		ARCSTAT(arcstat_metadata_size) =
7281 		    aggsum_value(&astat_metadata_size);
7282 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
7283 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
7284 		ARCSTAT(arcstat_dbuf_size) = aggsum_value(&astat_dbuf_size);
7285 #if defined(COMPAT_FREEBSD11)
7286 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_bonus_size) +
7287 		    aggsum_value(&astat_dnode_size) +
7288 		    aggsum_value(&astat_dbuf_size);
7289 #endif
7290 		ARCSTAT(arcstat_dnode_size) = aggsum_value(&astat_dnode_size);
7291 		ARCSTAT(arcstat_bonus_size) = aggsum_value(&astat_bonus_size);
7292 		ARCSTAT(arcstat_abd_chunk_waste_size) =
7293 		    aggsum_value(&astat_abd_chunk_waste_size);
7294 
7295 		as->arcstat_memory_all_bytes.value.ui64 =
7296 		    arc_all_memory();
7297 		as->arcstat_memory_free_bytes.value.ui64 =
7298 		    arc_free_memory();
7299 		as->arcstat_memory_available_bytes.value.i64 =
7300 		    arc_available_memory();
7301 	}
7302 
7303 	return (0);
7304 }
7305 
7306 /*
7307  * This function *must* return indices evenly distributed between all
7308  * sublists of the multilist. This is needed due to how the ARC eviction
7309  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
7310  * distributed between all sublists and uses this assumption when
7311  * deciding which sublist to evict from and how much to evict from it.
7312  */
7313 static unsigned int
7314 arc_state_multilist_index_func(multilist_t *ml, void *obj)
7315 {
7316 	arc_buf_hdr_t *hdr = obj;
7317 
7318 	/*
7319 	 * We rely on b_dva to generate evenly distributed index
7320 	 * numbers using buf_hash below. So, as an added precaution,
7321 	 * let's make sure we never add empty buffers to the arc lists.
7322 	 */
7323 	ASSERT(!HDR_EMPTY(hdr));
7324 
7325 	/*
7326 	 * The assumption here, is the hash value for a given
7327 	 * arc_buf_hdr_t will remain constant throughout its lifetime
7328 	 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
7329 	 * Thus, we don't need to store the header's sublist index
7330 	 * on insertion, as this index can be recalculated on removal.
7331 	 *
7332 	 * Also, the low order bits of the hash value are thought to be
7333 	 * distributed evenly. Otherwise, in the case that the multilist
7334 	 * has a power of two number of sublists, each sublists' usage
7335 	 * would not be evenly distributed.
7336 	 */
7337 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
7338 	    multilist_get_num_sublists(ml));
7339 }
7340 
7341 #define	WARN_IF_TUNING_IGNORED(tuning, value, do_warn) do {	\
7342 	if ((do_warn) && (tuning) && ((tuning) != (value))) {	\
7343 		cmn_err(CE_WARN,				\
7344 		    "ignoring tunable %s (using %llu instead)",	\
7345 		    (#tuning), (value));			\
7346 	}							\
7347 } while (0)
7348 
7349 /*
7350  * Called during module initialization and periodically thereafter to
7351  * apply reasonable changes to the exposed performance tunings.  Can also be
7352  * called explicitly by param_set_arc_*() functions when ARC tunables are
7353  * updated manually.  Non-zero zfs_* values which differ from the currently set
7354  * values will be applied.
7355  */
7356 void
7357 arc_tuning_update(boolean_t verbose)
7358 {
7359 	uint64_t allmem = arc_all_memory();
7360 	unsigned long limit;
7361 
7362 	/* Valid range: 32M - <arc_c_max> */
7363 	if ((zfs_arc_min) && (zfs_arc_min != arc_c_min) &&
7364 	    (zfs_arc_min >= 2ULL << SPA_MAXBLOCKSHIFT) &&
7365 	    (zfs_arc_min <= arc_c_max)) {
7366 		arc_c_min = zfs_arc_min;
7367 		arc_c = MAX(arc_c, arc_c_min);
7368 	}
7369 	WARN_IF_TUNING_IGNORED(zfs_arc_min, arc_c_min, verbose);
7370 
7371 	/* Valid range: 64M - <all physical memory> */
7372 	if ((zfs_arc_max) && (zfs_arc_max != arc_c_max) &&
7373 	    (zfs_arc_max >= 64 << 20) && (zfs_arc_max < allmem) &&
7374 	    (zfs_arc_max > arc_c_min)) {
7375 		arc_c_max = zfs_arc_max;
7376 		arc_c = MIN(arc_c, arc_c_max);
7377 		arc_p = (arc_c >> 1);
7378 		if (arc_meta_limit > arc_c_max)
7379 			arc_meta_limit = arc_c_max;
7380 		if (arc_dnode_size_limit > arc_meta_limit)
7381 			arc_dnode_size_limit = arc_meta_limit;
7382 	}
7383 	WARN_IF_TUNING_IGNORED(zfs_arc_max, arc_c_max, verbose);
7384 
7385 	/* Valid range: 16M - <arc_c_max> */
7386 	if ((zfs_arc_meta_min) && (zfs_arc_meta_min != arc_meta_min) &&
7387 	    (zfs_arc_meta_min >= 1ULL << SPA_MAXBLOCKSHIFT) &&
7388 	    (zfs_arc_meta_min <= arc_c_max)) {
7389 		arc_meta_min = zfs_arc_meta_min;
7390 		if (arc_meta_limit < arc_meta_min)
7391 			arc_meta_limit = arc_meta_min;
7392 		if (arc_dnode_size_limit < arc_meta_min)
7393 			arc_dnode_size_limit = arc_meta_min;
7394 	}
7395 	WARN_IF_TUNING_IGNORED(zfs_arc_meta_min, arc_meta_min, verbose);
7396 
7397 	/* Valid range: <arc_meta_min> - <arc_c_max> */
7398 	limit = zfs_arc_meta_limit ? zfs_arc_meta_limit :
7399 	    MIN(zfs_arc_meta_limit_percent, 100) * arc_c_max / 100;
7400 	if ((limit != arc_meta_limit) &&
7401 	    (limit >= arc_meta_min) &&
7402 	    (limit <= arc_c_max))
7403 		arc_meta_limit = limit;
7404 	WARN_IF_TUNING_IGNORED(zfs_arc_meta_limit, arc_meta_limit, verbose);
7405 
7406 	/* Valid range: <arc_meta_min> - <arc_meta_limit> */
7407 	limit = zfs_arc_dnode_limit ? zfs_arc_dnode_limit :
7408 	    MIN(zfs_arc_dnode_limit_percent, 100) * arc_meta_limit / 100;
7409 	if ((limit != arc_dnode_size_limit) &&
7410 	    (limit >= arc_meta_min) &&
7411 	    (limit <= arc_meta_limit))
7412 		arc_dnode_size_limit = limit;
7413 	WARN_IF_TUNING_IGNORED(zfs_arc_dnode_limit, arc_dnode_size_limit,
7414 	    verbose);
7415 
7416 	/* Valid range: 1 - N */
7417 	if (zfs_arc_grow_retry)
7418 		arc_grow_retry = zfs_arc_grow_retry;
7419 
7420 	/* Valid range: 1 - N */
7421 	if (zfs_arc_shrink_shift) {
7422 		arc_shrink_shift = zfs_arc_shrink_shift;
7423 		arc_no_grow_shift = MIN(arc_no_grow_shift, arc_shrink_shift -1);
7424 	}
7425 
7426 	/* Valid range: 1 - N */
7427 	if (zfs_arc_p_min_shift)
7428 		arc_p_min_shift = zfs_arc_p_min_shift;
7429 
7430 	/* Valid range: 1 - N ms */
7431 	if (zfs_arc_min_prefetch_ms)
7432 		arc_min_prefetch_ms = zfs_arc_min_prefetch_ms;
7433 
7434 	/* Valid range: 1 - N ms */
7435 	if (zfs_arc_min_prescient_prefetch_ms) {
7436 		arc_min_prescient_prefetch_ms =
7437 		    zfs_arc_min_prescient_prefetch_ms;
7438 	}
7439 
7440 	/* Valid range: 0 - 100 */
7441 	if ((zfs_arc_lotsfree_percent >= 0) &&
7442 	    (zfs_arc_lotsfree_percent <= 100))
7443 		arc_lotsfree_percent = zfs_arc_lotsfree_percent;
7444 	WARN_IF_TUNING_IGNORED(zfs_arc_lotsfree_percent, arc_lotsfree_percent,
7445 	    verbose);
7446 
7447 	/* Valid range: 0 - <all physical memory> */
7448 	if ((zfs_arc_sys_free) && (zfs_arc_sys_free != arc_sys_free))
7449 		arc_sys_free = MIN(MAX(zfs_arc_sys_free, 0), allmem);
7450 	WARN_IF_TUNING_IGNORED(zfs_arc_sys_free, arc_sys_free, verbose);
7451 }
7452 
7453 static void
7454 arc_state_init(void)
7455 {
7456 	arc_anon = &ARC_anon;
7457 	arc_mru = &ARC_mru;
7458 	arc_mru_ghost = &ARC_mru_ghost;
7459 	arc_mfu = &ARC_mfu;
7460 	arc_mfu_ghost = &ARC_mfu_ghost;
7461 	arc_l2c_only = &ARC_l2c_only;
7462 
7463 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
7464 	    multilist_create(sizeof (arc_buf_hdr_t),
7465 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7466 	    arc_state_multilist_index_func);
7467 	arc_mru->arcs_list[ARC_BUFC_DATA] =
7468 	    multilist_create(sizeof (arc_buf_hdr_t),
7469 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7470 	    arc_state_multilist_index_func);
7471 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
7472 	    multilist_create(sizeof (arc_buf_hdr_t),
7473 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7474 	    arc_state_multilist_index_func);
7475 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
7476 	    multilist_create(sizeof (arc_buf_hdr_t),
7477 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7478 	    arc_state_multilist_index_func);
7479 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
7480 	    multilist_create(sizeof (arc_buf_hdr_t),
7481 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7482 	    arc_state_multilist_index_func);
7483 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
7484 	    multilist_create(sizeof (arc_buf_hdr_t),
7485 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7486 	    arc_state_multilist_index_func);
7487 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
7488 	    multilist_create(sizeof (arc_buf_hdr_t),
7489 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7490 	    arc_state_multilist_index_func);
7491 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
7492 	    multilist_create(sizeof (arc_buf_hdr_t),
7493 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7494 	    arc_state_multilist_index_func);
7495 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
7496 	    multilist_create(sizeof (arc_buf_hdr_t),
7497 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7498 	    arc_state_multilist_index_func);
7499 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
7500 	    multilist_create(sizeof (arc_buf_hdr_t),
7501 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7502 	    arc_state_multilist_index_func);
7503 
7504 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7505 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7506 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7507 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7508 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7509 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7510 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7511 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7512 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7513 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7514 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7515 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7516 
7517 	zfs_refcount_create(&arc_anon->arcs_size);
7518 	zfs_refcount_create(&arc_mru->arcs_size);
7519 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
7520 	zfs_refcount_create(&arc_mfu->arcs_size);
7521 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7522 	zfs_refcount_create(&arc_l2c_only->arcs_size);
7523 
7524 	aggsum_init(&arc_meta_used, 0);
7525 	aggsum_init(&arc_size, 0);
7526 	aggsum_init(&astat_data_size, 0);
7527 	aggsum_init(&astat_metadata_size, 0);
7528 	aggsum_init(&astat_hdr_size, 0);
7529 	aggsum_init(&astat_l2_hdr_size, 0);
7530 	aggsum_init(&astat_bonus_size, 0);
7531 	aggsum_init(&astat_dnode_size, 0);
7532 	aggsum_init(&astat_dbuf_size, 0);
7533 	aggsum_init(&astat_abd_chunk_waste_size, 0);
7534 
7535 	arc_anon->arcs_state = ARC_STATE_ANON;
7536 	arc_mru->arcs_state = ARC_STATE_MRU;
7537 	arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7538 	arc_mfu->arcs_state = ARC_STATE_MFU;
7539 	arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7540 	arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
7541 }
7542 
7543 static void
7544 arc_state_fini(void)
7545 {
7546 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7547 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7548 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7549 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7550 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7551 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7552 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7553 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7554 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7555 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7556 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7557 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7558 
7559 	zfs_refcount_destroy(&arc_anon->arcs_size);
7560 	zfs_refcount_destroy(&arc_mru->arcs_size);
7561 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7562 	zfs_refcount_destroy(&arc_mfu->arcs_size);
7563 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7564 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7565 
7566 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
7567 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7568 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7569 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7570 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
7571 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7572 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
7573 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7574 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7575 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
7576 
7577 	aggsum_fini(&arc_meta_used);
7578 	aggsum_fini(&arc_size);
7579 	aggsum_fini(&astat_data_size);
7580 	aggsum_fini(&astat_metadata_size);
7581 	aggsum_fini(&astat_hdr_size);
7582 	aggsum_fini(&astat_l2_hdr_size);
7583 	aggsum_fini(&astat_bonus_size);
7584 	aggsum_fini(&astat_dnode_size);
7585 	aggsum_fini(&astat_dbuf_size);
7586 	aggsum_fini(&astat_abd_chunk_waste_size);
7587 }
7588 
7589 uint64_t
7590 arc_target_bytes(void)
7591 {
7592 	return (arc_c);
7593 }
7594 
7595 void
7596 arc_set_limits(uint64_t allmem)
7597 {
7598 	/* Set min cache to 1/32 of all memory, or 32MB, whichever is more. */
7599 	arc_c_min = MAX(allmem / 32, 2ULL << SPA_MAXBLOCKSHIFT);
7600 
7601 	/* How to set default max varies by platform. */
7602 	arc_c_max = arc_default_max(arc_c_min, allmem);
7603 }
7604 void
7605 arc_init(void)
7606 {
7607 	uint64_t percent, allmem = arc_all_memory();
7608 	mutex_init(&arc_evict_lock, NULL, MUTEX_DEFAULT, NULL);
7609 	list_create(&arc_evict_waiters, sizeof (arc_evict_waiter_t),
7610 	    offsetof(arc_evict_waiter_t, aew_node));
7611 
7612 	arc_min_prefetch_ms = 1000;
7613 	arc_min_prescient_prefetch_ms = 6000;
7614 
7615 #if defined(_KERNEL)
7616 	arc_lowmem_init();
7617 #endif
7618 
7619 	arc_set_limits(allmem);
7620 
7621 #ifndef _KERNEL
7622 	/*
7623 	 * In userland, there's only the memory pressure that we artificially
7624 	 * create (see arc_available_memory()).  Don't let arc_c get too
7625 	 * small, because it can cause transactions to be larger than
7626 	 * arc_c, causing arc_tempreserve_space() to fail.
7627 	 */
7628 	arc_c_min = MAX(arc_c_max / 2, 2ULL << SPA_MAXBLOCKSHIFT);
7629 #endif
7630 
7631 	arc_c = arc_c_min;
7632 	arc_p = (arc_c >> 1);
7633 
7634 	/* Set min to 1/2 of arc_c_min */
7635 	arc_meta_min = 1ULL << SPA_MAXBLOCKSHIFT;
7636 	/* Initialize maximum observed usage to zero */
7637 	arc_meta_max = 0;
7638 	/*
7639 	 * Set arc_meta_limit to a percent of arc_c_max with a floor of
7640 	 * arc_meta_min, and a ceiling of arc_c_max.
7641 	 */
7642 	percent = MIN(zfs_arc_meta_limit_percent, 100);
7643 	arc_meta_limit = MAX(arc_meta_min, (percent * arc_c_max) / 100);
7644 	percent = MIN(zfs_arc_dnode_limit_percent, 100);
7645 	arc_dnode_size_limit = (percent * arc_meta_limit) / 100;
7646 
7647 	/* Apply user specified tunings */
7648 	arc_tuning_update(B_TRUE);
7649 
7650 	/* if kmem_flags are set, lets try to use less memory */
7651 	if (kmem_debugging())
7652 		arc_c = arc_c / 2;
7653 	if (arc_c < arc_c_min)
7654 		arc_c = arc_c_min;
7655 
7656 	arc_register_hotplug();
7657 
7658 	arc_state_init();
7659 
7660 	buf_init();
7661 
7662 	list_create(&arc_prune_list, sizeof (arc_prune_t),
7663 	    offsetof(arc_prune_t, p_node));
7664 	mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
7665 
7666 	arc_prune_taskq = taskq_create("arc_prune", 100, defclsyspri,
7667 	    boot_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC |
7668 	    TASKQ_THREADS_CPU_PCT);
7669 
7670 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7671 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7672 
7673 	if (arc_ksp != NULL) {
7674 		arc_ksp->ks_data = &arc_stats;
7675 		arc_ksp->ks_update = arc_kstat_update;
7676 		kstat_install(arc_ksp);
7677 	}
7678 
7679 	arc_evict_zthr = zthr_create("arc_evict",
7680 	    arc_evict_cb_check, arc_evict_cb, NULL);
7681 	arc_reap_zthr = zthr_create_timer("arc_reap",
7682 	    arc_reap_cb_check, arc_reap_cb, NULL, SEC2NSEC(1));
7683 
7684 	arc_warm = B_FALSE;
7685 
7686 	/*
7687 	 * Calculate maximum amount of dirty data per pool.
7688 	 *
7689 	 * If it has been set by a module parameter, take that.
7690 	 * Otherwise, use a percentage of physical memory defined by
7691 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
7692 	 * zfs_dirty_data_max_max (default 4G or 25% of physical memory).
7693 	 */
7694 #ifdef __LP64__
7695 	if (zfs_dirty_data_max_max == 0)
7696 		zfs_dirty_data_max_max = MIN(4ULL * 1024 * 1024 * 1024,
7697 		    allmem * zfs_dirty_data_max_max_percent / 100);
7698 #else
7699 	if (zfs_dirty_data_max_max == 0)
7700 		zfs_dirty_data_max_max = MIN(1ULL * 1024 * 1024 * 1024,
7701 		    allmem * zfs_dirty_data_max_max_percent / 100);
7702 #endif
7703 
7704 	if (zfs_dirty_data_max == 0) {
7705 		zfs_dirty_data_max = allmem *
7706 		    zfs_dirty_data_max_percent / 100;
7707 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7708 		    zfs_dirty_data_max_max);
7709 	}
7710 }
7711 
7712 void
7713 arc_fini(void)
7714 {
7715 	arc_prune_t *p;
7716 
7717 #ifdef _KERNEL
7718 	arc_lowmem_fini();
7719 #endif /* _KERNEL */
7720 
7721 	/* Use B_TRUE to ensure *all* buffers are evicted */
7722 	arc_flush(NULL, B_TRUE);
7723 
7724 	if (arc_ksp != NULL) {
7725 		kstat_delete(arc_ksp);
7726 		arc_ksp = NULL;
7727 	}
7728 
7729 	taskq_wait(arc_prune_taskq);
7730 	taskq_destroy(arc_prune_taskq);
7731 
7732 	mutex_enter(&arc_prune_mtx);
7733 	while ((p = list_head(&arc_prune_list)) != NULL) {
7734 		list_remove(&arc_prune_list, p);
7735 		zfs_refcount_remove(&p->p_refcnt, &arc_prune_list);
7736 		zfs_refcount_destroy(&p->p_refcnt);
7737 		kmem_free(p, sizeof (*p));
7738 	}
7739 	mutex_exit(&arc_prune_mtx);
7740 
7741 	list_destroy(&arc_prune_list);
7742 	mutex_destroy(&arc_prune_mtx);
7743 
7744 	(void) zthr_cancel(arc_evict_zthr);
7745 	(void) zthr_cancel(arc_reap_zthr);
7746 
7747 	mutex_destroy(&arc_evict_lock);
7748 	list_destroy(&arc_evict_waiters);
7749 
7750 	/*
7751 	 * Free any buffers that were tagged for destruction.  This needs
7752 	 * to occur before arc_state_fini() runs and destroys the aggsum
7753 	 * values which are updated when freeing scatter ABDs.
7754 	 */
7755 	l2arc_do_free_on_write();
7756 
7757 	/*
7758 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
7759 	 * trigger the release of kmem magazines, which can callback to
7760 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
7761 	 */
7762 	buf_fini();
7763 	arc_state_fini();
7764 
7765 	arc_unregister_hotplug();
7766 
7767 	/*
7768 	 * We destroy the zthrs after all the ARC state has been
7769 	 * torn down to avoid the case of them receiving any
7770 	 * wakeup() signals after they are destroyed.
7771 	 */
7772 	zthr_destroy(arc_evict_zthr);
7773 	zthr_destroy(arc_reap_zthr);
7774 
7775 	ASSERT0(arc_loaned_bytes);
7776 }
7777 
7778 /*
7779  * Level 2 ARC
7780  *
7781  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7782  * It uses dedicated storage devices to hold cached data, which are populated
7783  * using large infrequent writes.  The main role of this cache is to boost
7784  * the performance of random read workloads.  The intended L2ARC devices
7785  * include short-stroked disks, solid state disks, and other media with
7786  * substantially faster read latency than disk.
7787  *
7788  *                 +-----------------------+
7789  *                 |         ARC           |
7790  *                 +-----------------------+
7791  *                    |         ^     ^
7792  *                    |         |     |
7793  *      l2arc_feed_thread()    arc_read()
7794  *                    |         |     |
7795  *                    |  l2arc read   |
7796  *                    V         |     |
7797  *               +---------------+    |
7798  *               |     L2ARC     |    |
7799  *               +---------------+    |
7800  *                   |    ^           |
7801  *          l2arc_write() |           |
7802  *                   |    |           |
7803  *                   V    |           |
7804  *                 +-------+      +-------+
7805  *                 | vdev  |      | vdev  |
7806  *                 | cache |      | cache |
7807  *                 +-------+      +-------+
7808  *                 +=========+     .-----.
7809  *                 :  L2ARC  :    |-_____-|
7810  *                 : devices :    | Disks |
7811  *                 +=========+    `-_____-'
7812  *
7813  * Read requests are satisfied from the following sources, in order:
7814  *
7815  *	1) ARC
7816  *	2) vdev cache of L2ARC devices
7817  *	3) L2ARC devices
7818  *	4) vdev cache of disks
7819  *	5) disks
7820  *
7821  * Some L2ARC device types exhibit extremely slow write performance.
7822  * To accommodate for this there are some significant differences between
7823  * the L2ARC and traditional cache design:
7824  *
7825  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
7826  * the ARC behave as usual, freeing buffers and placing headers on ghost
7827  * lists.  The ARC does not send buffers to the L2ARC during eviction as
7828  * this would add inflated write latencies for all ARC memory pressure.
7829  *
7830  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7831  * It does this by periodically scanning buffers from the eviction-end of
7832  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7833  * not already there. It scans until a headroom of buffers is satisfied,
7834  * which itself is a buffer for ARC eviction. If a compressible buffer is
7835  * found during scanning and selected for writing to an L2ARC device, we
7836  * temporarily boost scanning headroom during the next scan cycle to make
7837  * sure we adapt to compression effects (which might significantly reduce
7838  * the data volume we write to L2ARC). The thread that does this is
7839  * l2arc_feed_thread(), illustrated below; example sizes are included to
7840  * provide a better sense of ratio than this diagram:
7841  *
7842  *	       head -->                        tail
7843  *	        +---------------------+----------+
7844  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
7845  *	        +---------------------+----------+   |   o L2ARC eligible
7846  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
7847  *	        +---------------------+----------+   |
7848  *	             15.9 Gbytes      ^ 32 Mbytes    |
7849  *	                           headroom          |
7850  *	                                      l2arc_feed_thread()
7851  *	                                             |
7852  *	                 l2arc write hand <--[oooo]--'
7853  *	                         |           8 Mbyte
7854  *	                         |          write max
7855  *	                         V
7856  *		  +==============================+
7857  *	L2ARC dev |####|#|###|###|    |####| ... |
7858  *	          +==============================+
7859  *	                     32 Gbytes
7860  *
7861  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7862  * evicted, then the L2ARC has cached a buffer much sooner than it probably
7863  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
7864  * safe to say that this is an uncommon case, since buffers at the end of
7865  * the ARC lists have moved there due to inactivity.
7866  *
7867  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7868  * then the L2ARC simply misses copying some buffers.  This serves as a
7869  * pressure valve to prevent heavy read workloads from both stalling the ARC
7870  * with waits and clogging the L2ARC with writes.  This also helps prevent
7871  * the potential for the L2ARC to churn if it attempts to cache content too
7872  * quickly, such as during backups of the entire pool.
7873  *
7874  * 5. After system boot and before the ARC has filled main memory, there are
7875  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7876  * lists can remain mostly static.  Instead of searching from tail of these
7877  * lists as pictured, the l2arc_feed_thread() will search from the list heads
7878  * for eligible buffers, greatly increasing its chance of finding them.
7879  *
7880  * The L2ARC device write speed is also boosted during this time so that
7881  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
7882  * there are no L2ARC reads, and no fear of degrading read performance
7883  * through increased writes.
7884  *
7885  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7886  * the vdev queue can aggregate them into larger and fewer writes.  Each
7887  * device is written to in a rotor fashion, sweeping writes through
7888  * available space then repeating.
7889  *
7890  * 7. The L2ARC does not store dirty content.  It never needs to flush
7891  * write buffers back to disk based storage.
7892  *
7893  * 8. If an ARC buffer is written (and dirtied) which also exists in the
7894  * L2ARC, the now stale L2ARC buffer is immediately dropped.
7895  *
7896  * The performance of the L2ARC can be tweaked by a number of tunables, which
7897  * may be necessary for different workloads:
7898  *
7899  *	l2arc_write_max		max write bytes per interval
7900  *	l2arc_write_boost	extra write bytes during device warmup
7901  *	l2arc_noprefetch	skip caching prefetched buffers
7902  *	l2arc_headroom		number of max device writes to precache
7903  *	l2arc_headroom_boost	when we find compressed buffers during ARC
7904  *				scanning, we multiply headroom by this
7905  *				percentage factor for the next scan cycle,
7906  *				since more compressed buffers are likely to
7907  *				be present
7908  *	l2arc_feed_secs		seconds between L2ARC writing
7909  *
7910  * Tunables may be removed or added as future performance improvements are
7911  * integrated, and also may become zpool properties.
7912  *
7913  * There are three key functions that control how the L2ARC warms up:
7914  *
7915  *	l2arc_write_eligible()	check if a buffer is eligible to cache
7916  *	l2arc_write_size()	calculate how much to write
7917  *	l2arc_write_interval()	calculate sleep delay between writes
7918  *
7919  * These three functions determine what to write, how much, and how quickly
7920  * to send writes.
7921  *
7922  * L2ARC persistence:
7923  *
7924  * When writing buffers to L2ARC, we periodically add some metadata to
7925  * make sure we can pick them up after reboot, thus dramatically reducing
7926  * the impact that any downtime has on the performance of storage systems
7927  * with large caches.
7928  *
7929  * The implementation works fairly simply by integrating the following two
7930  * modifications:
7931  *
7932  * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
7933  *    which is an additional piece of metadata which describes what's been
7934  *    written. This allows us to rebuild the arc_buf_hdr_t structures of the
7935  *    main ARC buffers. There are 2 linked-lists of log blocks headed by
7936  *    dh_start_lbps[2]. We alternate which chain we append to, so they are
7937  *    time-wise and offset-wise interleaved, but that is an optimization rather
7938  *    than for correctness. The log block also includes a pointer to the
7939  *    previous block in its chain.
7940  *
7941  * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
7942  *    for our header bookkeeping purposes. This contains a device header,
7943  *    which contains our top-level reference structures. We update it each
7944  *    time we write a new log block, so that we're able to locate it in the
7945  *    L2ARC device. If this write results in an inconsistent device header
7946  *    (e.g. due to power failure), we detect this by verifying the header's
7947  *    checksum and simply fail to reconstruct the L2ARC after reboot.
7948  *
7949  * Implementation diagram:
7950  *
7951  * +=== L2ARC device (not to scale) ======================================+
7952  * |       ___two newest log block pointers__.__________                  |
7953  * |      /                                   \dh_start_lbps[1]           |
7954  * |	 /				       \         \dh_start_lbps[0]|
7955  * |.___/__.                                    V         V               |
7956  * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
7957  * ||   hdr|      ^         /^       /^        /         /                |
7958  * |+------+  ...--\-------/  \-----/--\------/         /                 |
7959  * |                \--------------/    \--------------/                  |
7960  * +======================================================================+
7961  *
7962  * As can be seen on the diagram, rather than using a simple linked list,
7963  * we use a pair of linked lists with alternating elements. This is a
7964  * performance enhancement due to the fact that we only find out the
7965  * address of the next log block access once the current block has been
7966  * completely read in. Obviously, this hurts performance, because we'd be
7967  * keeping the device's I/O queue at only a 1 operation deep, thus
7968  * incurring a large amount of I/O round-trip latency. Having two lists
7969  * allows us to fetch two log blocks ahead of where we are currently
7970  * rebuilding L2ARC buffers.
7971  *
7972  * On-device data structures:
7973  *
7974  * L2ARC device header:	l2arc_dev_hdr_phys_t
7975  * L2ARC log block:	l2arc_log_blk_phys_t
7976  *
7977  * L2ARC reconstruction:
7978  *
7979  * When writing data, we simply write in the standard rotary fashion,
7980  * evicting buffers as we go and simply writing new data over them (writing
7981  * a new log block every now and then). This obviously means that once we
7982  * loop around the end of the device, we will start cutting into an already
7983  * committed log block (and its referenced data buffers), like so:
7984  *
7985  *    current write head__       __old tail
7986  *                        \     /
7987  *                        V    V
7988  * <--|bufs |lb |bufs |lb |    |bufs |lb |bufs |lb |-->
7989  *                         ^    ^^^^^^^^^___________________________________
7990  *                         |                                                \
7991  *                   <<nextwrite>> may overwrite this blk and/or its bufs --'
7992  *
7993  * When importing the pool, we detect this situation and use it to stop
7994  * our scanning process (see l2arc_rebuild).
7995  *
7996  * There is one significant caveat to consider when rebuilding ARC contents
7997  * from an L2ARC device: what about invalidated buffers? Given the above
7998  * construction, we cannot update blocks which we've already written to amend
7999  * them to remove buffers which were invalidated. Thus, during reconstruction,
8000  * we might be populating the cache with buffers for data that's not on the
8001  * main pool anymore, or may have been overwritten!
8002  *
8003  * As it turns out, this isn't a problem. Every arc_read request includes
8004  * both the DVA and, crucially, the birth TXG of the BP the caller is
8005  * looking for. So even if the cache were populated by completely rotten
8006  * blocks for data that had been long deleted and/or overwritten, we'll
8007  * never actually return bad data from the cache, since the DVA with the
8008  * birth TXG uniquely identify a block in space and time - once created,
8009  * a block is immutable on disk. The worst thing we have done is wasted
8010  * some time and memory at l2arc rebuild to reconstruct outdated ARC
8011  * entries that will get dropped from the l2arc as it is being updated
8012  * with new blocks.
8013  *
8014  * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
8015  * hand are not restored. This is done by saving the offset (in bytes)
8016  * l2arc_evict() has evicted to in the L2ARC device header and taking it
8017  * into account when restoring buffers.
8018  */
8019 
8020 static boolean_t
8021 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
8022 {
8023 	/*
8024 	 * A buffer is *not* eligible for the L2ARC if it:
8025 	 * 1. belongs to a different spa.
8026 	 * 2. is already cached on the L2ARC.
8027 	 * 3. has an I/O in progress (it may be an incomplete read).
8028 	 * 4. is flagged not eligible (zfs property).
8029 	 */
8030 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
8031 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
8032 		return (B_FALSE);
8033 
8034 	return (B_TRUE);
8035 }
8036 
8037 static uint64_t
8038 l2arc_write_size(l2arc_dev_t *dev)
8039 {
8040 	uint64_t size, dev_size, tsize;
8041 
8042 	/*
8043 	 * Make sure our globals have meaningful values in case the user
8044 	 * altered them.
8045 	 */
8046 	size = l2arc_write_max;
8047 	if (size == 0) {
8048 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
8049 		    "be greater than zero, resetting it to the default (%d)",
8050 		    L2ARC_WRITE_SIZE);
8051 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
8052 	}
8053 
8054 	if (arc_warm == B_FALSE)
8055 		size += l2arc_write_boost;
8056 
8057 	/*
8058 	 * Make sure the write size does not exceed the size of the cache
8059 	 * device. This is important in l2arc_evict(), otherwise infinite
8060 	 * iteration can occur.
8061 	 */
8062 	dev_size = dev->l2ad_end - dev->l2ad_start;
8063 	tsize = size + l2arc_log_blk_overhead(size, dev);
8064 	if (dev->l2ad_vdev->vdev_has_trim && l2arc_trim_ahead > 0)
8065 		tsize += MAX(64 * 1024 * 1024,
8066 		    (tsize * l2arc_trim_ahead) / 100);
8067 
8068 	if (tsize >= dev_size) {
8069 		cmn_err(CE_NOTE, "l2arc_write_max or l2arc_write_boost "
8070 		    "plus the overhead of log blocks (persistent L2ARC, "
8071 		    "%llu bytes) exceeds the size of the cache device "
8072 		    "(guid %llu), resetting them to the default (%d)",
8073 		    l2arc_log_blk_overhead(size, dev),
8074 		    dev->l2ad_vdev->vdev_guid, L2ARC_WRITE_SIZE);
8075 		size = l2arc_write_max = l2arc_write_boost = L2ARC_WRITE_SIZE;
8076 
8077 		if (arc_warm == B_FALSE)
8078 			size += l2arc_write_boost;
8079 	}
8080 
8081 	return (size);
8082 
8083 }
8084 
8085 static clock_t
8086 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
8087 {
8088 	clock_t interval, next, now;
8089 
8090 	/*
8091 	 * If the ARC lists are busy, increase our write rate; if the
8092 	 * lists are stale, idle back.  This is achieved by checking
8093 	 * how much we previously wrote - if it was more than half of
8094 	 * what we wanted, schedule the next write much sooner.
8095 	 */
8096 	if (l2arc_feed_again && wrote > (wanted / 2))
8097 		interval = (hz * l2arc_feed_min_ms) / 1000;
8098 	else
8099 		interval = hz * l2arc_feed_secs;
8100 
8101 	now = ddi_get_lbolt();
8102 	next = MAX(now, MIN(now + interval, began + interval));
8103 
8104 	return (next);
8105 }
8106 
8107 /*
8108  * Cycle through L2ARC devices.  This is how L2ARC load balances.
8109  * If a device is returned, this also returns holding the spa config lock.
8110  */
8111 static l2arc_dev_t *
8112 l2arc_dev_get_next(void)
8113 {
8114 	l2arc_dev_t *first, *next = NULL;
8115 
8116 	/*
8117 	 * Lock out the removal of spas (spa_namespace_lock), then removal
8118 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
8119 	 * both locks will be dropped and a spa config lock held instead.
8120 	 */
8121 	mutex_enter(&spa_namespace_lock);
8122 	mutex_enter(&l2arc_dev_mtx);
8123 
8124 	/* if there are no vdevs, there is nothing to do */
8125 	if (l2arc_ndev == 0)
8126 		goto out;
8127 
8128 	first = NULL;
8129 	next = l2arc_dev_last;
8130 	do {
8131 		/* loop around the list looking for a non-faulted vdev */
8132 		if (next == NULL) {
8133 			next = list_head(l2arc_dev_list);
8134 		} else {
8135 			next = list_next(l2arc_dev_list, next);
8136 			if (next == NULL)
8137 				next = list_head(l2arc_dev_list);
8138 		}
8139 
8140 		/* if we have come back to the start, bail out */
8141 		if (first == NULL)
8142 			first = next;
8143 		else if (next == first)
8144 			break;
8145 
8146 	} while (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
8147 	    next->l2ad_trim_all);
8148 
8149 	/* if we were unable to find any usable vdevs, return NULL */
8150 	if (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild ||
8151 	    next->l2ad_trim_all)
8152 		next = NULL;
8153 
8154 	l2arc_dev_last = next;
8155 
8156 out:
8157 	mutex_exit(&l2arc_dev_mtx);
8158 
8159 	/*
8160 	 * Grab the config lock to prevent the 'next' device from being
8161 	 * removed while we are writing to it.
8162 	 */
8163 	if (next != NULL)
8164 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
8165 	mutex_exit(&spa_namespace_lock);
8166 
8167 	return (next);
8168 }
8169 
8170 /*
8171  * Free buffers that were tagged for destruction.
8172  */
8173 static void
8174 l2arc_do_free_on_write(void)
8175 {
8176 	list_t *buflist;
8177 	l2arc_data_free_t *df, *df_prev;
8178 
8179 	mutex_enter(&l2arc_free_on_write_mtx);
8180 	buflist = l2arc_free_on_write;
8181 
8182 	for (df = list_tail(buflist); df; df = df_prev) {
8183 		df_prev = list_prev(buflist, df);
8184 		ASSERT3P(df->l2df_abd, !=, NULL);
8185 		abd_free(df->l2df_abd);
8186 		list_remove(buflist, df);
8187 		kmem_free(df, sizeof (l2arc_data_free_t));
8188 	}
8189 
8190 	mutex_exit(&l2arc_free_on_write_mtx);
8191 }
8192 
8193 /*
8194  * A write to a cache device has completed.  Update all headers to allow
8195  * reads from these buffers to begin.
8196  */
8197 static void
8198 l2arc_write_done(zio_t *zio)
8199 {
8200 	l2arc_write_callback_t	*cb;
8201 	l2arc_lb_abd_buf_t	*abd_buf;
8202 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
8203 	l2arc_dev_t		*dev;
8204 	l2arc_dev_hdr_phys_t	*l2dhdr;
8205 	list_t			*buflist;
8206 	arc_buf_hdr_t		*head, *hdr, *hdr_prev;
8207 	kmutex_t		*hash_lock;
8208 	int64_t			bytes_dropped = 0;
8209 
8210 	cb = zio->io_private;
8211 	ASSERT3P(cb, !=, NULL);
8212 	dev = cb->l2wcb_dev;
8213 	l2dhdr = dev->l2ad_dev_hdr;
8214 	ASSERT3P(dev, !=, NULL);
8215 	head = cb->l2wcb_head;
8216 	ASSERT3P(head, !=, NULL);
8217 	buflist = &dev->l2ad_buflist;
8218 	ASSERT3P(buflist, !=, NULL);
8219 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
8220 	    l2arc_write_callback_t *, cb);
8221 
8222 	/*
8223 	 * All writes completed, or an error was hit.
8224 	 */
8225 top:
8226 	mutex_enter(&dev->l2ad_mtx);
8227 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
8228 		hdr_prev = list_prev(buflist, hdr);
8229 
8230 		hash_lock = HDR_LOCK(hdr);
8231 
8232 		/*
8233 		 * We cannot use mutex_enter or else we can deadlock
8234 		 * with l2arc_write_buffers (due to swapping the order
8235 		 * the hash lock and l2ad_mtx are taken).
8236 		 */
8237 		if (!mutex_tryenter(hash_lock)) {
8238 			/*
8239 			 * Missed the hash lock. We must retry so we
8240 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
8241 			 */
8242 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
8243 
8244 			/*
8245 			 * We don't want to rescan the headers we've
8246 			 * already marked as having been written out, so
8247 			 * we reinsert the head node so we can pick up
8248 			 * where we left off.
8249 			 */
8250 			list_remove(buflist, head);
8251 			list_insert_after(buflist, hdr, head);
8252 
8253 			mutex_exit(&dev->l2ad_mtx);
8254 
8255 			/*
8256 			 * We wait for the hash lock to become available
8257 			 * to try and prevent busy waiting, and increase
8258 			 * the chance we'll be able to acquire the lock
8259 			 * the next time around.
8260 			 */
8261 			mutex_enter(hash_lock);
8262 			mutex_exit(hash_lock);
8263 			goto top;
8264 		}
8265 
8266 		/*
8267 		 * We could not have been moved into the arc_l2c_only
8268 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
8269 		 * bit being set. Let's just ensure that's being enforced.
8270 		 */
8271 		ASSERT(HDR_HAS_L1HDR(hdr));
8272 
8273 		/*
8274 		 * Skipped - drop L2ARC entry and mark the header as no
8275 		 * longer L2 eligibile.
8276 		 */
8277 		if (zio->io_error != 0) {
8278 			/*
8279 			 * Error - drop L2ARC entry.
8280 			 */
8281 			list_remove(buflist, hdr);
8282 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
8283 
8284 			uint64_t psize = HDR_GET_PSIZE(hdr);
8285 			l2arc_hdr_arcstats_decrement(hdr);
8286 
8287 			bytes_dropped +=
8288 			    vdev_psize_to_asize(dev->l2ad_vdev, psize);
8289 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
8290 			    arc_hdr_size(hdr), hdr);
8291 		}
8292 
8293 		/*
8294 		 * Allow ARC to begin reads and ghost list evictions to
8295 		 * this L2ARC entry.
8296 		 */
8297 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
8298 
8299 		mutex_exit(hash_lock);
8300 	}
8301 
8302 	/*
8303 	 * Free the allocated abd buffers for writing the log blocks.
8304 	 * If the zio failed reclaim the allocated space and remove the
8305 	 * pointers to these log blocks from the log block pointer list
8306 	 * of the L2ARC device.
8307 	 */
8308 	while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
8309 		abd_free(abd_buf->abd);
8310 		zio_buf_free(abd_buf, sizeof (*abd_buf));
8311 		if (zio->io_error != 0) {
8312 			lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
8313 			/*
8314 			 * L2BLK_GET_PSIZE returns aligned size for log
8315 			 * blocks.
8316 			 */
8317 			uint64_t asize =
8318 			    L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
8319 			bytes_dropped += asize;
8320 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8321 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8322 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8323 			    lb_ptr_buf);
8324 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8325 			kmem_free(lb_ptr_buf->lb_ptr,
8326 			    sizeof (l2arc_log_blkptr_t));
8327 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8328 		}
8329 	}
8330 	list_destroy(&cb->l2wcb_abd_list);
8331 
8332 	if (zio->io_error != 0) {
8333 		ARCSTAT_BUMP(arcstat_l2_writes_error);
8334 
8335 		/*
8336 		 * Restore the lbps array in the header to its previous state.
8337 		 * If the list of log block pointers is empty, zero out the
8338 		 * log block pointers in the device header.
8339 		 */
8340 		lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
8341 		for (int i = 0; i < 2; i++) {
8342 			if (lb_ptr_buf == NULL) {
8343 				/*
8344 				 * If the list is empty zero out the device
8345 				 * header. Otherwise zero out the second log
8346 				 * block pointer in the header.
8347 				 */
8348 				if (i == 0) {
8349 					bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
8350 				} else {
8351 					bzero(&l2dhdr->dh_start_lbps[i],
8352 					    sizeof (l2arc_log_blkptr_t));
8353 				}
8354 				break;
8355 			}
8356 			bcopy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[i],
8357 			    sizeof (l2arc_log_blkptr_t));
8358 			lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
8359 			    lb_ptr_buf);
8360 		}
8361 	}
8362 
8363 	atomic_inc_64(&l2arc_writes_done);
8364 	list_remove(buflist, head);
8365 	ASSERT(!HDR_HAS_L1HDR(head));
8366 	kmem_cache_free(hdr_l2only_cache, head);
8367 	mutex_exit(&dev->l2ad_mtx);
8368 
8369 	ASSERT(dev->l2ad_vdev != NULL);
8370 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
8371 
8372 	l2arc_do_free_on_write();
8373 
8374 	kmem_free(cb, sizeof (l2arc_write_callback_t));
8375 }
8376 
8377 static int
8378 l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
8379 {
8380 	int ret;
8381 	spa_t *spa = zio->io_spa;
8382 	arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
8383 	blkptr_t *bp = zio->io_bp;
8384 	uint8_t salt[ZIO_DATA_SALT_LEN];
8385 	uint8_t iv[ZIO_DATA_IV_LEN];
8386 	uint8_t mac[ZIO_DATA_MAC_LEN];
8387 	boolean_t no_crypt = B_FALSE;
8388 
8389 	/*
8390 	 * ZIL data is never be written to the L2ARC, so we don't need
8391 	 * special handling for its unique MAC storage.
8392 	 */
8393 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
8394 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
8395 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8396 
8397 	/*
8398 	 * If the data was encrypted, decrypt it now. Note that
8399 	 * we must check the bp here and not the hdr, since the
8400 	 * hdr does not have its encryption parameters updated
8401 	 * until arc_read_done().
8402 	 */
8403 	if (BP_IS_ENCRYPTED(bp)) {
8404 		abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8405 		    B_TRUE);
8406 
8407 		zio_crypt_decode_params_bp(bp, salt, iv);
8408 		zio_crypt_decode_mac_bp(bp, mac);
8409 
8410 		ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
8411 		    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
8412 		    salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
8413 		    hdr->b_l1hdr.b_pabd, &no_crypt);
8414 		if (ret != 0) {
8415 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8416 			goto error;
8417 		}
8418 
8419 		/*
8420 		 * If we actually performed decryption, replace b_pabd
8421 		 * with the decrypted data. Otherwise we can just throw
8422 		 * our decryption buffer away.
8423 		 */
8424 		if (!no_crypt) {
8425 			arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8426 			    arc_hdr_size(hdr), hdr);
8427 			hdr->b_l1hdr.b_pabd = eabd;
8428 			zio->io_abd = eabd;
8429 		} else {
8430 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
8431 		}
8432 	}
8433 
8434 	/*
8435 	 * If the L2ARC block was compressed, but ARC compression
8436 	 * is disabled we decompress the data into a new buffer and
8437 	 * replace the existing data.
8438 	 */
8439 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8440 	    !HDR_COMPRESSION_ENABLED(hdr)) {
8441 		abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
8442 		    B_TRUE);
8443 		void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
8444 
8445 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
8446 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
8447 		    HDR_GET_LSIZE(hdr), &hdr->b_complevel);
8448 		if (ret != 0) {
8449 			abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8450 			arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
8451 			goto error;
8452 		}
8453 
8454 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
8455 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
8456 		    arc_hdr_size(hdr), hdr);
8457 		hdr->b_l1hdr.b_pabd = cabd;
8458 		zio->io_abd = cabd;
8459 		zio->io_size = HDR_GET_LSIZE(hdr);
8460 	}
8461 
8462 	return (0);
8463 
8464 error:
8465 	return (ret);
8466 }
8467 
8468 
8469 /*
8470  * A read to a cache device completed.  Validate buffer contents before
8471  * handing over to the regular ARC routines.
8472  */
8473 static void
8474 l2arc_read_done(zio_t *zio)
8475 {
8476 	int tfm_error = 0;
8477 	l2arc_read_callback_t *cb = zio->io_private;
8478 	arc_buf_hdr_t *hdr;
8479 	kmutex_t *hash_lock;
8480 	boolean_t valid_cksum;
8481 	boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
8482 	    (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
8483 
8484 	ASSERT3P(zio->io_vd, !=, NULL);
8485 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
8486 
8487 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
8488 
8489 	ASSERT3P(cb, !=, NULL);
8490 	hdr = cb->l2rcb_hdr;
8491 	ASSERT3P(hdr, !=, NULL);
8492 
8493 	hash_lock = HDR_LOCK(hdr);
8494 	mutex_enter(hash_lock);
8495 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
8496 
8497 	/*
8498 	 * If the data was read into a temporary buffer,
8499 	 * move it and free the buffer.
8500 	 */
8501 	if (cb->l2rcb_abd != NULL) {
8502 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
8503 		if (zio->io_error == 0) {
8504 			if (using_rdata) {
8505 				abd_copy(hdr->b_crypt_hdr.b_rabd,
8506 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8507 			} else {
8508 				abd_copy(hdr->b_l1hdr.b_pabd,
8509 				    cb->l2rcb_abd, arc_hdr_size(hdr));
8510 			}
8511 		}
8512 
8513 		/*
8514 		 * The following must be done regardless of whether
8515 		 * there was an error:
8516 		 * - free the temporary buffer
8517 		 * - point zio to the real ARC buffer
8518 		 * - set zio size accordingly
8519 		 * These are required because zio is either re-used for
8520 		 * an I/O of the block in the case of the error
8521 		 * or the zio is passed to arc_read_done() and it
8522 		 * needs real data.
8523 		 */
8524 		abd_free(cb->l2rcb_abd);
8525 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
8526 
8527 		if (using_rdata) {
8528 			ASSERT(HDR_HAS_RABD(hdr));
8529 			zio->io_abd = zio->io_orig_abd =
8530 			    hdr->b_crypt_hdr.b_rabd;
8531 		} else {
8532 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8533 			zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8534 		}
8535 	}
8536 
8537 	ASSERT3P(zio->io_abd, !=, NULL);
8538 
8539 	/*
8540 	 * Check this survived the L2ARC journey.
8541 	 */
8542 	ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8543 	    (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8544 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
8545 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
8546 	zio->io_prop.zp_complevel = hdr->b_complevel;
8547 
8548 	valid_cksum = arc_cksum_is_equal(hdr, zio);
8549 
8550 	/*
8551 	 * b_rabd will always match the data as it exists on disk if it is
8552 	 * being used. Therefore if we are reading into b_rabd we do not
8553 	 * attempt to untransform the data.
8554 	 */
8555 	if (valid_cksum && !using_rdata)
8556 		tfm_error = l2arc_untransform(zio, cb);
8557 
8558 	if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8559 	    !HDR_L2_EVICTED(hdr)) {
8560 		mutex_exit(hash_lock);
8561 		zio->io_private = hdr;
8562 		arc_read_done(zio);
8563 	} else {
8564 		/*
8565 		 * Buffer didn't survive caching.  Increment stats and
8566 		 * reissue to the original storage device.
8567 		 */
8568 		if (zio->io_error != 0) {
8569 			ARCSTAT_BUMP(arcstat_l2_io_error);
8570 		} else {
8571 			zio->io_error = SET_ERROR(EIO);
8572 		}
8573 		if (!valid_cksum || tfm_error != 0)
8574 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8575 
8576 		/*
8577 		 * If there's no waiter, issue an async i/o to the primary
8578 		 * storage now.  If there *is* a waiter, the caller must
8579 		 * issue the i/o in a context where it's OK to block.
8580 		 */
8581 		if (zio->io_waiter == NULL) {
8582 			zio_t *pio = zio_unique_parent(zio);
8583 			void *abd = (using_rdata) ?
8584 			    hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
8585 
8586 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8587 
8588 			zio = zio_read(pio, zio->io_spa, zio->io_bp,
8589 			    abd, zio->io_size, arc_read_done,
8590 			    hdr, zio->io_priority, cb->l2rcb_flags,
8591 			    &cb->l2rcb_zb);
8592 
8593 			/*
8594 			 * Original ZIO will be freed, so we need to update
8595 			 * ARC header with the new ZIO pointer to be used
8596 			 * by zio_change_priority() in arc_read().
8597 			 */
8598 			for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
8599 			    acb != NULL; acb = acb->acb_next)
8600 				acb->acb_zio_head = zio;
8601 
8602 			mutex_exit(hash_lock);
8603 			zio_nowait(zio);
8604 		} else {
8605 			mutex_exit(hash_lock);
8606 		}
8607 	}
8608 
8609 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8610 }
8611 
8612 /*
8613  * This is the list priority from which the L2ARC will search for pages to
8614  * cache.  This is used within loops (0..3) to cycle through lists in the
8615  * desired order.  This order can have a significant effect on cache
8616  * performance.
8617  *
8618  * Currently the metadata lists are hit first, MFU then MRU, followed by
8619  * the data lists.  This function returns a locked list, and also returns
8620  * the lock pointer.
8621  */
8622 static multilist_sublist_t *
8623 l2arc_sublist_lock(int list_num)
8624 {
8625 	multilist_t *ml = NULL;
8626 	unsigned int idx;
8627 
8628 	ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
8629 
8630 	switch (list_num) {
8631 	case 0:
8632 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
8633 		break;
8634 	case 1:
8635 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
8636 		break;
8637 	case 2:
8638 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
8639 		break;
8640 	case 3:
8641 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
8642 		break;
8643 	default:
8644 		return (NULL);
8645 	}
8646 
8647 	/*
8648 	 * Return a randomly-selected sublist. This is acceptable
8649 	 * because the caller feeds only a little bit of data for each
8650 	 * call (8MB). Subsequent calls will result in different
8651 	 * sublists being selected.
8652 	 */
8653 	idx = multilist_get_random_index(ml);
8654 	return (multilist_sublist_lock(ml, idx));
8655 }
8656 
8657 /*
8658  * Calculates the maximum overhead of L2ARC metadata log blocks for a given
8659  * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
8660  * overhead in processing to make sure there is enough headroom available
8661  * when writing buffers.
8662  */
8663 static inline uint64_t
8664 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
8665 {
8666 	if (dev->l2ad_log_entries == 0) {
8667 		return (0);
8668 	} else {
8669 		uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
8670 
8671 		uint64_t log_blocks = (log_entries +
8672 		    dev->l2ad_log_entries - 1) /
8673 		    dev->l2ad_log_entries;
8674 
8675 		return (vdev_psize_to_asize(dev->l2ad_vdev,
8676 		    sizeof (l2arc_log_blk_phys_t)) * log_blocks);
8677 	}
8678 }
8679 
8680 /*
8681  * Evict buffers from the device write hand to the distance specified in
8682  * bytes. This distance may span populated buffers, it may span nothing.
8683  * This is clearing a region on the L2ARC device ready for writing.
8684  * If the 'all' boolean is set, every buffer is evicted.
8685  */
8686 static void
8687 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
8688 {
8689 	list_t *buflist;
8690 	arc_buf_hdr_t *hdr, *hdr_prev;
8691 	kmutex_t *hash_lock;
8692 	uint64_t taddr;
8693 	l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
8694 	vdev_t *vd = dev->l2ad_vdev;
8695 	boolean_t rerun;
8696 
8697 	buflist = &dev->l2ad_buflist;
8698 
8699 	/*
8700 	 * We need to add in the worst case scenario of log block overhead.
8701 	 */
8702 	distance += l2arc_log_blk_overhead(distance, dev);
8703 	if (vd->vdev_has_trim && l2arc_trim_ahead > 0) {
8704 		/*
8705 		 * Trim ahead of the write size 64MB or (l2arc_trim_ahead/100)
8706 		 * times the write size, whichever is greater.
8707 		 */
8708 		distance += MAX(64 * 1024 * 1024,
8709 		    (distance * l2arc_trim_ahead) / 100);
8710 	}
8711 
8712 top:
8713 	rerun = B_FALSE;
8714 	if (dev->l2ad_hand >= (dev->l2ad_end - distance)) {
8715 		/*
8716 		 * When there is no space to accommodate upcoming writes,
8717 		 * evict to the end. Then bump the write and evict hands
8718 		 * to the start and iterate. This iteration does not
8719 		 * happen indefinitely as we make sure in
8720 		 * l2arc_write_size() that when the write hand is reset,
8721 		 * the write size does not exceed the end of the device.
8722 		 */
8723 		rerun = B_TRUE;
8724 		taddr = dev->l2ad_end;
8725 	} else {
8726 		taddr = dev->l2ad_hand + distance;
8727 	}
8728 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
8729 	    uint64_t, taddr, boolean_t, all);
8730 
8731 	if (!all) {
8732 		/*
8733 		 * This check has to be placed after deciding whether to
8734 		 * iterate (rerun).
8735 		 */
8736 		if (dev->l2ad_first) {
8737 			/*
8738 			 * This is the first sweep through the device. There is
8739 			 * nothing to evict. We have already trimmmed the
8740 			 * whole device.
8741 			 */
8742 			goto out;
8743 		} else {
8744 			/*
8745 			 * Trim the space to be evicted.
8746 			 */
8747 			if (vd->vdev_has_trim && dev->l2ad_evict < taddr &&
8748 			    l2arc_trim_ahead > 0) {
8749 				/*
8750 				 * We have to drop the spa_config lock because
8751 				 * vdev_trim_range() will acquire it.
8752 				 * l2ad_evict already accounts for the label
8753 				 * size. To prevent vdev_trim_ranges() from
8754 				 * adding it again, we subtract it from
8755 				 * l2ad_evict.
8756 				 */
8757 				spa_config_exit(dev->l2ad_spa, SCL_L2ARC, dev);
8758 				vdev_trim_simple(vd,
8759 				    dev->l2ad_evict - VDEV_LABEL_START_SIZE,
8760 				    taddr - dev->l2ad_evict);
8761 				spa_config_enter(dev->l2ad_spa, SCL_L2ARC, dev,
8762 				    RW_READER);
8763 			}
8764 
8765 			/*
8766 			 * When rebuilding L2ARC we retrieve the evict hand
8767 			 * from the header of the device. Of note, l2arc_evict()
8768 			 * does not actually delete buffers from the cache
8769 			 * device, but trimming may do so depending on the
8770 			 * hardware implementation. Thus keeping track of the
8771 			 * evict hand is useful.
8772 			 */
8773 			dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
8774 		}
8775 	}
8776 
8777 retry:
8778 	mutex_enter(&dev->l2ad_mtx);
8779 	/*
8780 	 * We have to account for evicted log blocks. Run vdev_space_update()
8781 	 * on log blocks whose offset (in bytes) is before the evicted offset
8782 	 * (in bytes) by searching in the list of pointers to log blocks
8783 	 * present in the L2ARC device.
8784 	 */
8785 	for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
8786 	    lb_ptr_buf = lb_ptr_buf_prev) {
8787 
8788 		lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
8789 
8790 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
8791 		uint64_t asize = L2BLK_GET_PSIZE(
8792 		    (lb_ptr_buf->lb_ptr)->lbp_prop);
8793 
8794 		/*
8795 		 * We don't worry about log blocks left behind (ie
8796 		 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
8797 		 * will never write more than l2arc_evict() evicts.
8798 		 */
8799 		if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
8800 			break;
8801 		} else {
8802 			vdev_space_update(vd, -asize, 0, 0);
8803 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8804 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8805 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8806 			    lb_ptr_buf);
8807 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8808 			list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
8809 			kmem_free(lb_ptr_buf->lb_ptr,
8810 			    sizeof (l2arc_log_blkptr_t));
8811 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8812 		}
8813 	}
8814 
8815 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
8816 		hdr_prev = list_prev(buflist, hdr);
8817 
8818 		ASSERT(!HDR_EMPTY(hdr));
8819 		hash_lock = HDR_LOCK(hdr);
8820 
8821 		/*
8822 		 * We cannot use mutex_enter or else we can deadlock
8823 		 * with l2arc_write_buffers (due to swapping the order
8824 		 * the hash lock and l2ad_mtx are taken).
8825 		 */
8826 		if (!mutex_tryenter(hash_lock)) {
8827 			/*
8828 			 * Missed the hash lock.  Retry.
8829 			 */
8830 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
8831 			mutex_exit(&dev->l2ad_mtx);
8832 			mutex_enter(hash_lock);
8833 			mutex_exit(hash_lock);
8834 			goto retry;
8835 		}
8836 
8837 		/*
8838 		 * A header can't be on this list if it doesn't have L2 header.
8839 		 */
8840 		ASSERT(HDR_HAS_L2HDR(hdr));
8841 
8842 		/* Ensure this header has finished being written. */
8843 		ASSERT(!HDR_L2_WRITING(hdr));
8844 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8845 
8846 		if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
8847 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
8848 			/*
8849 			 * We've evicted to the target address,
8850 			 * or the end of the device.
8851 			 */
8852 			mutex_exit(hash_lock);
8853 			break;
8854 		}
8855 
8856 		if (!HDR_HAS_L1HDR(hdr)) {
8857 			ASSERT(!HDR_L2_READING(hdr));
8858 			/*
8859 			 * This doesn't exist in the ARC.  Destroy.
8860 			 * arc_hdr_destroy() will call list_remove()
8861 			 * and decrement arcstat_l2_lsize.
8862 			 */
8863 			arc_change_state(arc_anon, hdr, hash_lock);
8864 			arc_hdr_destroy(hdr);
8865 		} else {
8866 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
8867 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
8868 			/*
8869 			 * Invalidate issued or about to be issued
8870 			 * reads, since we may be about to write
8871 			 * over this location.
8872 			 */
8873 			if (HDR_L2_READING(hdr)) {
8874 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
8875 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
8876 			}
8877 
8878 			arc_hdr_l2hdr_destroy(hdr);
8879 		}
8880 		mutex_exit(hash_lock);
8881 	}
8882 	mutex_exit(&dev->l2ad_mtx);
8883 
8884 out:
8885 	/*
8886 	 * We need to check if we evict all buffers, otherwise we may iterate
8887 	 * unnecessarily.
8888 	 */
8889 	if (!all && rerun) {
8890 		/*
8891 		 * Bump device hand to the device start if it is approaching the
8892 		 * end. l2arc_evict() has already evicted ahead for this case.
8893 		 */
8894 		dev->l2ad_hand = dev->l2ad_start;
8895 		dev->l2ad_evict = dev->l2ad_start;
8896 		dev->l2ad_first = B_FALSE;
8897 		goto top;
8898 	}
8899 
8900 	if (!all) {
8901 		/*
8902 		 * In case of cache device removal (all) the following
8903 		 * assertions may be violated without functional consequences
8904 		 * as the device is about to be removed.
8905 		 */
8906 		ASSERT3U(dev->l2ad_hand + distance, <, dev->l2ad_end);
8907 		if (!dev->l2ad_first)
8908 			ASSERT3U(dev->l2ad_hand, <, dev->l2ad_evict);
8909 	}
8910 }
8911 
8912 /*
8913  * Handle any abd transforms that might be required for writing to the L2ARC.
8914  * If successful, this function will always return an abd with the data
8915  * transformed as it is on disk in a new abd of asize bytes.
8916  */
8917 static int
8918 l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
8919     abd_t **abd_out)
8920 {
8921 	int ret;
8922 	void *tmp = NULL;
8923 	abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
8924 	enum zio_compress compress = HDR_GET_COMPRESS(hdr);
8925 	uint64_t psize = HDR_GET_PSIZE(hdr);
8926 	uint64_t size = arc_hdr_size(hdr);
8927 	boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
8928 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
8929 	dsl_crypto_key_t *dck = NULL;
8930 	uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
8931 	boolean_t no_crypt = B_FALSE;
8932 
8933 	ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8934 	    !HDR_COMPRESSION_ENABLED(hdr)) ||
8935 	    HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
8936 	ASSERT3U(psize, <=, asize);
8937 
8938 	/*
8939 	 * If this data simply needs its own buffer, we simply allocate it
8940 	 * and copy the data. This may be done to eliminate a dependency on a
8941 	 * shared buffer or to reallocate the buffer to match asize.
8942 	 */
8943 	if (HDR_HAS_RABD(hdr) && asize != psize) {
8944 		ASSERT3U(asize, >=, psize);
8945 		to_write = abd_alloc_for_io(asize, ismd);
8946 		abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
8947 		if (psize != asize)
8948 			abd_zero_off(to_write, psize, asize - psize);
8949 		goto out;
8950 	}
8951 
8952 	if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
8953 	    !HDR_ENCRYPTED(hdr)) {
8954 		ASSERT3U(size, ==, psize);
8955 		to_write = abd_alloc_for_io(asize, ismd);
8956 		abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8957 		if (size != asize)
8958 			abd_zero_off(to_write, size, asize - size);
8959 		goto out;
8960 	}
8961 
8962 	if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
8963 		cabd = abd_alloc_for_io(asize, ismd);
8964 		tmp = abd_borrow_buf(cabd, asize);
8965 
8966 		psize = zio_compress_data(compress, to_write, tmp, size,
8967 		    hdr->b_complevel);
8968 
8969 		if (psize >= size) {
8970 			abd_return_buf(cabd, tmp, asize);
8971 			HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
8972 			to_write = cabd;
8973 			abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8974 			if (size != asize)
8975 				abd_zero_off(to_write, size, asize - size);
8976 			goto encrypt;
8977 		}
8978 		ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
8979 		if (psize < asize)
8980 			bzero((char *)tmp + psize, asize - psize);
8981 		psize = HDR_GET_PSIZE(hdr);
8982 		abd_return_buf_copy(cabd, tmp, asize);
8983 		to_write = cabd;
8984 	}
8985 
8986 encrypt:
8987 	if (HDR_ENCRYPTED(hdr)) {
8988 		eabd = abd_alloc_for_io(asize, ismd);
8989 
8990 		/*
8991 		 * If the dataset was disowned before the buffer
8992 		 * made it to this point, the key to re-encrypt
8993 		 * it won't be available. In this case we simply
8994 		 * won't write the buffer to the L2ARC.
8995 		 */
8996 		ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
8997 		    FTAG, &dck);
8998 		if (ret != 0)
8999 			goto error;
9000 
9001 		ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
9002 		    hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
9003 		    hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
9004 		    &no_crypt);
9005 		if (ret != 0)
9006 			goto error;
9007 
9008 		if (no_crypt)
9009 			abd_copy(eabd, to_write, psize);
9010 
9011 		if (psize != asize)
9012 			abd_zero_off(eabd, psize, asize - psize);
9013 
9014 		/* assert that the MAC we got here matches the one we saved */
9015 		ASSERT0(bcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
9016 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
9017 
9018 		if (to_write == cabd)
9019 			abd_free(cabd);
9020 
9021 		to_write = eabd;
9022 	}
9023 
9024 out:
9025 	ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
9026 	*abd_out = to_write;
9027 	return (0);
9028 
9029 error:
9030 	if (dck != NULL)
9031 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
9032 	if (cabd != NULL)
9033 		abd_free(cabd);
9034 	if (eabd != NULL)
9035 		abd_free(eabd);
9036 
9037 	*abd_out = NULL;
9038 	return (ret);
9039 }
9040 
9041 static void
9042 l2arc_blk_fetch_done(zio_t *zio)
9043 {
9044 	l2arc_read_callback_t *cb;
9045 
9046 	cb = zio->io_private;
9047 	if (cb->l2rcb_abd != NULL)
9048 		abd_free(cb->l2rcb_abd);
9049 	kmem_free(cb, sizeof (l2arc_read_callback_t));
9050 }
9051 
9052 /*
9053  * Find and write ARC buffers to the L2ARC device.
9054  *
9055  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
9056  * for reading until they have completed writing.
9057  * The headroom_boost is an in-out parameter used to maintain headroom boost
9058  * state between calls to this function.
9059  *
9060  * Returns the number of bytes actually written (which may be smaller than
9061  * the delta by which the device hand has changed due to alignment and the
9062  * writing of log blocks).
9063  */
9064 static uint64_t
9065 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
9066 {
9067 	arc_buf_hdr_t 		*hdr, *hdr_prev, *head;
9068 	uint64_t 		write_asize, write_psize, write_lsize, headroom;
9069 	boolean_t		full;
9070 	l2arc_write_callback_t	*cb = NULL;
9071 	zio_t 			*pio, *wzio;
9072 	uint64_t 		guid = spa_load_guid(spa);
9073 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9074 
9075 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
9076 
9077 	pio = NULL;
9078 	write_lsize = write_asize = write_psize = 0;
9079 	full = B_FALSE;
9080 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
9081 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
9082 
9083 	/*
9084 	 * Copy buffers for L2ARC writing.
9085 	 */
9086 	for (int pass = 0; pass < L2ARC_FEED_TYPES; pass++) {
9087 		/*
9088 		 * If pass == 1 or 3, we cache MRU metadata and data
9089 		 * respectively.
9090 		 */
9091 		if (l2arc_mfuonly) {
9092 			if (pass == 1 || pass == 3)
9093 				continue;
9094 		}
9095 
9096 		multilist_sublist_t *mls = l2arc_sublist_lock(pass);
9097 		uint64_t passed_sz = 0;
9098 
9099 		VERIFY3P(mls, !=, NULL);
9100 
9101 		/*
9102 		 * L2ARC fast warmup.
9103 		 *
9104 		 * Until the ARC is warm and starts to evict, read from the
9105 		 * head of the ARC lists rather than the tail.
9106 		 */
9107 		if (arc_warm == B_FALSE)
9108 			hdr = multilist_sublist_head(mls);
9109 		else
9110 			hdr = multilist_sublist_tail(mls);
9111 
9112 		headroom = target_sz * l2arc_headroom;
9113 		if (zfs_compressed_arc_enabled)
9114 			headroom = (headroom * l2arc_headroom_boost) / 100;
9115 
9116 		for (; hdr; hdr = hdr_prev) {
9117 			kmutex_t *hash_lock;
9118 			abd_t *to_write = NULL;
9119 
9120 			if (arc_warm == B_FALSE)
9121 				hdr_prev = multilist_sublist_next(mls, hdr);
9122 			else
9123 				hdr_prev = multilist_sublist_prev(mls, hdr);
9124 
9125 			hash_lock = HDR_LOCK(hdr);
9126 			if (!mutex_tryenter(hash_lock)) {
9127 				/*
9128 				 * Skip this buffer rather than waiting.
9129 				 */
9130 				continue;
9131 			}
9132 
9133 			passed_sz += HDR_GET_LSIZE(hdr);
9134 			if (l2arc_headroom != 0 && passed_sz > headroom) {
9135 				/*
9136 				 * Searched too far.
9137 				 */
9138 				mutex_exit(hash_lock);
9139 				break;
9140 			}
9141 
9142 			if (!l2arc_write_eligible(guid, hdr)) {
9143 				mutex_exit(hash_lock);
9144 				continue;
9145 			}
9146 
9147 			/*
9148 			 * We rely on the L1 portion of the header below, so
9149 			 * it's invalid for this header to have been evicted out
9150 			 * of the ghost cache, prior to being written out. The
9151 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
9152 			 */
9153 			ASSERT(HDR_HAS_L1HDR(hdr));
9154 
9155 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
9156 			ASSERT3U(arc_hdr_size(hdr), >, 0);
9157 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
9158 			    HDR_HAS_RABD(hdr));
9159 			uint64_t psize = HDR_GET_PSIZE(hdr);
9160 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
9161 			    psize);
9162 
9163 			if ((write_asize + asize) > target_sz) {
9164 				full = B_TRUE;
9165 				mutex_exit(hash_lock);
9166 				break;
9167 			}
9168 
9169 			/*
9170 			 * We rely on the L1 portion of the header below, so
9171 			 * it's invalid for this header to have been evicted out
9172 			 * of the ghost cache, prior to being written out. The
9173 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
9174 			 */
9175 			arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
9176 			ASSERT(HDR_HAS_L1HDR(hdr));
9177 
9178 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
9179 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
9180 			    HDR_HAS_RABD(hdr));
9181 			ASSERT3U(arc_hdr_size(hdr), >, 0);
9182 
9183 			/*
9184 			 * If this header has b_rabd, we can use this since it
9185 			 * must always match the data exactly as it exists on
9186 			 * disk. Otherwise, the L2ARC can normally use the
9187 			 * hdr's data, but if we're sharing data between the
9188 			 * hdr and one of its bufs, L2ARC needs its own copy of
9189 			 * the data so that the ZIO below can't race with the
9190 			 * buf consumer. To ensure that this copy will be
9191 			 * available for the lifetime of the ZIO and be cleaned
9192 			 * up afterwards, we add it to the l2arc_free_on_write
9193 			 * queue. If we need to apply any transforms to the
9194 			 * data (compression, encryption) we will also need the
9195 			 * extra buffer.
9196 			 */
9197 			if (HDR_HAS_RABD(hdr) && psize == asize) {
9198 				to_write = hdr->b_crypt_hdr.b_rabd;
9199 			} else if ((HDR_COMPRESSION_ENABLED(hdr) ||
9200 			    HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
9201 			    !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
9202 			    psize == asize) {
9203 				to_write = hdr->b_l1hdr.b_pabd;
9204 			} else {
9205 				int ret;
9206 				arc_buf_contents_t type = arc_buf_type(hdr);
9207 
9208 				ret = l2arc_apply_transforms(spa, hdr, asize,
9209 				    &to_write);
9210 				if (ret != 0) {
9211 					arc_hdr_clear_flags(hdr,
9212 					    ARC_FLAG_L2_WRITING);
9213 					mutex_exit(hash_lock);
9214 					continue;
9215 				}
9216 
9217 				l2arc_free_abd_on_write(to_write, asize, type);
9218 			}
9219 
9220 			if (pio == NULL) {
9221 				/*
9222 				 * Insert a dummy header on the buflist so
9223 				 * l2arc_write_done() can find where the
9224 				 * write buffers begin without searching.
9225 				 */
9226 				mutex_enter(&dev->l2ad_mtx);
9227 				list_insert_head(&dev->l2ad_buflist, head);
9228 				mutex_exit(&dev->l2ad_mtx);
9229 
9230 				cb = kmem_alloc(
9231 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
9232 				cb->l2wcb_dev = dev;
9233 				cb->l2wcb_head = head;
9234 				/*
9235 				 * Create a list to save allocated abd buffers
9236 				 * for l2arc_log_blk_commit().
9237 				 */
9238 				list_create(&cb->l2wcb_abd_list,
9239 				    sizeof (l2arc_lb_abd_buf_t),
9240 				    offsetof(l2arc_lb_abd_buf_t, node));
9241 				pio = zio_root(spa, l2arc_write_done, cb,
9242 				    ZIO_FLAG_CANFAIL);
9243 			}
9244 
9245 			hdr->b_l2hdr.b_dev = dev;
9246 			hdr->b_l2hdr.b_hits = 0;
9247 
9248 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
9249 			hdr->b_l2hdr.b_arcs_state =
9250 			    hdr->b_l1hdr.b_state->arcs_state;
9251 			arc_hdr_set_flags(hdr, ARC_FLAG_HAS_L2HDR);
9252 
9253 			mutex_enter(&dev->l2ad_mtx);
9254 			list_insert_head(&dev->l2ad_buflist, hdr);
9255 			mutex_exit(&dev->l2ad_mtx);
9256 
9257 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
9258 			    arc_hdr_size(hdr), hdr);
9259 
9260 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
9261 			    hdr->b_l2hdr.b_daddr, asize, to_write,
9262 			    ZIO_CHECKSUM_OFF, NULL, hdr,
9263 			    ZIO_PRIORITY_ASYNC_WRITE,
9264 			    ZIO_FLAG_CANFAIL, B_FALSE);
9265 
9266 			write_lsize += HDR_GET_LSIZE(hdr);
9267 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
9268 			    zio_t *, wzio);
9269 
9270 			write_psize += psize;
9271 			write_asize += asize;
9272 			dev->l2ad_hand += asize;
9273 			l2arc_hdr_arcstats_increment(hdr);
9274 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9275 
9276 			mutex_exit(hash_lock);
9277 
9278 			/*
9279 			 * Append buf info to current log and commit if full.
9280 			 * arcstat_l2_{size,asize} kstats are updated
9281 			 * internally.
9282 			 */
9283 			if (l2arc_log_blk_insert(dev, hdr))
9284 				l2arc_log_blk_commit(dev, pio, cb);
9285 
9286 			zio_nowait(wzio);
9287 		}
9288 
9289 		multilist_sublist_unlock(mls);
9290 
9291 		if (full == B_TRUE)
9292 			break;
9293 	}
9294 
9295 	/* No buffers selected for writing? */
9296 	if (pio == NULL) {
9297 		ASSERT0(write_lsize);
9298 		ASSERT(!HDR_HAS_L1HDR(head));
9299 		kmem_cache_free(hdr_l2only_cache, head);
9300 
9301 		/*
9302 		 * Although we did not write any buffers l2ad_evict may
9303 		 * have advanced.
9304 		 */
9305 		if (dev->l2ad_evict != l2dhdr->dh_evict)
9306 			l2arc_dev_hdr_update(dev);
9307 
9308 		return (0);
9309 	}
9310 
9311 	if (!dev->l2ad_first)
9312 		ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
9313 
9314 	ASSERT3U(write_asize, <=, target_sz);
9315 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
9316 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
9317 
9318 	dev->l2ad_writing = B_TRUE;
9319 	(void) zio_wait(pio);
9320 	dev->l2ad_writing = B_FALSE;
9321 
9322 	/*
9323 	 * Update the device header after the zio completes as
9324 	 * l2arc_write_done() may have updated the memory holding the log block
9325 	 * pointers in the device header.
9326 	 */
9327 	l2arc_dev_hdr_update(dev);
9328 
9329 	return (write_asize);
9330 }
9331 
9332 static boolean_t
9333 l2arc_hdr_limit_reached(void)
9334 {
9335 	int64_t s = aggsum_upper_bound(&astat_l2_hdr_size);
9336 
9337 	return (arc_reclaim_needed() || (s > arc_meta_limit * 3 / 4) ||
9338 	    (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
9339 }
9340 
9341 /*
9342  * This thread feeds the L2ARC at regular intervals.  This is the beating
9343  * heart of the L2ARC.
9344  */
9345 /* ARGSUSED */
9346 static void
9347 l2arc_feed_thread(void *unused)
9348 {
9349 	callb_cpr_t cpr;
9350 	l2arc_dev_t *dev;
9351 	spa_t *spa;
9352 	uint64_t size, wrote;
9353 	clock_t begin, next = ddi_get_lbolt();
9354 	fstrans_cookie_t cookie;
9355 
9356 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
9357 
9358 	mutex_enter(&l2arc_feed_thr_lock);
9359 
9360 	cookie = spl_fstrans_mark();
9361 	while (l2arc_thread_exit == 0) {
9362 		CALLB_CPR_SAFE_BEGIN(&cpr);
9363 		(void) cv_timedwait_idle(&l2arc_feed_thr_cv,
9364 		    &l2arc_feed_thr_lock, next);
9365 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
9366 		next = ddi_get_lbolt() + hz;
9367 
9368 		/*
9369 		 * Quick check for L2ARC devices.
9370 		 */
9371 		mutex_enter(&l2arc_dev_mtx);
9372 		if (l2arc_ndev == 0) {
9373 			mutex_exit(&l2arc_dev_mtx);
9374 			continue;
9375 		}
9376 		mutex_exit(&l2arc_dev_mtx);
9377 		begin = ddi_get_lbolt();
9378 
9379 		/*
9380 		 * This selects the next l2arc device to write to, and in
9381 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
9382 		 * will return NULL if there are now no l2arc devices or if
9383 		 * they are all faulted.
9384 		 *
9385 		 * If a device is returned, its spa's config lock is also
9386 		 * held to prevent device removal.  l2arc_dev_get_next()
9387 		 * will grab and release l2arc_dev_mtx.
9388 		 */
9389 		if ((dev = l2arc_dev_get_next()) == NULL)
9390 			continue;
9391 
9392 		spa = dev->l2ad_spa;
9393 		ASSERT3P(spa, !=, NULL);
9394 
9395 		/*
9396 		 * If the pool is read-only then force the feed thread to
9397 		 * sleep a little longer.
9398 		 */
9399 		if (!spa_writeable(spa)) {
9400 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
9401 			spa_config_exit(spa, SCL_L2ARC, dev);
9402 			continue;
9403 		}
9404 
9405 		/*
9406 		 * Avoid contributing to memory pressure.
9407 		 */
9408 		if (l2arc_hdr_limit_reached()) {
9409 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
9410 			spa_config_exit(spa, SCL_L2ARC, dev);
9411 			continue;
9412 		}
9413 
9414 		ARCSTAT_BUMP(arcstat_l2_feeds);
9415 
9416 		size = l2arc_write_size(dev);
9417 
9418 		/*
9419 		 * Evict L2ARC buffers that will be overwritten.
9420 		 */
9421 		l2arc_evict(dev, size, B_FALSE);
9422 
9423 		/*
9424 		 * Write ARC buffers.
9425 		 */
9426 		wrote = l2arc_write_buffers(spa, dev, size);
9427 
9428 		/*
9429 		 * Calculate interval between writes.
9430 		 */
9431 		next = l2arc_write_interval(begin, size, wrote);
9432 		spa_config_exit(spa, SCL_L2ARC, dev);
9433 	}
9434 	spl_fstrans_unmark(cookie);
9435 
9436 	l2arc_thread_exit = 0;
9437 	cv_broadcast(&l2arc_feed_thr_cv);
9438 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
9439 	thread_exit();
9440 }
9441 
9442 boolean_t
9443 l2arc_vdev_present(vdev_t *vd)
9444 {
9445 	return (l2arc_vdev_get(vd) != NULL);
9446 }
9447 
9448 /*
9449  * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
9450  * the vdev_t isn't an L2ARC device.
9451  */
9452 l2arc_dev_t *
9453 l2arc_vdev_get(vdev_t *vd)
9454 {
9455 	l2arc_dev_t	*dev;
9456 
9457 	mutex_enter(&l2arc_dev_mtx);
9458 	for (dev = list_head(l2arc_dev_list); dev != NULL;
9459 	    dev = list_next(l2arc_dev_list, dev)) {
9460 		if (dev->l2ad_vdev == vd)
9461 			break;
9462 	}
9463 	mutex_exit(&l2arc_dev_mtx);
9464 
9465 	return (dev);
9466 }
9467 
9468 /*
9469  * Add a vdev for use by the L2ARC.  By this point the spa has already
9470  * validated the vdev and opened it.
9471  */
9472 void
9473 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
9474 {
9475 	l2arc_dev_t		*adddev;
9476 	uint64_t		l2dhdr_asize;
9477 
9478 	ASSERT(!l2arc_vdev_present(vd));
9479 
9480 	/*
9481 	 * Create a new l2arc device entry.
9482 	 */
9483 	adddev = vmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
9484 	adddev->l2ad_spa = spa;
9485 	adddev->l2ad_vdev = vd;
9486 	/* leave extra size for an l2arc device header */
9487 	l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
9488 	    MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
9489 	adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
9490 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
9491 	ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
9492 	adddev->l2ad_hand = adddev->l2ad_start;
9493 	adddev->l2ad_evict = adddev->l2ad_start;
9494 	adddev->l2ad_first = B_TRUE;
9495 	adddev->l2ad_writing = B_FALSE;
9496 	adddev->l2ad_trim_all = B_FALSE;
9497 	list_link_init(&adddev->l2ad_node);
9498 	adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
9499 
9500 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
9501 	/*
9502 	 * This is a list of all ARC buffers that are still valid on the
9503 	 * device.
9504 	 */
9505 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
9506 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
9507 
9508 	/*
9509 	 * This is a list of pointers to log blocks that are still present
9510 	 * on the device.
9511 	 */
9512 	list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
9513 	    offsetof(l2arc_lb_ptr_buf_t, node));
9514 
9515 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
9516 	zfs_refcount_create(&adddev->l2ad_alloc);
9517 	zfs_refcount_create(&adddev->l2ad_lb_asize);
9518 	zfs_refcount_create(&adddev->l2ad_lb_count);
9519 
9520 	/*
9521 	 * Add device to global list
9522 	 */
9523 	mutex_enter(&l2arc_dev_mtx);
9524 	list_insert_head(l2arc_dev_list, adddev);
9525 	atomic_inc_64(&l2arc_ndev);
9526 	mutex_exit(&l2arc_dev_mtx);
9527 
9528 	/*
9529 	 * Decide if vdev is eligible for L2ARC rebuild
9530 	 */
9531 	l2arc_rebuild_vdev(adddev->l2ad_vdev, B_FALSE);
9532 }
9533 
9534 void
9535 l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
9536 {
9537 	l2arc_dev_t		*dev = NULL;
9538 	l2arc_dev_hdr_phys_t	*l2dhdr;
9539 	uint64_t		l2dhdr_asize;
9540 	spa_t			*spa;
9541 
9542 	dev = l2arc_vdev_get(vd);
9543 	ASSERT3P(dev, !=, NULL);
9544 	spa = dev->l2ad_spa;
9545 	l2dhdr = dev->l2ad_dev_hdr;
9546 	l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9547 
9548 	/*
9549 	 * The L2ARC has to hold at least the payload of one log block for
9550 	 * them to be restored (persistent L2ARC). The payload of a log block
9551 	 * depends on the amount of its log entries. We always write log blocks
9552 	 * with 1022 entries. How many of them are committed or restored depends
9553 	 * on the size of the L2ARC device. Thus the maximum payload of
9554 	 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
9555 	 * is less than that, we reduce the amount of committed and restored
9556 	 * log entries per block so as to enable persistence.
9557 	 */
9558 	if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
9559 		dev->l2ad_log_entries = 0;
9560 	} else {
9561 		dev->l2ad_log_entries = MIN((dev->l2ad_end -
9562 		    dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
9563 		    L2ARC_LOG_BLK_MAX_ENTRIES);
9564 	}
9565 
9566 	/*
9567 	 * Read the device header, if an error is returned do not rebuild L2ARC.
9568 	 */
9569 	if (l2arc_dev_hdr_read(dev) == 0 && dev->l2ad_log_entries > 0) {
9570 		/*
9571 		 * If we are onlining a cache device (vdev_reopen) that was
9572 		 * still present (l2arc_vdev_present()) and rebuild is enabled,
9573 		 * we should evict all ARC buffers and pointers to log blocks
9574 		 * and reclaim their space before restoring its contents to
9575 		 * L2ARC.
9576 		 */
9577 		if (reopen) {
9578 			if (!l2arc_rebuild_enabled) {
9579 				return;
9580 			} else {
9581 				l2arc_evict(dev, 0, B_TRUE);
9582 				/* start a new log block */
9583 				dev->l2ad_log_ent_idx = 0;
9584 				dev->l2ad_log_blk_payload_asize = 0;
9585 				dev->l2ad_log_blk_payload_start = 0;
9586 			}
9587 		}
9588 		/*
9589 		 * Just mark the device as pending for a rebuild. We won't
9590 		 * be starting a rebuild in line here as it would block pool
9591 		 * import. Instead spa_load_impl will hand that off to an
9592 		 * async task which will call l2arc_spa_rebuild_start.
9593 		 */
9594 		dev->l2ad_rebuild = B_TRUE;
9595 	} else if (spa_writeable(spa)) {
9596 		/*
9597 		 * In this case TRIM the whole device if l2arc_trim_ahead > 0,
9598 		 * otherwise create a new header. We zero out the memory holding
9599 		 * the header to reset dh_start_lbps. If we TRIM the whole
9600 		 * device the new header will be written by
9601 		 * vdev_trim_l2arc_thread() at the end of the TRIM to update the
9602 		 * trim_state in the header too. When reading the header, if
9603 		 * trim_state is not VDEV_TRIM_COMPLETE and l2arc_trim_ahead > 0
9604 		 * we opt to TRIM the whole device again.
9605 		 */
9606 		if (l2arc_trim_ahead > 0) {
9607 			dev->l2ad_trim_all = B_TRUE;
9608 		} else {
9609 			bzero(l2dhdr, l2dhdr_asize);
9610 			l2arc_dev_hdr_update(dev);
9611 		}
9612 	}
9613 }
9614 
9615 /*
9616  * Remove a vdev from the L2ARC.
9617  */
9618 void
9619 l2arc_remove_vdev(vdev_t *vd)
9620 {
9621 	l2arc_dev_t *remdev = NULL;
9622 
9623 	/*
9624 	 * Find the device by vdev
9625 	 */
9626 	remdev = l2arc_vdev_get(vd);
9627 	ASSERT3P(remdev, !=, NULL);
9628 
9629 	/*
9630 	 * Cancel any ongoing or scheduled rebuild.
9631 	 */
9632 	mutex_enter(&l2arc_rebuild_thr_lock);
9633 	if (remdev->l2ad_rebuild_began == B_TRUE) {
9634 		remdev->l2ad_rebuild_cancel = B_TRUE;
9635 		while (remdev->l2ad_rebuild == B_TRUE)
9636 			cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
9637 	}
9638 	mutex_exit(&l2arc_rebuild_thr_lock);
9639 
9640 	/*
9641 	 * Remove device from global list
9642 	 */
9643 	mutex_enter(&l2arc_dev_mtx);
9644 	list_remove(l2arc_dev_list, remdev);
9645 	l2arc_dev_last = NULL;		/* may have been invalidated */
9646 	atomic_dec_64(&l2arc_ndev);
9647 	mutex_exit(&l2arc_dev_mtx);
9648 
9649 	/*
9650 	 * Clear all buflists and ARC references.  L2ARC device flush.
9651 	 */
9652 	l2arc_evict(remdev, 0, B_TRUE);
9653 	list_destroy(&remdev->l2ad_buflist);
9654 	ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
9655 	list_destroy(&remdev->l2ad_lbptr_list);
9656 	mutex_destroy(&remdev->l2ad_mtx);
9657 	zfs_refcount_destroy(&remdev->l2ad_alloc);
9658 	zfs_refcount_destroy(&remdev->l2ad_lb_asize);
9659 	zfs_refcount_destroy(&remdev->l2ad_lb_count);
9660 	kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
9661 	vmem_free(remdev, sizeof (l2arc_dev_t));
9662 }
9663 
9664 void
9665 l2arc_init(void)
9666 {
9667 	l2arc_thread_exit = 0;
9668 	l2arc_ndev = 0;
9669 	l2arc_writes_sent = 0;
9670 	l2arc_writes_done = 0;
9671 
9672 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9673 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
9674 	mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9675 	cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
9676 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
9677 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
9678 
9679 	l2arc_dev_list = &L2ARC_dev_list;
9680 	l2arc_free_on_write = &L2ARC_free_on_write;
9681 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
9682 	    offsetof(l2arc_dev_t, l2ad_node));
9683 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
9684 	    offsetof(l2arc_data_free_t, l2df_list_node));
9685 }
9686 
9687 void
9688 l2arc_fini(void)
9689 {
9690 	mutex_destroy(&l2arc_feed_thr_lock);
9691 	cv_destroy(&l2arc_feed_thr_cv);
9692 	mutex_destroy(&l2arc_rebuild_thr_lock);
9693 	cv_destroy(&l2arc_rebuild_thr_cv);
9694 	mutex_destroy(&l2arc_dev_mtx);
9695 	mutex_destroy(&l2arc_free_on_write_mtx);
9696 
9697 	list_destroy(l2arc_dev_list);
9698 	list_destroy(l2arc_free_on_write);
9699 }
9700 
9701 void
9702 l2arc_start(void)
9703 {
9704 	if (!(spa_mode_global & SPA_MODE_WRITE))
9705 		return;
9706 
9707 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
9708 	    TS_RUN, defclsyspri);
9709 }
9710 
9711 void
9712 l2arc_stop(void)
9713 {
9714 	if (!(spa_mode_global & SPA_MODE_WRITE))
9715 		return;
9716 
9717 	mutex_enter(&l2arc_feed_thr_lock);
9718 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
9719 	l2arc_thread_exit = 1;
9720 	while (l2arc_thread_exit != 0)
9721 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
9722 	mutex_exit(&l2arc_feed_thr_lock);
9723 }
9724 
9725 /*
9726  * Punches out rebuild threads for the L2ARC devices in a spa. This should
9727  * be called after pool import from the spa async thread, since starting
9728  * these threads directly from spa_import() will make them part of the
9729  * "zpool import" context and delay process exit (and thus pool import).
9730  */
9731 void
9732 l2arc_spa_rebuild_start(spa_t *spa)
9733 {
9734 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
9735 
9736 	/*
9737 	 * Locate the spa's l2arc devices and kick off rebuild threads.
9738 	 */
9739 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
9740 		l2arc_dev_t *dev =
9741 		    l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
9742 		if (dev == NULL) {
9743 			/* Don't attempt a rebuild if the vdev is UNAVAIL */
9744 			continue;
9745 		}
9746 		mutex_enter(&l2arc_rebuild_thr_lock);
9747 		if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
9748 			dev->l2ad_rebuild_began = B_TRUE;
9749 			(void) thread_create(NULL, 0, l2arc_dev_rebuild_thread,
9750 			    dev, 0, &p0, TS_RUN, minclsyspri);
9751 		}
9752 		mutex_exit(&l2arc_rebuild_thr_lock);
9753 	}
9754 }
9755 
9756 /*
9757  * Main entry point for L2ARC rebuilding.
9758  */
9759 static void
9760 l2arc_dev_rebuild_thread(void *arg)
9761 {
9762 	l2arc_dev_t *dev = arg;
9763 
9764 	VERIFY(!dev->l2ad_rebuild_cancel);
9765 	VERIFY(dev->l2ad_rebuild);
9766 	(void) l2arc_rebuild(dev);
9767 	mutex_enter(&l2arc_rebuild_thr_lock);
9768 	dev->l2ad_rebuild_began = B_FALSE;
9769 	dev->l2ad_rebuild = B_FALSE;
9770 	mutex_exit(&l2arc_rebuild_thr_lock);
9771 
9772 	thread_exit();
9773 }
9774 
9775 /*
9776  * This function implements the actual L2ARC metadata rebuild. It:
9777  * starts reading the log block chain and restores each block's contents
9778  * to memory (reconstructing arc_buf_hdr_t's).
9779  *
9780  * Operation stops under any of the following conditions:
9781  *
9782  * 1) We reach the end of the log block chain.
9783  * 2) We encounter *any* error condition (cksum errors, io errors)
9784  */
9785 static int
9786 l2arc_rebuild(l2arc_dev_t *dev)
9787 {
9788 	vdev_t			*vd = dev->l2ad_vdev;
9789 	spa_t			*spa = vd->vdev_spa;
9790 	int			err = 0;
9791 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9792 	l2arc_log_blk_phys_t	*this_lb, *next_lb;
9793 	zio_t			*this_io = NULL, *next_io = NULL;
9794 	l2arc_log_blkptr_t	lbps[2];
9795 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
9796 	boolean_t		lock_held;
9797 
9798 	this_lb = vmem_zalloc(sizeof (*this_lb), KM_SLEEP);
9799 	next_lb = vmem_zalloc(sizeof (*next_lb), KM_SLEEP);
9800 
9801 	/*
9802 	 * We prevent device removal while issuing reads to the device,
9803 	 * then during the rebuilding phases we drop this lock again so
9804 	 * that a spa_unload or device remove can be initiated - this is
9805 	 * safe, because the spa will signal us to stop before removing
9806 	 * our device and wait for us to stop.
9807 	 */
9808 	spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
9809 	lock_held = B_TRUE;
9810 
9811 	/*
9812 	 * Retrieve the persistent L2ARC device state.
9813 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9814 	 */
9815 	dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
9816 	dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
9817 	    L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
9818 	    dev->l2ad_start);
9819 	dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
9820 
9821 	vd->vdev_trim_action_time = l2dhdr->dh_trim_action_time;
9822 	vd->vdev_trim_state = l2dhdr->dh_trim_state;
9823 
9824 	/*
9825 	 * In case the zfs module parameter l2arc_rebuild_enabled is false
9826 	 * we do not start the rebuild process.
9827 	 */
9828 	if (!l2arc_rebuild_enabled)
9829 		goto out;
9830 
9831 	/* Prepare the rebuild process */
9832 	bcopy(l2dhdr->dh_start_lbps, lbps, sizeof (lbps));
9833 
9834 	/* Start the rebuild process */
9835 	for (;;) {
9836 		if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
9837 			break;
9838 
9839 		if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
9840 		    this_lb, next_lb, this_io, &next_io)) != 0)
9841 			goto out;
9842 
9843 		/*
9844 		 * Our memory pressure valve. If the system is running low
9845 		 * on memory, rather than swamping memory with new ARC buf
9846 		 * hdrs, we opt not to rebuild the L2ARC. At this point,
9847 		 * however, we have already set up our L2ARC dev to chain in
9848 		 * new metadata log blocks, so the user may choose to offline/
9849 		 * online the L2ARC dev at a later time (or re-import the pool)
9850 		 * to reconstruct it (when there's less memory pressure).
9851 		 */
9852 		if (l2arc_hdr_limit_reached()) {
9853 			ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
9854 			cmn_err(CE_NOTE, "System running low on memory, "
9855 			    "aborting L2ARC rebuild.");
9856 			err = SET_ERROR(ENOMEM);
9857 			goto out;
9858 		}
9859 
9860 		spa_config_exit(spa, SCL_L2ARC, vd);
9861 		lock_held = B_FALSE;
9862 
9863 		/*
9864 		 * Now that we know that the next_lb checks out alright, we
9865 		 * can start reconstruction from this log block.
9866 		 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9867 		 */
9868 		uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
9869 		l2arc_log_blk_restore(dev, this_lb, asize);
9870 
9871 		/*
9872 		 * log block restored, include its pointer in the list of
9873 		 * pointers to log blocks present in the L2ARC device.
9874 		 */
9875 		lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
9876 		lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
9877 		    KM_SLEEP);
9878 		bcopy(&lbps[0], lb_ptr_buf->lb_ptr,
9879 		    sizeof (l2arc_log_blkptr_t));
9880 		mutex_enter(&dev->l2ad_mtx);
9881 		list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
9882 		ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
9883 		ARCSTAT_BUMP(arcstat_l2_log_blk_count);
9884 		zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
9885 		zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
9886 		mutex_exit(&dev->l2ad_mtx);
9887 		vdev_space_update(vd, asize, 0, 0);
9888 
9889 		/*
9890 		 * Protection against loops of log blocks:
9891 		 *
9892 		 *				       l2ad_hand  l2ad_evict
9893 		 *                                         V	      V
9894 		 * l2ad_start |=======================================| l2ad_end
9895 		 *             -----|||----|||---|||----|||
9896 		 *                  (3)    (2)   (1)    (0)
9897 		 *             ---|||---|||----|||---|||
9898 		 *		  (7)   (6)    (5)   (4)
9899 		 *
9900 		 * In this situation the pointer of log block (4) passes
9901 		 * l2arc_log_blkptr_valid() but the log block should not be
9902 		 * restored as it is overwritten by the payload of log block
9903 		 * (0). Only log blocks (0)-(3) should be restored. We check
9904 		 * whether l2ad_evict lies in between the payload starting
9905 		 * offset of the next log block (lbps[1].lbp_payload_start)
9906 		 * and the payload starting offset of the present log block
9907 		 * (lbps[0].lbp_payload_start). If true and this isn't the
9908 		 * first pass, we are looping from the beginning and we should
9909 		 * stop.
9910 		 */
9911 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
9912 		    lbps[0].lbp_payload_start, dev->l2ad_evict) &&
9913 		    !dev->l2ad_first)
9914 			goto out;
9915 
9916 		cond_resched();
9917 		for (;;) {
9918 			mutex_enter(&l2arc_rebuild_thr_lock);
9919 			if (dev->l2ad_rebuild_cancel) {
9920 				dev->l2ad_rebuild = B_FALSE;
9921 				cv_signal(&l2arc_rebuild_thr_cv);
9922 				mutex_exit(&l2arc_rebuild_thr_lock);
9923 				err = SET_ERROR(ECANCELED);
9924 				goto out;
9925 			}
9926 			mutex_exit(&l2arc_rebuild_thr_lock);
9927 			if (spa_config_tryenter(spa, SCL_L2ARC, vd,
9928 			    RW_READER)) {
9929 				lock_held = B_TRUE;
9930 				break;
9931 			}
9932 			/*
9933 			 * L2ARC config lock held by somebody in writer,
9934 			 * possibly due to them trying to remove us. They'll
9935 			 * likely to want us to shut down, so after a little
9936 			 * delay, we check l2ad_rebuild_cancel and retry
9937 			 * the lock again.
9938 			 */
9939 			delay(1);
9940 		}
9941 
9942 		/*
9943 		 * Continue with the next log block.
9944 		 */
9945 		lbps[0] = lbps[1];
9946 		lbps[1] = this_lb->lb_prev_lbp;
9947 		PTR_SWAP(this_lb, next_lb);
9948 		this_io = next_io;
9949 		next_io = NULL;
9950 	}
9951 
9952 	if (this_io != NULL)
9953 		l2arc_log_blk_fetch_abort(this_io);
9954 out:
9955 	if (next_io != NULL)
9956 		l2arc_log_blk_fetch_abort(next_io);
9957 	vmem_free(this_lb, sizeof (*this_lb));
9958 	vmem_free(next_lb, sizeof (*next_lb));
9959 
9960 	if (!l2arc_rebuild_enabled) {
9961 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9962 		    "disabled");
9963 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
9964 		ARCSTAT_BUMP(arcstat_l2_rebuild_success);
9965 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9966 		    "successful, restored %llu blocks",
9967 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9968 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
9969 		/*
9970 		 * No error but also nothing restored, meaning the lbps array
9971 		 * in the device header points to invalid/non-present log
9972 		 * blocks. Reset the header.
9973 		 */
9974 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9975 		    "no valid log blocks");
9976 		bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
9977 		l2arc_dev_hdr_update(dev);
9978 	} else if (err == ECANCELED) {
9979 		/*
9980 		 * In case the rebuild was canceled do not log to spa history
9981 		 * log as the pool may be in the process of being removed.
9982 		 */
9983 		zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
9984 		    zfs_refcount_count(&dev->l2ad_lb_count));
9985 	} else if (err != 0) {
9986 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9987 		    "aborted, restored %llu blocks",
9988 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9989 	}
9990 
9991 	if (lock_held)
9992 		spa_config_exit(spa, SCL_L2ARC, vd);
9993 
9994 	return (err);
9995 }
9996 
9997 /*
9998  * Attempts to read the device header on the provided L2ARC device and writes
9999  * it to `hdr'. On success, this function returns 0, otherwise the appropriate
10000  * error code is returned.
10001  */
10002 static int
10003 l2arc_dev_hdr_read(l2arc_dev_t *dev)
10004 {
10005 	int			err;
10006 	uint64_t		guid;
10007 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10008 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10009 	abd_t 			*abd;
10010 
10011 	guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10012 
10013 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10014 
10015 	err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
10016 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
10017 	    ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
10018 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10019 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
10020 	    ZIO_FLAG_SPECULATIVE, B_FALSE));
10021 
10022 	abd_free(abd);
10023 
10024 	if (err != 0) {
10025 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
10026 		zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
10027 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
10028 		return (err);
10029 	}
10030 
10031 	if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
10032 		byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
10033 
10034 	if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
10035 	    l2dhdr->dh_spa_guid != guid ||
10036 	    l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
10037 	    l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
10038 	    l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
10039 	    l2dhdr->dh_end != dev->l2ad_end ||
10040 	    !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
10041 	    l2dhdr->dh_evict) ||
10042 	    (l2dhdr->dh_trim_state != VDEV_TRIM_COMPLETE &&
10043 	    l2arc_trim_ahead > 0)) {
10044 		/*
10045 		 * Attempt to rebuild a device containing no actual dev hdr
10046 		 * or containing a header from some other pool or from another
10047 		 * version of persistent L2ARC.
10048 		 */
10049 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
10050 		return (SET_ERROR(ENOTSUP));
10051 	}
10052 
10053 	return (0);
10054 }
10055 
10056 /*
10057  * Reads L2ARC log blocks from storage and validates their contents.
10058  *
10059  * This function implements a simple fetcher to make sure that while
10060  * we're processing one buffer the L2ARC is already fetching the next
10061  * one in the chain.
10062  *
10063  * The arguments this_lp and next_lp point to the current and next log block
10064  * address in the block chain. Similarly, this_lb and next_lb hold the
10065  * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
10066  *
10067  * The `this_io' and `next_io' arguments are used for block fetching.
10068  * When issuing the first blk IO during rebuild, you should pass NULL for
10069  * `this_io'. This function will then issue a sync IO to read the block and
10070  * also issue an async IO to fetch the next block in the block chain. The
10071  * fetched IO is returned in `next_io'. On subsequent calls to this
10072  * function, pass the value returned in `next_io' from the previous call
10073  * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
10074  * Prior to the call, you should initialize your `next_io' pointer to be
10075  * NULL. If no fetch IO was issued, the pointer is left set at NULL.
10076  *
10077  * On success, this function returns 0, otherwise it returns an appropriate
10078  * error code. On error the fetching IO is aborted and cleared before
10079  * returning from this function. Therefore, if we return `success', the
10080  * caller can assume that we have taken care of cleanup of fetch IOs.
10081  */
10082 static int
10083 l2arc_log_blk_read(l2arc_dev_t *dev,
10084     const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
10085     l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
10086     zio_t *this_io, zio_t **next_io)
10087 {
10088 	int		err = 0;
10089 	zio_cksum_t	cksum;
10090 	abd_t		*abd = NULL;
10091 	uint64_t	asize;
10092 
10093 	ASSERT(this_lbp != NULL && next_lbp != NULL);
10094 	ASSERT(this_lb != NULL && next_lb != NULL);
10095 	ASSERT(next_io != NULL && *next_io == NULL);
10096 	ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
10097 
10098 	/*
10099 	 * Check to see if we have issued the IO for this log block in a
10100 	 * previous run. If not, this is the first call, so issue it now.
10101 	 */
10102 	if (this_io == NULL) {
10103 		this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
10104 		    this_lb);
10105 	}
10106 
10107 	/*
10108 	 * Peek to see if we can start issuing the next IO immediately.
10109 	 */
10110 	if (l2arc_log_blkptr_valid(dev, next_lbp)) {
10111 		/*
10112 		 * Start issuing IO for the next log block early - this
10113 		 * should help keep the L2ARC device busy while we
10114 		 * decompress and restore this log block.
10115 		 */
10116 		*next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
10117 		    next_lb);
10118 	}
10119 
10120 	/* Wait for the IO to read this log block to complete */
10121 	if ((err = zio_wait(this_io)) != 0) {
10122 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
10123 		zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
10124 		    "offset: %llu, vdev guid: %llu", err, this_lbp->lbp_daddr,
10125 		    dev->l2ad_vdev->vdev_guid);
10126 		goto cleanup;
10127 	}
10128 
10129 	/*
10130 	 * Make sure the buffer checks out.
10131 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
10132 	 */
10133 	asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
10134 	fletcher_4_native(this_lb, asize, NULL, &cksum);
10135 	if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
10136 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
10137 		zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
10138 		    "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
10139 		    this_lbp->lbp_daddr, dev->l2ad_vdev->vdev_guid,
10140 		    dev->l2ad_hand, dev->l2ad_evict);
10141 		err = SET_ERROR(ECKSUM);
10142 		goto cleanup;
10143 	}
10144 
10145 	/* Now we can take our time decoding this buffer */
10146 	switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
10147 	case ZIO_COMPRESS_OFF:
10148 		break;
10149 	case ZIO_COMPRESS_LZ4:
10150 		abd = abd_alloc_for_io(asize, B_TRUE);
10151 		abd_copy_from_buf_off(abd, this_lb, 0, asize);
10152 		if ((err = zio_decompress_data(
10153 		    L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
10154 		    abd, this_lb, asize, sizeof (*this_lb), NULL)) != 0) {
10155 			err = SET_ERROR(EINVAL);
10156 			goto cleanup;
10157 		}
10158 		break;
10159 	default:
10160 		err = SET_ERROR(EINVAL);
10161 		goto cleanup;
10162 	}
10163 	if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
10164 		byteswap_uint64_array(this_lb, sizeof (*this_lb));
10165 	if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
10166 		err = SET_ERROR(EINVAL);
10167 		goto cleanup;
10168 	}
10169 cleanup:
10170 	/* Abort an in-flight fetch I/O in case of error */
10171 	if (err != 0 && *next_io != NULL) {
10172 		l2arc_log_blk_fetch_abort(*next_io);
10173 		*next_io = NULL;
10174 	}
10175 	if (abd != NULL)
10176 		abd_free(abd);
10177 	return (err);
10178 }
10179 
10180 /*
10181  * Restores the payload of a log block to ARC. This creates empty ARC hdr
10182  * entries which only contain an l2arc hdr, essentially restoring the
10183  * buffers to their L2ARC evicted state. This function also updates space
10184  * usage on the L2ARC vdev to make sure it tracks restored buffers.
10185  */
10186 static void
10187 l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
10188     uint64_t lb_asize)
10189 {
10190 	uint64_t	size = 0, asize = 0;
10191 	uint64_t	log_entries = dev->l2ad_log_entries;
10192 
10193 	/*
10194 	 * Usually arc_adapt() is called only for data, not headers, but
10195 	 * since we may allocate significant amount of memory here, let ARC
10196 	 * grow its arc_c.
10197 	 */
10198 	arc_adapt(log_entries * HDR_L2ONLY_SIZE, arc_l2c_only);
10199 
10200 	for (int i = log_entries - 1; i >= 0; i--) {
10201 		/*
10202 		 * Restore goes in the reverse temporal direction to preserve
10203 		 * correct temporal ordering of buffers in the l2ad_buflist.
10204 		 * l2arc_hdr_restore also does a list_insert_tail instead of
10205 		 * list_insert_head on the l2ad_buflist:
10206 		 *
10207 		 *		LIST	l2ad_buflist		LIST
10208 		 *		HEAD  <------ (time) ------	TAIL
10209 		 * direction	+-----+-----+-----+-----+-----+    direction
10210 		 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
10211 		 * fill		+-----+-----+-----+-----+-----+
10212 		 *		^				^
10213 		 *		|				|
10214 		 *		|				|
10215 		 *	l2arc_feed_thread		l2arc_rebuild
10216 		 *	will place new bufs here	restores bufs here
10217 		 *
10218 		 * During l2arc_rebuild() the device is not used by
10219 		 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
10220 		 */
10221 		size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
10222 		asize += vdev_psize_to_asize(dev->l2ad_vdev,
10223 		    L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
10224 		l2arc_hdr_restore(&lb->lb_entries[i], dev);
10225 	}
10226 
10227 	/*
10228 	 * Record rebuild stats:
10229 	 *	size		Logical size of restored buffers in the L2ARC
10230 	 *	asize		Aligned size of restored buffers in the L2ARC
10231 	 */
10232 	ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
10233 	ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
10234 	ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
10235 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
10236 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
10237 	ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
10238 }
10239 
10240 /*
10241  * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
10242  * into a state indicating that it has been evicted to L2ARC.
10243  */
10244 static void
10245 l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
10246 {
10247 	arc_buf_hdr_t		*hdr, *exists;
10248 	kmutex_t		*hash_lock;
10249 	arc_buf_contents_t	type = L2BLK_GET_TYPE((le)->le_prop);
10250 	uint64_t		asize;
10251 
10252 	/*
10253 	 * Do all the allocation before grabbing any locks, this lets us
10254 	 * sleep if memory is full and we don't have to deal with failed
10255 	 * allocations.
10256 	 */
10257 	hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
10258 	    dev, le->le_dva, le->le_daddr,
10259 	    L2BLK_GET_PSIZE((le)->le_prop), le->le_birth,
10260 	    L2BLK_GET_COMPRESS((le)->le_prop), le->le_complevel,
10261 	    L2BLK_GET_PROTECTED((le)->le_prop),
10262 	    L2BLK_GET_PREFETCH((le)->le_prop),
10263 	    L2BLK_GET_STATE((le)->le_prop));
10264 	asize = vdev_psize_to_asize(dev->l2ad_vdev,
10265 	    L2BLK_GET_PSIZE((le)->le_prop));
10266 
10267 	/*
10268 	 * vdev_space_update() has to be called before arc_hdr_destroy() to
10269 	 * avoid underflow since the latter also calls vdev_space_update().
10270 	 */
10271 	l2arc_hdr_arcstats_increment(hdr);
10272 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10273 
10274 	mutex_enter(&dev->l2ad_mtx);
10275 	list_insert_tail(&dev->l2ad_buflist, hdr);
10276 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
10277 	mutex_exit(&dev->l2ad_mtx);
10278 
10279 	exists = buf_hash_insert(hdr, &hash_lock);
10280 	if (exists) {
10281 		/* Buffer was already cached, no need to restore it. */
10282 		arc_hdr_destroy(hdr);
10283 		/*
10284 		 * If the buffer is already cached, check whether it has
10285 		 * L2ARC metadata. If not, enter them and update the flag.
10286 		 * This is important is case of onlining a cache device, since
10287 		 * we previously evicted all L2ARC metadata from ARC.
10288 		 */
10289 		if (!HDR_HAS_L2HDR(exists)) {
10290 			arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
10291 			exists->b_l2hdr.b_dev = dev;
10292 			exists->b_l2hdr.b_daddr = le->le_daddr;
10293 			exists->b_l2hdr.b_arcs_state =
10294 			    L2BLK_GET_STATE((le)->le_prop);
10295 			mutex_enter(&dev->l2ad_mtx);
10296 			list_insert_tail(&dev->l2ad_buflist, exists);
10297 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
10298 			    arc_hdr_size(exists), exists);
10299 			mutex_exit(&dev->l2ad_mtx);
10300 			l2arc_hdr_arcstats_increment(exists);
10301 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10302 		}
10303 		ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
10304 	}
10305 
10306 	mutex_exit(hash_lock);
10307 }
10308 
10309 /*
10310  * Starts an asynchronous read IO to read a log block. This is used in log
10311  * block reconstruction to start reading the next block before we are done
10312  * decoding and reconstructing the current block, to keep the l2arc device
10313  * nice and hot with read IO to process.
10314  * The returned zio will contain a newly allocated memory buffers for the IO
10315  * data which should then be freed by the caller once the zio is no longer
10316  * needed (i.e. due to it having completed). If you wish to abort this
10317  * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
10318  * care of disposing of the allocated buffers correctly.
10319  */
10320 static zio_t *
10321 l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
10322     l2arc_log_blk_phys_t *lb)
10323 {
10324 	uint32_t		asize;
10325 	zio_t			*pio;
10326 	l2arc_read_callback_t	*cb;
10327 
10328 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
10329 	asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10330 	ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
10331 
10332 	cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
10333 	cb->l2rcb_abd = abd_get_from_buf(lb, asize);
10334 	pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
10335 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
10336 	    ZIO_FLAG_DONT_RETRY);
10337 	(void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
10338 	    cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10339 	    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
10340 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
10341 
10342 	return (pio);
10343 }
10344 
10345 /*
10346  * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
10347  * buffers allocated for it.
10348  */
10349 static void
10350 l2arc_log_blk_fetch_abort(zio_t *zio)
10351 {
10352 	(void) zio_wait(zio);
10353 }
10354 
10355 /*
10356  * Creates a zio to update the device header on an l2arc device.
10357  */
10358 void
10359 l2arc_dev_hdr_update(l2arc_dev_t *dev)
10360 {
10361 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10362 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
10363 	abd_t			*abd;
10364 	int			err;
10365 
10366 	VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
10367 
10368 	l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
10369 	l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
10370 	l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
10371 	l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
10372 	l2dhdr->dh_log_entries = dev->l2ad_log_entries;
10373 	l2dhdr->dh_evict = dev->l2ad_evict;
10374 	l2dhdr->dh_start = dev->l2ad_start;
10375 	l2dhdr->dh_end = dev->l2ad_end;
10376 	l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
10377 	l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
10378 	l2dhdr->dh_flags = 0;
10379 	l2dhdr->dh_trim_action_time = dev->l2ad_vdev->vdev_trim_action_time;
10380 	l2dhdr->dh_trim_state = dev->l2ad_vdev->vdev_trim_state;
10381 	if (dev->l2ad_first)
10382 		l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
10383 
10384 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
10385 
10386 	err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
10387 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
10388 	    NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
10389 
10390 	abd_free(abd);
10391 
10392 	if (err != 0) {
10393 		zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
10394 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
10395 	}
10396 }
10397 
10398 /*
10399  * Commits a log block to the L2ARC device. This routine is invoked from
10400  * l2arc_write_buffers when the log block fills up.
10401  * This function allocates some memory to temporarily hold the serialized
10402  * buffer to be written. This is then released in l2arc_write_done.
10403  */
10404 static void
10405 l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
10406 {
10407 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
10408 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
10409 	uint64_t		psize, asize;
10410 	zio_t			*wzio;
10411 	l2arc_lb_abd_buf_t	*abd_buf;
10412 	uint8_t			*tmpbuf;
10413 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
10414 
10415 	VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
10416 
10417 	tmpbuf = zio_buf_alloc(sizeof (*lb));
10418 	abd_buf = zio_buf_alloc(sizeof (*abd_buf));
10419 	abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
10420 	lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
10421 	lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
10422 
10423 	/* link the buffer into the block chain */
10424 	lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
10425 	lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
10426 
10427 	/*
10428 	 * l2arc_log_blk_commit() may be called multiple times during a single
10429 	 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
10430 	 * so we can free them in l2arc_write_done() later on.
10431 	 */
10432 	list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
10433 
10434 	/* try to compress the buffer */
10435 	psize = zio_compress_data(ZIO_COMPRESS_LZ4,
10436 	    abd_buf->abd, tmpbuf, sizeof (*lb), 0);
10437 
10438 	/* a log block is never entirely zero */
10439 	ASSERT(psize != 0);
10440 	asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
10441 	ASSERT(asize <= sizeof (*lb));
10442 
10443 	/*
10444 	 * Update the start log block pointer in the device header to point
10445 	 * to the log block we're about to write.
10446 	 */
10447 	l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
10448 	l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
10449 	l2dhdr->dh_start_lbps[0].lbp_payload_asize =
10450 	    dev->l2ad_log_blk_payload_asize;
10451 	l2dhdr->dh_start_lbps[0].lbp_payload_start =
10452 	    dev->l2ad_log_blk_payload_start;
10453 	_NOTE(CONSTCOND)
10454 	L2BLK_SET_LSIZE(
10455 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
10456 	L2BLK_SET_PSIZE(
10457 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
10458 	L2BLK_SET_CHECKSUM(
10459 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10460 	    ZIO_CHECKSUM_FLETCHER_4);
10461 	if (asize < sizeof (*lb)) {
10462 		/* compression succeeded */
10463 		bzero(tmpbuf + psize, asize - psize);
10464 		L2BLK_SET_COMPRESS(
10465 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10466 		    ZIO_COMPRESS_LZ4);
10467 	} else {
10468 		/* compression failed */
10469 		bcopy(lb, tmpbuf, sizeof (*lb));
10470 		L2BLK_SET_COMPRESS(
10471 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
10472 		    ZIO_COMPRESS_OFF);
10473 	}
10474 
10475 	/* checksum what we're about to write */
10476 	fletcher_4_native(tmpbuf, asize, NULL,
10477 	    &l2dhdr->dh_start_lbps[0].lbp_cksum);
10478 
10479 	abd_free(abd_buf->abd);
10480 
10481 	/* perform the write itself */
10482 	abd_buf->abd = abd_get_from_buf(tmpbuf, sizeof (*lb));
10483 	abd_take_ownership_of_buf(abd_buf->abd, B_TRUE);
10484 	wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
10485 	    asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
10486 	    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
10487 	DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
10488 	(void) zio_nowait(wzio);
10489 
10490 	dev->l2ad_hand += asize;
10491 	/*
10492 	 * Include the committed log block's pointer  in the list of pointers
10493 	 * to log blocks present in the L2ARC device.
10494 	 */
10495 	bcopy(&l2dhdr->dh_start_lbps[0], lb_ptr_buf->lb_ptr,
10496 	    sizeof (l2arc_log_blkptr_t));
10497 	mutex_enter(&dev->l2ad_mtx);
10498 	list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
10499 	ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
10500 	ARCSTAT_BUMP(arcstat_l2_log_blk_count);
10501 	zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
10502 	zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
10503 	mutex_exit(&dev->l2ad_mtx);
10504 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
10505 
10506 	/* bump the kstats */
10507 	ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
10508 	ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
10509 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
10510 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
10511 	    dev->l2ad_log_blk_payload_asize / asize);
10512 
10513 	/* start a new log block */
10514 	dev->l2ad_log_ent_idx = 0;
10515 	dev->l2ad_log_blk_payload_asize = 0;
10516 	dev->l2ad_log_blk_payload_start = 0;
10517 }
10518 
10519 /*
10520  * Validates an L2ARC log block address to make sure that it can be read
10521  * from the provided L2ARC device.
10522  */
10523 boolean_t
10524 l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
10525 {
10526 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
10527 	uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
10528 	uint64_t end = lbp->lbp_daddr + asize - 1;
10529 	uint64_t start = lbp->lbp_payload_start;
10530 	boolean_t evicted = B_FALSE;
10531 
10532 	/*
10533 	 * A log block is valid if all of the following conditions are true:
10534 	 * - it fits entirely (including its payload) between l2ad_start and
10535 	 *   l2ad_end
10536 	 * - it has a valid size
10537 	 * - neither the log block itself nor part of its payload was evicted
10538 	 *   by l2arc_evict():
10539 	 *
10540 	 *		l2ad_hand          l2ad_evict
10541 	 *		|			 |	lbp_daddr
10542 	 *		|     start		 |	|  end
10543 	 *		|     |			 |	|  |
10544 	 *		V     V		         V	V  V
10545 	 *   l2ad_start ============================================ l2ad_end
10546 	 *                    --------------------------||||
10547 	 *				^		 ^
10548 	 *				|		log block
10549 	 *				payload
10550 	 */
10551 
10552 	evicted =
10553 	    l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
10554 	    l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
10555 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
10556 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
10557 
10558 	return (start >= dev->l2ad_start && end <= dev->l2ad_end &&
10559 	    asize > 0 && asize <= sizeof (l2arc_log_blk_phys_t) &&
10560 	    (!evicted || dev->l2ad_first));
10561 }
10562 
10563 /*
10564  * Inserts ARC buffer header `hdr' into the current L2ARC log block on
10565  * the device. The buffer being inserted must be present in L2ARC.
10566  * Returns B_TRUE if the L2ARC log block is full and needs to be committed
10567  * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
10568  */
10569 static boolean_t
10570 l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
10571 {
10572 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
10573 	l2arc_log_ent_phys_t	*le;
10574 
10575 	if (dev->l2ad_log_entries == 0)
10576 		return (B_FALSE);
10577 
10578 	int index = dev->l2ad_log_ent_idx++;
10579 
10580 	ASSERT3S(index, <, dev->l2ad_log_entries);
10581 	ASSERT(HDR_HAS_L2HDR(hdr));
10582 
10583 	le = &lb->lb_entries[index];
10584 	bzero(le, sizeof (*le));
10585 	le->le_dva = hdr->b_dva;
10586 	le->le_birth = hdr->b_birth;
10587 	le->le_daddr = hdr->b_l2hdr.b_daddr;
10588 	if (index == 0)
10589 		dev->l2ad_log_blk_payload_start = le->le_daddr;
10590 	L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
10591 	L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
10592 	L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
10593 	le->le_complevel = hdr->b_complevel;
10594 	L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
10595 	L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
10596 	L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
10597 	L2BLK_SET_STATE((le)->le_prop, hdr->b_l1hdr.b_state->arcs_state);
10598 
10599 	dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
10600 	    HDR_GET_PSIZE(hdr));
10601 
10602 	return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
10603 }
10604 
10605 /*
10606  * Checks whether a given L2ARC device address sits in a time-sequential
10607  * range. The trick here is that the L2ARC is a rotary buffer, so we can't
10608  * just do a range comparison, we need to handle the situation in which the
10609  * range wraps around the end of the L2ARC device. Arguments:
10610  *	bottom -- Lower end of the range to check (written to earlier).
10611  *	top    -- Upper end of the range to check (written to later).
10612  *	check  -- The address for which we want to determine if it sits in
10613  *		  between the top and bottom.
10614  *
10615  * The 3-way conditional below represents the following cases:
10616  *
10617  *	bottom < top : Sequentially ordered case:
10618  *	  <check>--------+-------------------+
10619  *	                 |  (overlap here?)  |
10620  *	 L2ARC dev       V                   V
10621  *	 |---------------<bottom>============<top>--------------|
10622  *
10623  *	bottom > top: Looped-around case:
10624  *	                      <check>--------+------------------+
10625  *	                                     |  (overlap here?) |
10626  *	 L2ARC dev                           V                  V
10627  *	 |===============<top>---------------<bottom>===========|
10628  *	 ^               ^
10629  *	 |  (or here?)   |
10630  *	 +---------------+---------<check>
10631  *
10632  *	top == bottom : Just a single address comparison.
10633  */
10634 boolean_t
10635 l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
10636 {
10637 	if (bottom < top)
10638 		return (bottom <= check && check <= top);
10639 	else if (bottom > top)
10640 		return (check <= top || bottom <= check);
10641 	else
10642 		return (check == top);
10643 }
10644 
10645 EXPORT_SYMBOL(arc_buf_size);
10646 EXPORT_SYMBOL(arc_write);
10647 EXPORT_SYMBOL(arc_read);
10648 EXPORT_SYMBOL(arc_buf_info);
10649 EXPORT_SYMBOL(arc_getbuf_func);
10650 EXPORT_SYMBOL(arc_add_prune_callback);
10651 EXPORT_SYMBOL(arc_remove_prune_callback);
10652 
10653 /* BEGIN CSTYLED */
10654 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min, param_set_arc_long,
10655 	param_get_long, ZMOD_RW, "Min arc size");
10656 
10657 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, max, param_set_arc_long,
10658 	param_get_long, ZMOD_RW, "Max arc size");
10659 
10660 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_limit, param_set_arc_long,
10661 	param_get_long, ZMOD_RW, "Metadata limit for arc size");
10662 
10663 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_limit_percent,
10664 	param_set_arc_long, param_get_long, ZMOD_RW,
10665 	"Percent of arc size for arc meta limit");
10666 
10667 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, meta_min, param_set_arc_long,
10668 	param_get_long, ZMOD_RW, "Min arc metadata");
10669 
10670 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_prune, INT, ZMOD_RW,
10671 	"Meta objects to scan for prune");
10672 
10673 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_adjust_restarts, INT, ZMOD_RW,
10674 	"Limit number of restarts in arc_evict_meta");
10675 
10676 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, meta_strategy, INT, ZMOD_RW,
10677 	"Meta reclaim strategy");
10678 
10679 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, grow_retry, param_set_arc_int,
10680 	param_get_int, ZMOD_RW, "Seconds before growing arc size");
10681 
10682 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, p_dampener_disable, INT, ZMOD_RW,
10683 	"Disable arc_p adapt dampener");
10684 
10685 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, shrink_shift, param_set_arc_int,
10686 	param_get_int, ZMOD_RW, "log2(fraction of arc to reclaim)");
10687 
10688 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, pc_percent, UINT, ZMOD_RW,
10689 	"Percent of pagecache to reclaim arc to");
10690 
10691 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, p_min_shift, param_set_arc_int,
10692 	param_get_int, ZMOD_RW, "arc_c shift to calc min/max arc_p");
10693 
10694 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, average_blocksize, INT, ZMOD_RD,
10695 	"Target average block size");
10696 
10697 ZFS_MODULE_PARAM(zfs, zfs_, compressed_arc_enabled, INT, ZMOD_RW,
10698 	"Disable compressed arc buffers");
10699 
10700 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prefetch_ms, param_set_arc_int,
10701 	param_get_int, ZMOD_RW, "Min life of prefetch block in ms");
10702 
10703 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, min_prescient_prefetch_ms,
10704 	param_set_arc_int, param_get_int, ZMOD_RW,
10705 	"Min life of prescient prefetched block in ms");
10706 
10707 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_max, ULONG, ZMOD_RW,
10708 	"Max write bytes per interval");
10709 
10710 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, write_boost, ULONG, ZMOD_RW,
10711 	"Extra write bytes during device warmup");
10712 
10713 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom, ULONG, ZMOD_RW,
10714 	"Number of max device writes to precache");
10715 
10716 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, headroom_boost, ULONG, ZMOD_RW,
10717 	"Compressed l2arc_headroom multiplier");
10718 
10719 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, trim_ahead, ULONG, ZMOD_RW,
10720 	"TRIM ahead L2ARC write size multiplier");
10721 
10722 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_secs, ULONG, ZMOD_RW,
10723 	"Seconds between L2ARC writing");
10724 
10725 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_min_ms, ULONG, ZMOD_RW,
10726 	"Min feed interval in milliseconds");
10727 
10728 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, noprefetch, INT, ZMOD_RW,
10729 	"Skip caching prefetched buffers");
10730 
10731 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, feed_again, INT, ZMOD_RW,
10732 	"Turbo L2ARC warmup");
10733 
10734 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, norw, INT, ZMOD_RW,
10735 	"No reads during writes");
10736 
10737 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, meta_percent, INT, ZMOD_RW,
10738 	"Percent of ARC size allowed for L2ARC-only headers");
10739 
10740 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_enabled, INT, ZMOD_RW,
10741 	"Rebuild the L2ARC when importing a pool");
10742 
10743 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, rebuild_blocks_min_l2size, ULONG, ZMOD_RW,
10744 	"Min size in bytes to write rebuild log blocks in L2ARC");
10745 
10746 ZFS_MODULE_PARAM(zfs_l2arc, l2arc_, mfuonly, INT, ZMOD_RW,
10747 	"Cache only MFU data from ARC into L2ARC");
10748 
10749 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, lotsfree_percent, param_set_arc_int,
10750 	param_get_int, ZMOD_RW, "System free memory I/O throttle in bytes");
10751 
10752 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, sys_free, param_set_arc_long,
10753 	param_get_long, ZMOD_RW, "System free memory target size in bytes");
10754 
10755 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit, param_set_arc_long,
10756 	param_get_long, ZMOD_RW, "Minimum bytes of dnodes in arc");
10757 
10758 ZFS_MODULE_PARAM_CALL(zfs_arc, zfs_arc_, dnode_limit_percent,
10759 	param_set_arc_long, param_get_long, ZMOD_RW,
10760 	"Percent of ARC meta buffers for dnodes");
10761 
10762 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, dnode_reduce_percent, ULONG, ZMOD_RW,
10763 	"Percentage of excess dnodes to try to unpin");
10764 
10765 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, eviction_pct, INT, ZMOD_RW,
10766 	"When full, ARC allocation waits for eviction of this % of alloc size");
10767 
10768 ZFS_MODULE_PARAM(zfs_arc, zfs_arc_, evict_batch_limit, INT, ZMOD_RW,
10769 	"The number of headers to evict per sublist before moving to the next");
10770 /* END CSTYLED */
10771