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