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