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