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