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