xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision 66597161e2ba69a84fa138bce7ac02a1e6b9746c)
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 
4625 	/*
4626 	 * If zio data pages are being allocated out of a separate heap segment,
4627 	 * then enforce that the size of available vmem for this arena remains
4628 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4629 	 *
4630 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4631 	 * memory (in the zio_arena) free, which can avoid memory
4632 	 * fragmentation issues.
4633 	 */
4634 	if (zio_arena != NULL) {
4635 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4636 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
4637 		    arc_zio_arena_free_shift);
4638 		if (n < lowest) {
4639 			lowest = n;
4640 			r = FMR_ZIO_ARENA;
4641 		}
4642 	}
4643 #else
4644 	/* Every 100 calls, free a small amount */
4645 	if (spa_get_random(100) == 0)
4646 		lowest = -1024;
4647 #endif
4648 
4649 	last_free_memory = lowest;
4650 	last_free_reason = r;
4651 
4652 	return (lowest);
4653 }
4654 
4655 
4656 /*
4657  * Determine if the system is under memory pressure and is asking
4658  * to reclaim memory. A return value of B_TRUE indicates that the system
4659  * is under memory pressure and that the arc should adjust accordingly.
4660  */
4661 static boolean_t
4662 arc_reclaim_needed(void)
4663 {
4664 	return (arc_available_memory() < 0);
4665 }
4666 
4667 static void
4668 arc_kmem_reap_soon(void)
4669 {
4670 	size_t			i;
4671 	kmem_cache_t		*prev_cache = NULL;
4672 	kmem_cache_t		*prev_data_cache = NULL;
4673 	extern kmem_cache_t	*zio_buf_cache[];
4674 	extern kmem_cache_t	*zio_data_buf_cache[];
4675 	extern kmem_cache_t	*zfs_btree_leaf_cache;
4676 	extern kmem_cache_t	*abd_chunk_cache;
4677 
4678 #ifdef _KERNEL
4679 	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4680 		/*
4681 		 * We are exceeding our meta-data cache limit.
4682 		 * Purge some DNLC entries to release holds on meta-data.
4683 		 */
4684 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4685 	}
4686 #endif
4687 
4688 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4689 		if (zio_buf_cache[i] != prev_cache) {
4690 			prev_cache = zio_buf_cache[i];
4691 			kmem_cache_reap_soon(zio_buf_cache[i]);
4692 		}
4693 		if (zio_data_buf_cache[i] != prev_data_cache) {
4694 			prev_data_cache = zio_data_buf_cache[i];
4695 			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4696 		}
4697 	}
4698 	kmem_cache_reap_soon(abd_chunk_cache);
4699 	kmem_cache_reap_soon(buf_cache);
4700 	kmem_cache_reap_soon(hdr_full_cache);
4701 	kmem_cache_reap_soon(hdr_l2only_cache);
4702 	kmem_cache_reap_soon(zfs_btree_leaf_cache);
4703 
4704 	if (zio_arena != NULL) {
4705 		/*
4706 		 * Ask the vmem arena to reclaim unused memory from its
4707 		 * quantum caches.
4708 		 */
4709 		vmem_qcache_reap(zio_arena);
4710 	}
4711 }
4712 
4713 /* ARGSUSED */
4714 static boolean_t
4715 arc_adjust_cb_check(void *arg, zthr_t *zthr)
4716 {
4717 	/*
4718 	 * This is necessary in order for the mdb ::arc dcmd to
4719 	 * show up to date information. Since the ::arc command
4720 	 * does not call the kstat's update function, without
4721 	 * this call, the command may show stale stats for the
4722 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4723 	 * with this change, the data might be up to 1 second
4724 	 * out of date(the arc_adjust_zthr has a maximum sleep
4725 	 * time of 1 second); but that should suffice.  The
4726 	 * arc_state_t structures can be queried directly if more
4727 	 * accurate information is needed.
4728 	 */
4729 	if (arc_ksp != NULL)
4730 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4731 
4732 	/*
4733 	 * We have to rely on arc_get_data_impl() to tell us when to adjust,
4734 	 * rather than checking if we are overflowing here, so that we are
4735 	 * sure to not leave arc_get_data_impl() waiting on
4736 	 * arc_adjust_waiters_cv.  If we have become "not overflowing" since
4737 	 * arc_get_data_impl() checked, we need to wake it up.  We could
4738 	 * broadcast the CV here, but arc_get_data_impl() may have not yet
4739 	 * gone to sleep.  We would need to use a mutex to ensure that this
4740 	 * function doesn't broadcast until arc_get_data_impl() has gone to
4741 	 * sleep (e.g. the arc_adjust_lock).  However, the lock ordering of
4742 	 * such a lock would necessarily be incorrect with respect to the
4743 	 * zthr_lock, which is held before this function is called, and is
4744 	 * held by arc_get_data_impl() when it calls zthr_wakeup().
4745 	 */
4746 	return (arc_adjust_needed);
4747 }
4748 
4749 /*
4750  * Keep arc_size under arc_c by running arc_adjust which evicts data
4751  * from the ARC.
4752  */
4753 /* ARGSUSED */
4754 static void
4755 arc_adjust_cb(void *arg, zthr_t *zthr)
4756 {
4757 	uint64_t evicted = 0;
4758 
4759 	/* Evict from cache */
4760 	evicted = arc_adjust();
4761 
4762 	/*
4763 	 * If evicted is zero, we couldn't evict anything
4764 	 * via arc_adjust(). This could be due to hash lock
4765 	 * collisions, but more likely due to the majority of
4766 	 * arc buffers being unevictable. Therefore, even if
4767 	 * arc_size is above arc_c, another pass is unlikely to
4768 	 * be helpful and could potentially cause us to enter an
4769 	 * infinite loop.  Additionally, zthr_iscancelled() is
4770 	 * checked here so that if the arc is shutting down, the
4771 	 * broadcast will wake any remaining arc adjust waiters.
4772 	 */
4773 	mutex_enter(&arc_adjust_lock);
4774 	arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
4775 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4776 	if (!arc_adjust_needed) {
4777 		/*
4778 		 * We're either no longer overflowing, or we
4779 		 * can't evict anything more, so we should wake
4780 		 * up any waiters.
4781 		 */
4782 		cv_broadcast(&arc_adjust_waiters_cv);
4783 	}
4784 	mutex_exit(&arc_adjust_lock);
4785 }
4786 
4787 /* ARGSUSED */
4788 static boolean_t
4789 arc_reap_cb_check(void *arg, zthr_t *zthr)
4790 {
4791 	int64_t free_memory = arc_available_memory();
4792 
4793 	/*
4794 	 * If a kmem reap is already active, don't schedule more.  We must
4795 	 * check for this because kmem_cache_reap_soon() won't actually
4796 	 * block on the cache being reaped (this is to prevent callers from
4797 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4798 	 * on a system with many, many full magazines, can take minutes).
4799 	 */
4800 	if (!kmem_cache_reap_active() &&
4801 	    free_memory < 0) {
4802 		arc_no_grow = B_TRUE;
4803 		arc_warm = B_TRUE;
4804 		/*
4805 		 * Wait at least zfs_grow_retry (default 60) seconds
4806 		 * before considering growing.
4807 		 */
4808 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4809 		return (B_TRUE);
4810 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4811 		arc_no_grow = B_TRUE;
4812 	} else if (gethrtime() >= arc_growtime) {
4813 		arc_no_grow = B_FALSE;
4814 	}
4815 
4816 	return (B_FALSE);
4817 }
4818 
4819 /*
4820  * Keep enough free memory in the system by reaping the ARC's kmem
4821  * caches.  To cause more slabs to be reapable, we may reduce the
4822  * target size of the cache (arc_c), causing the arc_adjust_cb()
4823  * to free more buffers.
4824  */
4825 /* ARGSUSED */
4826 static void
4827 arc_reap_cb(void *arg, zthr_t *zthr)
4828 {
4829 	int64_t free_memory;
4830 
4831 	/*
4832 	 * Kick off asynchronous kmem_reap()'s of all our caches.
4833 	 */
4834 	arc_kmem_reap_soon();
4835 
4836 	/*
4837 	 * Wait at least arc_kmem_cache_reap_retry_ms between
4838 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
4839 	 * end up in a situation where we spend lots of time reaping
4840 	 * caches, while we're near arc_c_min.  Waiting here also gives the
4841 	 * subsequent free memory check a chance of finding that the
4842 	 * asynchronous reap has already freed enough memory, and we don't
4843 	 * need to call arc_reduce_target_size().
4844 	 */
4845 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4846 
4847 	/*
4848 	 * Reduce the target size as needed to maintain the amount of free
4849 	 * memory in the system at a fraction of the arc_size (1/128th by
4850 	 * default).  If oversubscribed (free_memory < 0) then reduce the
4851 	 * target arc_size by the deficit amount plus the fractional
4852 	 * amount.  If free memory is positive but less then the fractional
4853 	 * amount, reduce by what is needed to hit the fractional amount.
4854 	 */
4855 	free_memory = arc_available_memory();
4856 
4857 	int64_t to_free =
4858 	    (arc_c >> arc_shrink_shift) - free_memory;
4859 	if (to_free > 0) {
4860 #ifdef _KERNEL
4861 		to_free = MAX(to_free, ptob(needfree));
4862 #endif
4863 		arc_reduce_target_size(to_free);
4864 	}
4865 }
4866 
4867 /*
4868  * Adapt arc info given the number of bytes we are trying to add and
4869  * the state that we are coming from.  This function is only called
4870  * when we are adding new content to the cache.
4871  */
4872 static void
4873 arc_adapt(int bytes, arc_state_t *state)
4874 {
4875 	int mult;
4876 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4877 	int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
4878 	int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
4879 
4880 	ASSERT(bytes > 0);
4881 	/*
4882 	 * Adapt the target size of the MRU list:
4883 	 *	- if we just hit in the MRU ghost list, then increase
4884 	 *	  the target size of the MRU list.
4885 	 *	- if we just hit in the MFU ghost list, then increase
4886 	 *	  the target size of the MFU list by decreasing the
4887 	 *	  target size of the MRU list.
4888 	 */
4889 	if (state == arc_mru_ghost) {
4890 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4891 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4892 
4893 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4894 	} else if (state == arc_mfu_ghost) {
4895 		uint64_t delta;
4896 
4897 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4898 		mult = MIN(mult, 10);
4899 
4900 		delta = MIN(bytes * mult, arc_p);
4901 		arc_p = MAX(arc_p_min, arc_p - delta);
4902 	}
4903 	ASSERT((int64_t)arc_p >= 0);
4904 
4905 	/*
4906 	 * Wake reap thread if we do not have any available memory
4907 	 */
4908 	if (arc_reclaim_needed()) {
4909 		zthr_wakeup(arc_reap_zthr);
4910 		return;
4911 	}
4912 
4913 
4914 	if (arc_no_grow)
4915 		return;
4916 
4917 	if (arc_c >= arc_c_max)
4918 		return;
4919 
4920 	/*
4921 	 * If we're within (2 * maxblocksize) bytes of the target
4922 	 * cache size, increment the target cache size
4923 	 */
4924 	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
4925 	    0) {
4926 		atomic_add_64(&arc_c, (int64_t)bytes);
4927 		if (arc_c > arc_c_max)
4928 			arc_c = arc_c_max;
4929 		else if (state == arc_anon)
4930 			atomic_add_64(&arc_p, (int64_t)bytes);
4931 		if (arc_p > arc_c)
4932 			arc_p = arc_c;
4933 	}
4934 	ASSERT((int64_t)arc_p >= 0);
4935 }
4936 
4937 /*
4938  * Check if arc_size has grown past our upper threshold, determined by
4939  * zfs_arc_overflow_shift.
4940  */
4941 static boolean_t
4942 arc_is_overflowing(void)
4943 {
4944 	/* Always allow at least one block of overflow */
4945 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4946 	    arc_c >> zfs_arc_overflow_shift);
4947 
4948 	/*
4949 	 * We just compare the lower bound here for performance reasons. Our
4950 	 * primary goals are to make sure that the arc never grows without
4951 	 * bound, and that it can reach its maximum size. This check
4952 	 * accomplishes both goals. The maximum amount we could run over by is
4953 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4954 	 * in the ARC. In practice, that's in the tens of MB, which is low
4955 	 * enough to be safe.
4956 	 */
4957 	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4958 }
4959 
4960 static abd_t *
4961 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag,
4962     boolean_t do_adapt)
4963 {
4964 	arc_buf_contents_t type = arc_buf_type(hdr);
4965 
4966 	arc_get_data_impl(hdr, size, tag, do_adapt);
4967 	if (type == ARC_BUFC_METADATA) {
4968 		return (abd_alloc(size, B_TRUE));
4969 	} else {
4970 		ASSERT(type == ARC_BUFC_DATA);
4971 		return (abd_alloc(size, B_FALSE));
4972 	}
4973 }
4974 
4975 static void *
4976 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4977 {
4978 	arc_buf_contents_t type = arc_buf_type(hdr);
4979 
4980 	arc_get_data_impl(hdr, size, tag, B_TRUE);
4981 	if (type == ARC_BUFC_METADATA) {
4982 		return (zio_buf_alloc(size));
4983 	} else {
4984 		ASSERT(type == ARC_BUFC_DATA);
4985 		return (zio_data_buf_alloc(size));
4986 	}
4987 }
4988 
4989 /*
4990  * Allocate a block and return it to the caller. If we are hitting the
4991  * hard limit for the cache size, we must sleep, waiting for the eviction
4992  * thread to catch up. If we're past the target size but below the hard
4993  * limit, we'll only signal the reclaim thread and continue on.
4994  */
4995 static void
4996 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag,
4997     boolean_t do_adapt)
4998 {
4999 	arc_state_t *state = hdr->b_l1hdr.b_state;
5000 	arc_buf_contents_t type = arc_buf_type(hdr);
5001 
5002 	if (do_adapt)
5003 		arc_adapt(size, state);
5004 
5005 	/*
5006 	 * If arc_size is currently overflowing, and has grown past our
5007 	 * upper limit, we must be adding data faster than the evict
5008 	 * thread can evict. Thus, to ensure we don't compound the
5009 	 * problem by adding more data and forcing arc_size to grow even
5010 	 * further past its target size, we halt and wait for the
5011 	 * eviction thread to catch up.
5012 	 *
5013 	 * It's also possible that the reclaim thread is unable to evict
5014 	 * enough buffers to get arc_size below the overflow limit (e.g.
5015 	 * due to buffers being un-evictable, or hash lock collisions).
5016 	 * In this case, we want to proceed regardless if we're
5017 	 * overflowing; thus we don't use a while loop here.
5018 	 */
5019 	if (arc_is_overflowing()) {
5020 		mutex_enter(&arc_adjust_lock);
5021 
5022 		/*
5023 		 * Now that we've acquired the lock, we may no longer be
5024 		 * over the overflow limit, lets check.
5025 		 *
5026 		 * We're ignoring the case of spurious wake ups. If that
5027 		 * were to happen, it'd let this thread consume an ARC
5028 		 * buffer before it should have (i.e. before we're under
5029 		 * the overflow limit and were signalled by the reclaim
5030 		 * thread). As long as that is a rare occurrence, it
5031 		 * shouldn't cause any harm.
5032 		 */
5033 		if (arc_is_overflowing()) {
5034 			arc_adjust_needed = B_TRUE;
5035 			zthr_wakeup(arc_adjust_zthr);
5036 			(void) cv_wait(&arc_adjust_waiters_cv,
5037 			    &arc_adjust_lock);
5038 		}
5039 		mutex_exit(&arc_adjust_lock);
5040 	}
5041 
5042 	VERIFY3U(hdr->b_type, ==, type);
5043 	if (type == ARC_BUFC_METADATA) {
5044 		arc_space_consume(size, ARC_SPACE_META);
5045 	} else {
5046 		arc_space_consume(size, ARC_SPACE_DATA);
5047 	}
5048 
5049 	/*
5050 	 * Update the state size.  Note that ghost states have a
5051 	 * "ghost size" and so don't need to be updated.
5052 	 */
5053 	if (!GHOST_STATE(state)) {
5054 
5055 		(void) zfs_refcount_add_many(&state->arcs_size, size, tag);
5056 
5057 		/*
5058 		 * If this is reached via arc_read, the link is
5059 		 * protected by the hash lock. If reached via
5060 		 * arc_buf_alloc, the header should not be accessed by
5061 		 * any other thread. And, if reached via arc_read_done,
5062 		 * the hash lock will protect it if it's found in the
5063 		 * hash table; otherwise no other thread should be
5064 		 * trying to [add|remove]_reference it.
5065 		 */
5066 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5067 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5068 			(void) zfs_refcount_add_many(&state->arcs_esize[type],
5069 			    size, tag);
5070 		}
5071 
5072 		/*
5073 		 * If we are growing the cache, and we are adding anonymous
5074 		 * data, and we have outgrown arc_p, update arc_p
5075 		 */
5076 		if (aggsum_compare(&arc_size, arc_c) < 0 &&
5077 		    hdr->b_l1hdr.b_state == arc_anon &&
5078 		    (zfs_refcount_count(&arc_anon->arcs_size) +
5079 		    zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
5080 			arc_p = MIN(arc_c, arc_p + size);
5081 	}
5082 }
5083 
5084 static void
5085 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5086 {
5087 	arc_free_data_impl(hdr, size, tag);
5088 	abd_free(abd);
5089 }
5090 
5091 static void
5092 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5093 {
5094 	arc_buf_contents_t type = arc_buf_type(hdr);
5095 
5096 	arc_free_data_impl(hdr, size, tag);
5097 	if (type == ARC_BUFC_METADATA) {
5098 		zio_buf_free(buf, size);
5099 	} else {
5100 		ASSERT(type == ARC_BUFC_DATA);
5101 		zio_data_buf_free(buf, size);
5102 	}
5103 }
5104 
5105 /*
5106  * Free the arc data buffer.
5107  */
5108 static void
5109 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5110 {
5111 	arc_state_t *state = hdr->b_l1hdr.b_state;
5112 	arc_buf_contents_t type = arc_buf_type(hdr);
5113 
5114 	/* protected by hash lock, if in the hash table */
5115 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5116 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5117 		ASSERT(state != arc_anon && state != arc_l2c_only);
5118 
5119 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
5120 		    size, tag);
5121 	}
5122 	(void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
5123 
5124 	VERIFY3U(hdr->b_type, ==, type);
5125 	if (type == ARC_BUFC_METADATA) {
5126 		arc_space_return(size, ARC_SPACE_META);
5127 	} else {
5128 		ASSERT(type == ARC_BUFC_DATA);
5129 		arc_space_return(size, ARC_SPACE_DATA);
5130 	}
5131 }
5132 
5133 /*
5134  * This routine is called whenever a buffer is accessed.
5135  * NOTE: the hash lock is dropped in this function.
5136  */
5137 static void
5138 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5139 {
5140 	clock_t now;
5141 
5142 	ASSERT(MUTEX_HELD(hash_lock));
5143 	ASSERT(HDR_HAS_L1HDR(hdr));
5144 
5145 	if (hdr->b_l1hdr.b_state == arc_anon) {
5146 		/*
5147 		 * This buffer is not in the cache, and does not
5148 		 * appear in our "ghost" list.  Add the new buffer
5149 		 * to the MRU state.
5150 		 */
5151 
5152 		ASSERT0(hdr->b_l1hdr.b_arc_access);
5153 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5154 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5155 		arc_change_state(arc_mru, hdr, hash_lock);
5156 
5157 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
5158 		now = ddi_get_lbolt();
5159 
5160 		/*
5161 		 * If this buffer is here because of a prefetch, then either:
5162 		 * - clear the flag if this is a "referencing" read
5163 		 *   (any subsequent access will bump this into the MFU state).
5164 		 * or
5165 		 * - move the buffer to the head of the list if this is
5166 		 *   another prefetch (to make it less likely to be evicted).
5167 		 */
5168 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5169 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5170 				/* link protected by hash lock */
5171 				ASSERT(multilist_link_active(
5172 				    &hdr->b_l1hdr.b_arc_node));
5173 			} else {
5174 				if (HDR_HAS_L2HDR(hdr))
5175 					l2arc_hdr_arcstats_decrement_state(hdr);
5176 				arc_hdr_clear_flags(hdr,
5177 				    ARC_FLAG_PREFETCH |
5178 				    ARC_FLAG_PRESCIENT_PREFETCH);
5179 				ARCSTAT_BUMP(arcstat_mru_hits);
5180 				if (HDR_HAS_L2HDR(hdr))
5181 					l2arc_hdr_arcstats_increment_state(hdr);
5182 			}
5183 			hdr->b_l1hdr.b_arc_access = now;
5184 			return;
5185 		}
5186 
5187 		/*
5188 		 * This buffer has been "accessed" only once so far,
5189 		 * but it is still in the cache. Move it to the MFU
5190 		 * state.
5191 		 */
5192 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5193 			/*
5194 			 * More than 125ms have passed since we
5195 			 * instantiated this buffer.  Move it to the
5196 			 * most frequently used state.
5197 			 */
5198 			hdr->b_l1hdr.b_arc_access = now;
5199 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5200 			arc_change_state(arc_mfu, hdr, hash_lock);
5201 		}
5202 		ARCSTAT_BUMP(arcstat_mru_hits);
5203 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5204 		arc_state_t	*new_state;
5205 		/*
5206 		 * This buffer has been "accessed" recently, but
5207 		 * was evicted from the cache.  Move it to the
5208 		 * MFU state.
5209 		 */
5210 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5211 			new_state = arc_mru;
5212 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5213 				if (HDR_HAS_L2HDR(hdr))
5214 					l2arc_hdr_arcstats_decrement_state(hdr);
5215 				arc_hdr_clear_flags(hdr,
5216 				    ARC_FLAG_PREFETCH |
5217 				    ARC_FLAG_PRESCIENT_PREFETCH);
5218 				if (HDR_HAS_L2HDR(hdr))
5219 					l2arc_hdr_arcstats_increment_state(hdr);
5220 			}
5221 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5222 		} else {
5223 			new_state = arc_mfu;
5224 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5225 		}
5226 
5227 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5228 		arc_change_state(new_state, hdr, hash_lock);
5229 
5230 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5231 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
5232 		/*
5233 		 * This buffer has been accessed more than once and is
5234 		 * still in the cache.  Keep it in the MFU state.
5235 		 *
5236 		 * NOTE: an add_reference() that occurred when we did
5237 		 * the arc_read() will have kicked this off the list.
5238 		 * If it was a prefetch, we will explicitly move it to
5239 		 * the head of the list now.
5240 		 */
5241 		ARCSTAT_BUMP(arcstat_mfu_hits);
5242 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5243 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5244 		arc_state_t	*new_state = arc_mfu;
5245 		/*
5246 		 * This buffer has been accessed more than once but has
5247 		 * been evicted from the cache.  Move it back to the
5248 		 * MFU state.
5249 		 */
5250 
5251 		if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5252 			/*
5253 			 * This is a prefetch access...
5254 			 * move this block back to the MRU state.
5255 			 */
5256 			new_state = arc_mru;
5257 		}
5258 
5259 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5260 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5261 		arc_change_state(new_state, hdr, hash_lock);
5262 
5263 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5264 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5265 		/*
5266 		 * This buffer is on the 2nd Level ARC.
5267 		 */
5268 
5269 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5270 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5271 		arc_change_state(arc_mfu, hdr, hash_lock);
5272 	} else {
5273 		ASSERT(!"invalid arc state");
5274 	}
5275 }
5276 
5277 /*
5278  * This routine is called by dbuf_hold() to update the arc_access() state
5279  * which otherwise would be skipped for entries in the dbuf cache.
5280  */
5281 void
5282 arc_buf_access(arc_buf_t *buf)
5283 {
5284 	mutex_enter(&buf->b_evict_lock);
5285 	arc_buf_hdr_t *hdr = buf->b_hdr;
5286 
5287 	/*
5288 	 * Avoid taking the hash_lock when possible as an optimization.
5289 	 * The header must be checked again under the hash_lock in order
5290 	 * to handle the case where it is concurrently being released.
5291 	 */
5292 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5293 		mutex_exit(&buf->b_evict_lock);
5294 		return;
5295 	}
5296 
5297 	kmutex_t *hash_lock = HDR_LOCK(hdr);
5298 	mutex_enter(hash_lock);
5299 
5300 	if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5301 		mutex_exit(hash_lock);
5302 		mutex_exit(&buf->b_evict_lock);
5303 		ARCSTAT_BUMP(arcstat_access_skip);
5304 		return;
5305 	}
5306 
5307 	mutex_exit(&buf->b_evict_lock);
5308 
5309 	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5310 	    hdr->b_l1hdr.b_state == arc_mfu);
5311 
5312 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5313 	arc_access(hdr, hash_lock);
5314 	mutex_exit(hash_lock);
5315 
5316 	ARCSTAT_BUMP(arcstat_hits);
5317 	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5318 	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5319 }
5320 
5321 /* a generic arc_read_done_func_t which you can use */
5322 /* ARGSUSED */
5323 void
5324 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5325     arc_buf_t *buf, void *arg)
5326 {
5327 	if (buf == NULL)
5328 		return;
5329 
5330 	bcopy(buf->b_data, arg, arc_buf_size(buf));
5331 	arc_buf_destroy(buf, arg);
5332 }
5333 
5334 /* a generic arc_read_done_func_t */
5335 void
5336 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5337     arc_buf_t *buf, void *arg)
5338 {
5339 	arc_buf_t **bufp = arg;
5340 
5341 	if (buf == NULL) {
5342 		ASSERT(zio == NULL || zio->io_error != 0);
5343 		*bufp = NULL;
5344 	} else {
5345 		ASSERT(zio == NULL || zio->io_error == 0);
5346 		*bufp = buf;
5347 		ASSERT(buf->b_data != NULL);
5348 	}
5349 }
5350 
5351 static void
5352 arc_hdr_verify(arc_buf_hdr_t *hdr, const blkptr_t *bp)
5353 {
5354 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5355 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5356 		ASSERT3U(arc_hdr_get_compress(hdr), ==, ZIO_COMPRESS_OFF);
5357 	} else {
5358 		if (HDR_COMPRESSION_ENABLED(hdr)) {
5359 			ASSERT3U(arc_hdr_get_compress(hdr), ==,
5360 			    BP_GET_COMPRESS(bp));
5361 		}
5362 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5363 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5364 		ASSERT3U(!!HDR_PROTECTED(hdr), ==, BP_IS_PROTECTED(bp));
5365 	}
5366 }
5367 
5368 /*
5369  * XXX this should be changed to return an error, and callers
5370  * re-read from disk on failure (on nondebug bits).
5371  */
5372 static void
5373 arc_hdr_verify_checksum(spa_t *spa, arc_buf_hdr_t *hdr, const blkptr_t *bp)
5374 {
5375 	arc_hdr_verify(hdr, bp);
5376 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
5377 		return;
5378 	int err = 0;
5379 	abd_t *abd = NULL;
5380 	if (BP_IS_ENCRYPTED(bp)) {
5381 		if (HDR_HAS_RABD(hdr)) {
5382 			abd = hdr->b_crypt_hdr.b_rabd;
5383 		}
5384 	} else if (HDR_COMPRESSION_ENABLED(hdr)) {
5385 		abd = hdr->b_l1hdr.b_pabd;
5386 	}
5387 	if (abd != NULL) {
5388 		/*
5389 		 * The offset is only used for labels, which are not
5390 		 * cached in the ARC, so it doesn't matter what we
5391 		 * pass for the offset parameter.
5392 		 */
5393 		int psize = HDR_GET_PSIZE(hdr);
5394 		err = zio_checksum_error_impl(spa, bp,
5395 		    BP_GET_CHECKSUM(bp), abd, psize, 0, NULL);
5396 		if (err != 0) {
5397 			/*
5398 			 * Use abd_copy_to_buf() rather than
5399 			 * abd_borrow_buf_copy() so that we are sure to
5400 			 * include the buf in crash dumps.
5401 			 */
5402 			void *buf = kmem_alloc(psize, KM_SLEEP);
5403 			abd_copy_to_buf(buf, abd, psize);
5404 			panic("checksum of cached data doesn't match BP "
5405 			    "err=%u hdr=%p bp=%p abd=%p buf=%p",
5406 			    err, (void *)hdr, (void *)bp, (void *)abd, buf);
5407 		}
5408 	}
5409 }
5410 
5411 static void
5412 arc_read_done(zio_t *zio)
5413 {
5414 	blkptr_t	*bp = zio->io_bp;
5415 	arc_buf_hdr_t	*hdr = zio->io_private;
5416 	kmutex_t	*hash_lock = NULL;
5417 	arc_callback_t	*callback_list;
5418 	arc_callback_t	*acb;
5419 	boolean_t	freeable = B_FALSE;
5420 
5421 	/*
5422 	 * The hdr was inserted into hash-table and removed from lists
5423 	 * prior to starting I/O.  We should find this header, since
5424 	 * it's in the hash table, and it should be legit since it's
5425 	 * not possible to evict it during the I/O.  The only possible
5426 	 * reason for it not to be found is if we were freed during the
5427 	 * read.
5428 	 */
5429 	if (HDR_IN_HASH_TABLE(hdr)) {
5430 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5431 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
5432 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
5433 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
5434 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
5435 
5436 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
5437 		    &hash_lock);
5438 
5439 		ASSERT((found == hdr &&
5440 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5441 		    (found == hdr && HDR_L2_READING(hdr)));
5442 		ASSERT3P(hash_lock, !=, NULL);
5443 	}
5444 
5445 	if (BP_IS_PROTECTED(bp)) {
5446 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
5447 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
5448 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
5449 		    hdr->b_crypt_hdr.b_iv);
5450 
5451 		if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
5452 			void *tmpbuf;
5453 
5454 			tmpbuf = abd_borrow_buf_copy(zio->io_abd,
5455 			    sizeof (zil_chain_t));
5456 			zio_crypt_decode_mac_zil(tmpbuf,
5457 			    hdr->b_crypt_hdr.b_mac);
5458 			abd_return_buf(zio->io_abd, tmpbuf,
5459 			    sizeof (zil_chain_t));
5460 		} else {
5461 			zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
5462 		}
5463 	}
5464 
5465 	if (zio->io_error == 0) {
5466 		/* byteswap if necessary */
5467 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5468 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
5469 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5470 			} else {
5471 				hdr->b_l1hdr.b_byteswap =
5472 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5473 			}
5474 		} else {
5475 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5476 		}
5477 	}
5478 
5479 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5480 
5481 	callback_list = hdr->b_l1hdr.b_acb;
5482 	ASSERT3P(callback_list, !=, NULL);
5483 
5484 	if (hash_lock && zio->io_error == 0 &&
5485 	    hdr->b_l1hdr.b_state == arc_anon) {
5486 		/*
5487 		 * Only call arc_access on anonymous buffers.  This is because
5488 		 * if we've issued an I/O for an evicted buffer, we've already
5489 		 * called arc_access (to prevent any simultaneous readers from
5490 		 * getting confused).
5491 		 */
5492 		arc_access(hdr, hash_lock);
5493 	}
5494 
5495 	/*
5496 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
5497 	 * make a buf containing the data according to the parameters which were
5498 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5499 	 * aren't needlessly decompressing the data multiple times.
5500 	 */
5501 	int callback_cnt = 0;
5502 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5503 		if (!acb->acb_done)
5504 			continue;
5505 
5506 		callback_cnt++;
5507 
5508 		if (zio->io_error != 0)
5509 			continue;
5510 
5511 		int error = arc_buf_alloc_impl(hdr, zio->io_spa,
5512 		    &acb->acb_zb, acb->acb_private, acb->acb_encrypted,
5513 		    acb->acb_compressed, acb->acb_noauth, B_TRUE,
5514 		    &acb->acb_buf);
5515 
5516 		/*
5517 		 * Assert non-speculative zios didn't fail because an
5518 		 * encryption key wasn't loaded
5519 		 */
5520 		ASSERT((zio->io_flags & ZIO_FLAG_SPECULATIVE) ||
5521 		    error != EACCES);
5522 
5523 		/*
5524 		 * If we failed to decrypt, report an error now (as the zio
5525 		 * layer would have done if it had done the transforms).
5526 		 */
5527 		if (error == ECKSUM) {
5528 			ASSERT(BP_IS_PROTECTED(bp));
5529 			error = SET_ERROR(EIO);
5530 			if ((zio->io_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5531 				spa_log_error(zio->io_spa, &acb->acb_zb);
5532 				(void) zfs_ereport_post(
5533 				    FM_EREPORT_ZFS_AUTHENTICATION,
5534 				    zio->io_spa, NULL, &acb->acb_zb, zio, 0, 0);
5535 			}
5536 		}
5537 
5538 		if (error != 0) {
5539 			/*
5540 			 * Decompression failed.  Set io_error
5541 			 * so that when we call acb_done (below),
5542 			 * we will indicate that the read failed.
5543 			 * Note that in the unusual case where one
5544 			 * callback is compressed and another
5545 			 * uncompressed, we will mark all of them
5546 			 * as failed, even though the uncompressed
5547 			 * one can't actually fail.  In this case,
5548 			 * the hdr will not be anonymous, because
5549 			 * if there are multiple callbacks, it's
5550 			 * because multiple threads found the same
5551 			 * arc buf in the hash table.
5552 			 */
5553 			zio->io_error = error;
5554 		}
5555 	}
5556 
5557 	/*
5558 	 * If there are multiple callbacks, we must have the hash lock,
5559 	 * because the only way for multiple threads to find this hdr is
5560 	 * in the hash table.  This ensures that if there are multiple
5561 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
5562 	 * we couldn't use arc_buf_destroy() in the error case below.
5563 	 */
5564 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
5565 
5566 	hdr->b_l1hdr.b_acb = NULL;
5567 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5568 	if (callback_cnt == 0)
5569 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
5570 
5571 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5572 	    callback_list != NULL);
5573 
5574 	if (zio->io_error == 0) {
5575 		arc_hdr_verify(hdr, zio->io_bp);
5576 	} else {
5577 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5578 		if (hdr->b_l1hdr.b_state != arc_anon)
5579 			arc_change_state(arc_anon, hdr, hash_lock);
5580 		if (HDR_IN_HASH_TABLE(hdr))
5581 			buf_hash_remove(hdr);
5582 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5583 	}
5584 
5585 	/*
5586 	 * Broadcast before we drop the hash_lock to avoid the possibility
5587 	 * that the hdr (and hence the cv) might be freed before we get to
5588 	 * the cv_broadcast().
5589 	 */
5590 	cv_broadcast(&hdr->b_l1hdr.b_cv);
5591 
5592 	if (hash_lock != NULL) {
5593 		mutex_exit(hash_lock);
5594 	} else {
5595 		/*
5596 		 * This block was freed while we waited for the read to
5597 		 * complete.  It has been removed from the hash table and
5598 		 * moved to the anonymous state (so that it won't show up
5599 		 * in the cache).
5600 		 */
5601 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5602 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5603 	}
5604 
5605 	/* execute each callback and free its structure */
5606 	while ((acb = callback_list) != NULL) {
5607 
5608 		if (acb->acb_done != NULL) {
5609 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
5610 				/*
5611 				 * If arc_buf_alloc_impl() fails during
5612 				 * decompression, the buf will still be
5613 				 * allocated, and needs to be freed here.
5614 				 */
5615 				arc_buf_destroy(acb->acb_buf, acb->acb_private);
5616 				acb->acb_buf = NULL;
5617 			}
5618 			acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5619 			    acb->acb_buf, acb->acb_private);
5620 		}
5621 
5622 		if (acb->acb_zio_dummy != NULL) {
5623 			acb->acb_zio_dummy->io_error = zio->io_error;
5624 			zio_nowait(acb->acb_zio_dummy);
5625 		}
5626 
5627 		callback_list = acb->acb_next;
5628 		kmem_free(acb, sizeof (arc_callback_t));
5629 	}
5630 
5631 	if (freeable)
5632 		arc_hdr_destroy(hdr);
5633 }
5634 
5635 /*
5636  * "Read" the block at the specified DVA (in bp) via the
5637  * cache.  If the block is found in the cache, invoke the provided
5638  * callback immediately and return.  Note that the `zio' parameter
5639  * in the callback will be NULL in this case, since no IO was
5640  * required.  If the block is not in the cache pass the read request
5641  * on to the spa with a substitute callback function, so that the
5642  * requested block will be added to the cache.
5643  *
5644  * If a read request arrives for a block that has a read in-progress,
5645  * either wait for the in-progress read to complete (and return the
5646  * results); or, if this is a read with a "done" func, add a record
5647  * to the read to invoke the "done" func when the read completes,
5648  * and return; or just return.
5649  *
5650  * arc_read_done() will invoke all the requested "done" functions
5651  * for readers of this block.
5652  */
5653 int
5654 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_read_done_func_t *done,
5655     void *private, zio_priority_t priority, int zio_flags,
5656     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5657 {
5658 	arc_buf_hdr_t *hdr = NULL;
5659 	kmutex_t *hash_lock = NULL;
5660 	zio_t *rzio;
5661 	uint64_t guid = spa_load_guid(spa);
5662 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW_COMPRESS) != 0;
5663 	boolean_t encrypted_read = BP_IS_ENCRYPTED(bp) &&
5664 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5665 	boolean_t noauth_read = BP_IS_AUTHENTICATED(bp) &&
5666 	    (zio_flags & ZIO_FLAG_RAW_ENCRYPT) != 0;
5667 	int rc = 0;
5668 
5669 	ASSERT(!BP_IS_EMBEDDED(bp) ||
5670 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5671 
5672 top:
5673 	if (!BP_IS_EMBEDDED(bp)) {
5674 		/*
5675 		 * Embedded BP's have no DVA and require no I/O to "read".
5676 		 * Create an anonymous arc buf to back it.
5677 		 */
5678 		hdr = buf_hash_find(guid, bp, &hash_lock);
5679 	}
5680 
5681 	/*
5682 	 * Determine if we have an L1 cache hit or a cache miss. For simplicity
5683 	 * we maintain encrypted data seperately from compressed / uncompressed
5684 	 * data. If the user is requesting raw encrypted data and we don't have
5685 	 * that in the header we will read from disk to guarantee that we can
5686 	 * get it even if the encryption keys aren't loaded.
5687 	 */
5688 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && (HDR_HAS_RABD(hdr) ||
5689 	    (hdr->b_l1hdr.b_pabd != NULL && !encrypted_read))) {
5690 		arc_buf_t *buf = NULL;
5691 		*arc_flags |= ARC_FLAG_CACHED;
5692 
5693 		if (HDR_IO_IN_PROGRESS(hdr)) {
5694 			zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5695 
5696 			ASSERT3P(head_zio, !=, NULL);
5697 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5698 			    priority == ZIO_PRIORITY_SYNC_READ) {
5699 				/*
5700 				 * This is a sync read that needs to wait for
5701 				 * an in-flight async read. Request that the
5702 				 * zio have its priority upgraded.
5703 				 */
5704 				zio_change_priority(head_zio, priority);
5705 				DTRACE_PROBE1(arc__async__upgrade__sync,
5706 				    arc_buf_hdr_t *, hdr);
5707 				ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5708 			}
5709 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5710 				arc_hdr_clear_flags(hdr,
5711 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5712 			}
5713 
5714 			if (*arc_flags & ARC_FLAG_WAIT) {
5715 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5716 				mutex_exit(hash_lock);
5717 				goto top;
5718 			}
5719 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5720 
5721 			if (done) {
5722 				arc_callback_t *acb = NULL;
5723 
5724 				acb = kmem_zalloc(sizeof (arc_callback_t),
5725 				    KM_SLEEP);
5726 				acb->acb_done = done;
5727 				acb->acb_private = private;
5728 				acb->acb_compressed = compressed_read;
5729 				acb->acb_encrypted = encrypted_read;
5730 				acb->acb_noauth = noauth_read;
5731 				acb->acb_zb = *zb;
5732 				if (pio != NULL)
5733 					acb->acb_zio_dummy = zio_null(pio,
5734 					    spa, NULL, NULL, NULL, zio_flags);
5735 
5736 				ASSERT3P(acb->acb_done, !=, NULL);
5737 				acb->acb_zio_head = head_zio;
5738 				acb->acb_next = hdr->b_l1hdr.b_acb;
5739 				hdr->b_l1hdr.b_acb = acb;
5740 				mutex_exit(hash_lock);
5741 				return (0);
5742 			}
5743 			mutex_exit(hash_lock);
5744 			return (0);
5745 		}
5746 
5747 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5748 		    hdr->b_l1hdr.b_state == arc_mfu);
5749 
5750 		if (done) {
5751 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5752 				/*
5753 				 * This is a demand read which does not have to
5754 				 * wait for i/o because we did a predictive
5755 				 * prefetch i/o for it, which has completed.
5756 				 */
5757 				DTRACE_PROBE1(
5758 				    arc__demand__hit__predictive__prefetch,
5759 				    arc_buf_hdr_t *, hdr);
5760 				ARCSTAT_BUMP(
5761 				    arcstat_demand_hit_predictive_prefetch);
5762 				arc_hdr_clear_flags(hdr,
5763 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5764 			}
5765 
5766 			if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5767 				ARCSTAT_BUMP(
5768 				    arcstat_demand_hit_prescient_prefetch);
5769 				arc_hdr_clear_flags(hdr,
5770 				    ARC_FLAG_PRESCIENT_PREFETCH);
5771 			}
5772 
5773 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5774 
5775 			arc_hdr_verify_checksum(spa, hdr, bp);
5776 
5777 			/* Get a buf with the desired data in it. */
5778 			rc = arc_buf_alloc_impl(hdr, spa, zb, private,
5779 			    encrypted_read, compressed_read, noauth_read,
5780 			    B_TRUE, &buf);
5781 			if (rc == ECKSUM) {
5782 				/*
5783 				 * Convert authentication and decryption errors
5784 				 * to EIO (and generate an ereport if needed)
5785 				 * before leaving the ARC.
5786 				 */
5787 				rc = SET_ERROR(EIO);
5788 				if ((zio_flags & ZIO_FLAG_SPECULATIVE) == 0) {
5789 					spa_log_error(spa, zb);
5790 					(void) zfs_ereport_post(
5791 					    FM_EREPORT_ZFS_AUTHENTICATION,
5792 					    spa, NULL, zb, NULL, 0, 0);
5793 				}
5794 			}
5795 			if (rc != 0) {
5796 				(void) remove_reference(hdr, hash_lock,
5797 				    private);
5798 				arc_buf_destroy_impl(buf);
5799 				buf = NULL;
5800 			}
5801 			/* assert any errors weren't due to unloaded keys */
5802 			ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
5803 			    rc != EACCES);
5804 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
5805 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5806 			if (HDR_HAS_L2HDR(hdr))
5807 				l2arc_hdr_arcstats_decrement_state(hdr);
5808 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5809 			if (HDR_HAS_L2HDR(hdr))
5810 				l2arc_hdr_arcstats_increment_state(hdr);
5811 		}
5812 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5813 		arc_access(hdr, hash_lock);
5814 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5815 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5816 		if (*arc_flags & ARC_FLAG_L2CACHE)
5817 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5818 		mutex_exit(hash_lock);
5819 		ARCSTAT_BUMP(arcstat_hits);
5820 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5821 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5822 		    data, metadata, hits);
5823 
5824 		if (done)
5825 			done(NULL, zb, bp, buf, private);
5826 	} else {
5827 		uint64_t lsize = BP_GET_LSIZE(bp);
5828 		uint64_t psize = BP_GET_PSIZE(bp);
5829 		arc_callback_t *acb;
5830 		vdev_t *vd = NULL;
5831 		uint64_t addr = 0;
5832 		boolean_t devw = B_FALSE;
5833 		uint64_t size;
5834 		abd_t *hdr_abd;
5835 		int alloc_flags = encrypted_read ? ARC_HDR_ALLOC_RDATA : 0;
5836 
5837 		if (hdr == NULL) {
5838 			/* this block is not in the cache */
5839 			arc_buf_hdr_t *exists = NULL;
5840 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5841 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5842 			    BP_IS_PROTECTED(bp), BP_GET_COMPRESS(bp), type,
5843 			    encrypted_read);
5844 
5845 			if (!BP_IS_EMBEDDED(bp)) {
5846 				hdr->b_dva = *BP_IDENTITY(bp);
5847 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5848 				exists = buf_hash_insert(hdr, &hash_lock);
5849 			}
5850 			if (exists != NULL) {
5851 				/* somebody beat us to the hash insert */
5852 				mutex_exit(hash_lock);
5853 				buf_discard_identity(hdr);
5854 				arc_hdr_destroy(hdr);
5855 				goto top; /* restart the IO request */
5856 			}
5857 		} else {
5858 			/*
5859 			 * This block is in the ghost cache or encrypted data
5860 			 * was requested and we didn't have it. If it was
5861 			 * L2-only (and thus didn't have an L1 hdr),
5862 			 * we realloc the header to add an L1 hdr.
5863 			 */
5864 			if (!HDR_HAS_L1HDR(hdr)) {
5865 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5866 				    hdr_full_cache);
5867 			}
5868 
5869 			if (GHOST_STATE(hdr->b_l1hdr.b_state)) {
5870 				ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5871 				ASSERT(!HDR_HAS_RABD(hdr));
5872 				ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5873 				ASSERT0(zfs_refcount_count(
5874 				    &hdr->b_l1hdr.b_refcnt));
5875 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5876 				ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5877 			} else if (HDR_IO_IN_PROGRESS(hdr)) {
5878 				/*
5879 				 * If this header already had an IO in progress
5880 				 * and we are performing another IO to fetch
5881 				 * encrypted data we must wait until the first
5882 				 * IO completes so as not to confuse
5883 				 * arc_read_done(). This should be very rare
5884 				 * and so the performance impact shouldn't
5885 				 * matter.
5886 				 */
5887 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5888 				mutex_exit(hash_lock);
5889 				goto top;
5890 			}
5891 
5892 			/*
5893 			 * This is a delicate dance that we play here.
5894 			 * This hdr might be in the ghost list so we access
5895 			 * it to move it out of the ghost list before we
5896 			 * initiate the read. If it's a prefetch then
5897 			 * it won't have a callback so we'll remove the
5898 			 * reference that arc_buf_alloc_impl() created. We
5899 			 * do this after we've called arc_access() to
5900 			 * avoid hitting an assert in remove_reference().
5901 			 */
5902 			arc_adapt(arc_hdr_size(hdr), hdr->b_l1hdr.b_state);
5903 			arc_access(hdr, hash_lock);
5904 			arc_hdr_alloc_pabd(hdr, alloc_flags);
5905 		}
5906 
5907 		if (encrypted_read) {
5908 			ASSERT(HDR_HAS_RABD(hdr));
5909 			size = HDR_GET_PSIZE(hdr);
5910 			hdr_abd = hdr->b_crypt_hdr.b_rabd;
5911 			zio_flags |= ZIO_FLAG_RAW;
5912 		} else {
5913 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5914 			size = arc_hdr_size(hdr);
5915 			hdr_abd = hdr->b_l1hdr.b_pabd;
5916 
5917 			if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF) {
5918 				zio_flags |= ZIO_FLAG_RAW_COMPRESS;
5919 			}
5920 
5921 			/*
5922 			 * For authenticated bp's, we do not ask the ZIO layer
5923 			 * to authenticate them since this will cause the entire
5924 			 * IO to fail if the key isn't loaded. Instead, we
5925 			 * defer authentication until arc_buf_fill(), which will
5926 			 * verify the data when the key is available.
5927 			 */
5928 			if (BP_IS_AUTHENTICATED(bp))
5929 				zio_flags |= ZIO_FLAG_RAW_ENCRYPT;
5930 		}
5931 
5932 		if (*arc_flags & ARC_FLAG_PREFETCH &&
5933 		    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5934 			if (HDR_HAS_L2HDR(hdr))
5935 				l2arc_hdr_arcstats_decrement_state(hdr);
5936 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5937 			if (HDR_HAS_L2HDR(hdr))
5938 				l2arc_hdr_arcstats_increment_state(hdr);
5939 		}
5940 		if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5941 			arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5942 
5943 		if (*arc_flags & ARC_FLAG_L2CACHE)
5944 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5945 		if (BP_IS_AUTHENTICATED(bp))
5946 			arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
5947 		if (BP_GET_LEVEL(bp) > 0)
5948 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5949 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5950 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5951 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5952 
5953 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5954 		acb->acb_done = done;
5955 		acb->acb_private = private;
5956 		acb->acb_compressed = compressed_read;
5957 		acb->acb_encrypted = encrypted_read;
5958 		acb->acb_noauth = noauth_read;
5959 		acb->acb_zb = *zb;
5960 
5961 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5962 		hdr->b_l1hdr.b_acb = acb;
5963 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5964 
5965 		if (HDR_HAS_L2HDR(hdr) &&
5966 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5967 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5968 			addr = hdr->b_l2hdr.b_daddr;
5969 			/*
5970 			 * Lock out L2ARC device removal.
5971 			 */
5972 			if (vdev_is_dead(vd) ||
5973 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5974 				vd = NULL;
5975 		}
5976 
5977 		/*
5978 		 * We count both async reads and scrub IOs as asynchronous so
5979 		 * that both can be upgraded in the event of a cache hit while
5980 		 * the read IO is still in-flight.
5981 		 */
5982 		if (priority == ZIO_PRIORITY_ASYNC_READ ||
5983 		    priority == ZIO_PRIORITY_SCRUB)
5984 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5985 		else
5986 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5987 
5988 		/*
5989 		 * At this point, we have a level 1 cache miss.  Try again in
5990 		 * L2ARC if possible.
5991 		 */
5992 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5993 
5994 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5995 		    uint64_t, lsize, zbookmark_phys_t *, zb);
5996 		ARCSTAT_BUMP(arcstat_misses);
5997 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5998 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5999 		    data, metadata, misses);
6000 
6001 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
6002 			/*
6003 			 * Read from the L2ARC if the following are true:
6004 			 * 1. The L2ARC vdev was previously cached.
6005 			 * 2. This buffer still has L2ARC metadata.
6006 			 * 3. This buffer isn't currently writing to the L2ARC.
6007 			 * 4. The L2ARC entry wasn't evicted, which may
6008 			 *    also have invalidated the vdev.
6009 			 * 5. This isn't prefetch or l2arc_noprefetch is 0.
6010 			 */
6011 			if (HDR_HAS_L2HDR(hdr) &&
6012 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
6013 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
6014 				l2arc_read_callback_t *cb;
6015 				abd_t *abd;
6016 				uint64_t asize;
6017 
6018 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
6019 				ARCSTAT_BUMP(arcstat_l2_hits);
6020 
6021 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
6022 				    KM_SLEEP);
6023 				cb->l2rcb_hdr = hdr;
6024 				cb->l2rcb_bp = *bp;
6025 				cb->l2rcb_zb = *zb;
6026 				cb->l2rcb_flags = zio_flags;
6027 
6028 				/*
6029 				 * When Compressed ARC is disabled, but the
6030 				 * L2ARC block is compressed, arc_hdr_size()
6031 				 * will have returned LSIZE rather than PSIZE.
6032 				 */
6033 				if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
6034 				    !HDR_COMPRESSION_ENABLED(hdr) &&
6035 				    HDR_GET_PSIZE(hdr) != 0) {
6036 					size = HDR_GET_PSIZE(hdr);
6037 				}
6038 
6039 				asize = vdev_psize_to_asize(vd, size);
6040 				if (asize != size) {
6041 					abd = abd_alloc_for_io(asize,
6042 					    HDR_ISTYPE_METADATA(hdr));
6043 					cb->l2rcb_abd = abd;
6044 				} else {
6045 					abd = hdr_abd;
6046 				}
6047 
6048 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6049 				    addr + asize <= vd->vdev_psize -
6050 				    VDEV_LABEL_END_SIZE);
6051 
6052 				/*
6053 				 * l2arc read.  The SCL_L2ARC lock will be
6054 				 * released by l2arc_read_done().
6055 				 * Issue a null zio if the underlying buffer
6056 				 * was squashed to zero size by compression.
6057 				 */
6058 				ASSERT3U(arc_hdr_get_compress(hdr), !=,
6059 				    ZIO_COMPRESS_EMPTY);
6060 				rzio = zio_read_phys(pio, vd, addr,
6061 				    asize, abd,
6062 				    ZIO_CHECKSUM_OFF,
6063 				    l2arc_read_done, cb, priority,
6064 				    zio_flags | ZIO_FLAG_DONT_CACHE |
6065 				    ZIO_FLAG_CANFAIL |
6066 				    ZIO_FLAG_DONT_PROPAGATE |
6067 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
6068 				acb->acb_zio_head = rzio;
6069 
6070 				if (hash_lock != NULL)
6071 					mutex_exit(hash_lock);
6072 
6073 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6074 				    zio_t *, rzio);
6075 				ARCSTAT_INCR(arcstat_l2_read_bytes,
6076 				    HDR_GET_PSIZE(hdr));
6077 
6078 				if (*arc_flags & ARC_FLAG_NOWAIT) {
6079 					zio_nowait(rzio);
6080 					return (0);
6081 				}
6082 
6083 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
6084 				if (zio_wait(rzio) == 0)
6085 					return (0);
6086 
6087 				/* l2arc read error; goto zio_read() */
6088 				if (hash_lock != NULL)
6089 					mutex_enter(hash_lock);
6090 			} else {
6091 				DTRACE_PROBE1(l2arc__miss,
6092 				    arc_buf_hdr_t *, hdr);
6093 				ARCSTAT_BUMP(arcstat_l2_misses);
6094 				if (HDR_L2_WRITING(hdr))
6095 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
6096 				spa_config_exit(spa, SCL_L2ARC, vd);
6097 			}
6098 		} else {
6099 			if (vd != NULL)
6100 				spa_config_exit(spa, SCL_L2ARC, vd);
6101 			if (l2arc_ndev != 0) {
6102 				DTRACE_PROBE1(l2arc__miss,
6103 				    arc_buf_hdr_t *, hdr);
6104 				ARCSTAT_BUMP(arcstat_l2_misses);
6105 			}
6106 		}
6107 
6108 		rzio = zio_read(pio, spa, bp, hdr_abd, size,
6109 		    arc_read_done, hdr, priority, zio_flags, zb);
6110 		acb->acb_zio_head = rzio;
6111 
6112 		if (hash_lock != NULL)
6113 			mutex_exit(hash_lock);
6114 
6115 		if (*arc_flags & ARC_FLAG_WAIT)
6116 			return (zio_wait(rzio));
6117 
6118 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6119 		zio_nowait(rzio);
6120 	}
6121 	return (rc);
6122 }
6123 
6124 /*
6125  * Notify the arc that a block was freed, and thus will never be used again.
6126  */
6127 void
6128 arc_freed(spa_t *spa, const blkptr_t *bp)
6129 {
6130 	arc_buf_hdr_t *hdr;
6131 	kmutex_t *hash_lock;
6132 	uint64_t guid = spa_load_guid(spa);
6133 
6134 	ASSERT(!BP_IS_EMBEDDED(bp));
6135 
6136 	hdr = buf_hash_find(guid, bp, &hash_lock);
6137 	if (hdr == NULL)
6138 		return;
6139 
6140 	/*
6141 	 * We might be trying to free a block that is still doing I/O
6142 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6143 	 * dmu_sync-ed block). If this block is being prefetched, then it
6144 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6145 	 * until the I/O completes. A block may also have a reference if it is
6146 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6147 	 * have written the new block to its final resting place on disk but
6148 	 * without the dedup flag set. This would have left the hdr in the MRU
6149 	 * state and discoverable. When the txg finally syncs it detects that
6150 	 * the block was overridden in open context and issues an override I/O.
6151 	 * Since this is a dedup block, the override I/O will determine if the
6152 	 * block is already in the DDT. If so, then it will replace the io_bp
6153 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
6154 	 * reaches the done callback, dbuf_write_override_done, it will
6155 	 * check to see if the io_bp and io_bp_override are identical.
6156 	 * If they are not, then it indicates that the bp was replaced with
6157 	 * the bp in the DDT and the override bp is freed. This allows
6158 	 * us to arrive here with a reference on a block that is being
6159 	 * freed. So if we have an I/O in progress, or a reference to
6160 	 * this hdr, then we don't destroy the hdr.
6161 	 */
6162 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6163 	    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6164 		arc_change_state(arc_anon, hdr, hash_lock);
6165 		arc_hdr_destroy(hdr);
6166 		mutex_exit(hash_lock);
6167 	} else {
6168 		mutex_exit(hash_lock);
6169 	}
6170 
6171 }
6172 
6173 /*
6174  * Release this buffer from the cache, making it an anonymous buffer.  This
6175  * must be done after a read and prior to modifying the buffer contents.
6176  * If the buffer has more than one reference, we must make
6177  * a new hdr for the buffer.
6178  */
6179 void
6180 arc_release(arc_buf_t *buf, void *tag)
6181 {
6182 	arc_buf_hdr_t *hdr = buf->b_hdr;
6183 
6184 	/*
6185 	 * It would be nice to assert that if its DMU metadata (level >
6186 	 * 0 || it's the dnode file), then it must be syncing context.
6187 	 * But we don't know that information at this level.
6188 	 */
6189 
6190 	mutex_enter(&buf->b_evict_lock);
6191 
6192 	ASSERT(HDR_HAS_L1HDR(hdr));
6193 
6194 	/*
6195 	 * We don't grab the hash lock prior to this check, because if
6196 	 * the buffer's header is in the arc_anon state, it won't be
6197 	 * linked into the hash table.
6198 	 */
6199 	if (hdr->b_l1hdr.b_state == arc_anon) {
6200 		mutex_exit(&buf->b_evict_lock);
6201 		/*
6202 		 * If we are called from dmu_convert_mdn_block_to_raw(),
6203 		 * a write might be in progress.  This is OK because
6204 		 * the caller won't change the content of this buffer,
6205 		 * only the flags (via arc_convert_to_raw()).
6206 		 */
6207 		/* ASSERT(!HDR_IO_IN_PROGRESS(hdr)); */
6208 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
6209 		ASSERT(!HDR_HAS_L2HDR(hdr));
6210 		ASSERT(HDR_EMPTY(hdr));
6211 
6212 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6213 		ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6214 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6215 
6216 		hdr->b_l1hdr.b_arc_access = 0;
6217 
6218 		/*
6219 		 * If the buf is being overridden then it may already
6220 		 * have a hdr that is not empty.
6221 		 */
6222 		buf_discard_identity(hdr);
6223 		arc_buf_thaw(buf);
6224 
6225 		return;
6226 	}
6227 
6228 	kmutex_t *hash_lock = HDR_LOCK(hdr);
6229 	mutex_enter(hash_lock);
6230 
6231 	/*
6232 	 * This assignment is only valid as long as the hash_lock is
6233 	 * held, we must be careful not to reference state or the
6234 	 * b_state field after dropping the lock.
6235 	 */
6236 	arc_state_t *state = hdr->b_l1hdr.b_state;
6237 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6238 	ASSERT3P(state, !=, arc_anon);
6239 
6240 	/* this buffer is not on any list */
6241 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6242 
6243 	if (HDR_HAS_L2HDR(hdr)) {
6244 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6245 
6246 		/*
6247 		 * We have to recheck this conditional again now that
6248 		 * we're holding the l2ad_mtx to prevent a race with
6249 		 * another thread which might be concurrently calling
6250 		 * l2arc_evict(). In that case, l2arc_evict() might have
6251 		 * destroyed the header's L2 portion as we were waiting
6252 		 * to acquire the l2ad_mtx.
6253 		 */
6254 		if (HDR_HAS_L2HDR(hdr))
6255 			arc_hdr_l2hdr_destroy(hdr);
6256 
6257 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6258 	}
6259 
6260 	/*
6261 	 * Do we have more than one buf?
6262 	 */
6263 	if (hdr->b_l1hdr.b_bufcnt > 1) {
6264 		arc_buf_hdr_t *nhdr;
6265 		uint64_t spa = hdr->b_spa;
6266 		uint64_t psize = HDR_GET_PSIZE(hdr);
6267 		uint64_t lsize = HDR_GET_LSIZE(hdr);
6268 		boolean_t protected = HDR_PROTECTED(hdr);
6269 		enum zio_compress compress = arc_hdr_get_compress(hdr);
6270 		arc_buf_contents_t type = arc_buf_type(hdr);
6271 		VERIFY3U(hdr->b_type, ==, type);
6272 
6273 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6274 		(void) remove_reference(hdr, hash_lock, tag);
6275 
6276 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6277 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6278 			ASSERT(ARC_BUF_LAST(buf));
6279 		}
6280 
6281 		/*
6282 		 * Pull the data off of this hdr and attach it to
6283 		 * a new anonymous hdr. Also find the last buffer
6284 		 * in the hdr's buffer list.
6285 		 */
6286 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6287 		ASSERT3P(lastbuf, !=, NULL);
6288 
6289 		/*
6290 		 * If the current arc_buf_t and the hdr are sharing their data
6291 		 * buffer, then we must stop sharing that block.
6292 		 */
6293 		if (arc_buf_is_shared(buf)) {
6294 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6295 			VERIFY(!arc_buf_is_shared(lastbuf));
6296 
6297 			/*
6298 			 * First, sever the block sharing relationship between
6299 			 * buf and the arc_buf_hdr_t.
6300 			 */
6301 			arc_unshare_buf(hdr, buf);
6302 
6303 			/*
6304 			 * Now we need to recreate the hdr's b_pabd. Since we
6305 			 * have lastbuf handy, we try to share with it, but if
6306 			 * we can't then we allocate a new b_pabd and copy the
6307 			 * data from buf into it.
6308 			 */
6309 			if (arc_can_share(hdr, lastbuf)) {
6310 				arc_share_buf(hdr, lastbuf);
6311 			} else {
6312 				arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT);
6313 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6314 				    buf->b_data, psize);
6315 			}
6316 			VERIFY3P(lastbuf->b_data, !=, NULL);
6317 		} else if (HDR_SHARED_DATA(hdr)) {
6318 			/*
6319 			 * Uncompressed shared buffers are always at the end
6320 			 * of the list. Compressed buffers don't have the
6321 			 * same requirements. This makes it hard to
6322 			 * simply assert that the lastbuf is shared so
6323 			 * we rely on the hdr's compression flags to determine
6324 			 * if we have a compressed, shared buffer.
6325 			 */
6326 			ASSERT(arc_buf_is_shared(lastbuf) ||
6327 			    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
6328 			ASSERT(!ARC_BUF_SHARED(buf));
6329 		}
6330 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
6331 		ASSERT3P(state, !=, arc_l2c_only);
6332 
6333 		(void) zfs_refcount_remove_many(&state->arcs_size,
6334 		    arc_buf_size(buf), buf);
6335 
6336 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6337 			ASSERT3P(state, !=, arc_l2c_only);
6338 			(void) zfs_refcount_remove_many(
6339 			    &state->arcs_esize[type],
6340 			    arc_buf_size(buf), buf);
6341 		}
6342 
6343 		hdr->b_l1hdr.b_bufcnt -= 1;
6344 		if (ARC_BUF_ENCRYPTED(buf))
6345 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
6346 
6347 		arc_cksum_verify(buf);
6348 		arc_buf_unwatch(buf);
6349 
6350 		/* if this is the last uncompressed buf free the checksum */
6351 		if (!arc_hdr_has_uncompressed_buf(hdr))
6352 			arc_cksum_free(hdr);
6353 
6354 		mutex_exit(hash_lock);
6355 
6356 		/*
6357 		 * Allocate a new hdr. The new hdr will contain a b_pabd
6358 		 * buffer which will be freed in arc_write().
6359 		 */
6360 		nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6361 		    compress, type, HDR_HAS_RABD(hdr));
6362 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6363 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6364 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6365 		VERIFY3U(nhdr->b_type, ==, type);
6366 		ASSERT(!HDR_SHARED_DATA(nhdr));
6367 
6368 		nhdr->b_l1hdr.b_buf = buf;
6369 		nhdr->b_l1hdr.b_bufcnt = 1;
6370 		if (ARC_BUF_ENCRYPTED(buf))
6371 			nhdr->b_crypt_hdr.b_ebufcnt = 1;
6372 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6373 		buf->b_hdr = nhdr;
6374 
6375 		mutex_exit(&buf->b_evict_lock);
6376 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
6377 		    arc_buf_size(buf), buf);
6378 	} else {
6379 		mutex_exit(&buf->b_evict_lock);
6380 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6381 		/* protected by hash lock, or hdr is on arc_anon */
6382 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6383 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6384 		arc_change_state(arc_anon, hdr, hash_lock);
6385 		hdr->b_l1hdr.b_arc_access = 0;
6386 
6387 		mutex_exit(hash_lock);
6388 		buf_discard_identity(hdr);
6389 		arc_buf_thaw(buf);
6390 	}
6391 }
6392 
6393 int
6394 arc_released(arc_buf_t *buf)
6395 {
6396 	int released;
6397 
6398 	mutex_enter(&buf->b_evict_lock);
6399 	released = (buf->b_data != NULL &&
6400 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
6401 	mutex_exit(&buf->b_evict_lock);
6402 	return (released);
6403 }
6404 
6405 #ifdef ZFS_DEBUG
6406 int
6407 arc_referenced(arc_buf_t *buf)
6408 {
6409 	int referenced;
6410 
6411 	mutex_enter(&buf->b_evict_lock);
6412 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6413 	mutex_exit(&buf->b_evict_lock);
6414 	return (referenced);
6415 }
6416 #endif
6417 
6418 static void
6419 arc_write_ready(zio_t *zio)
6420 {
6421 	arc_write_callback_t *callback = zio->io_private;
6422 	arc_buf_t *buf = callback->awcb_buf;
6423 	arc_buf_hdr_t *hdr = buf->b_hdr;
6424 	blkptr_t *bp = zio->io_bp;
6425 	uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6426 
6427 	ASSERT(HDR_HAS_L1HDR(hdr));
6428 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6429 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6430 
6431 	/*
6432 	 * If we're reexecuting this zio because the pool suspended, then
6433 	 * cleanup any state that was previously set the first time the
6434 	 * callback was invoked.
6435 	 */
6436 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6437 		arc_cksum_free(hdr);
6438 		arc_buf_unwatch(buf);
6439 		if (hdr->b_l1hdr.b_pabd != NULL) {
6440 			if (arc_buf_is_shared(buf)) {
6441 				arc_unshare_buf(hdr, buf);
6442 			} else {
6443 				arc_hdr_free_pabd(hdr, B_FALSE);
6444 			}
6445 		}
6446 
6447 		if (HDR_HAS_RABD(hdr))
6448 			arc_hdr_free_pabd(hdr, B_TRUE);
6449 	}
6450 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6451 	ASSERT(!HDR_HAS_RABD(hdr));
6452 	ASSERT(!HDR_SHARED_DATA(hdr));
6453 	ASSERT(!arc_buf_is_shared(buf));
6454 
6455 	callback->awcb_ready(zio, buf, callback->awcb_private);
6456 
6457 	if (HDR_IO_IN_PROGRESS(hdr))
6458 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6459 
6460 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6461 
6462 	if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6463 		hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6464 
6465 	if (BP_IS_PROTECTED(bp)) {
6466 		/* ZIL blocks are written through zio_rewrite */
6467 		ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6468 		ASSERT(HDR_PROTECTED(hdr));
6469 
6470 		if (BP_SHOULD_BYTESWAP(bp)) {
6471 			if (BP_GET_LEVEL(bp) > 0) {
6472 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6473 			} else {
6474 				hdr->b_l1hdr.b_byteswap =
6475 				    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6476 			}
6477 		} else {
6478 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6479 		}
6480 
6481 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6482 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6483 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6484 		    hdr->b_crypt_hdr.b_iv);
6485 		zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6486 	}
6487 
6488 	/*
6489 	 * If this block was written for raw encryption but the zio layer
6490 	 * ended up only authenticating it, adjust the buffer flags now.
6491 	 */
6492 	if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6493 		arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6494 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6495 		if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6496 			buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6497 	} else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6498 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6499 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6500 	}
6501 
6502 	/* this must be done after the buffer flags are adjusted */
6503 	arc_cksum_compute(buf);
6504 
6505 	enum zio_compress compress;
6506 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6507 		compress = ZIO_COMPRESS_OFF;
6508 	} else {
6509 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6510 		compress = BP_GET_COMPRESS(bp);
6511 	}
6512 	HDR_SET_PSIZE(hdr, psize);
6513 	arc_hdr_set_compress(hdr, compress);
6514 
6515 	if (zio->io_error != 0 || psize == 0)
6516 		goto out;
6517 
6518 	/*
6519 	 * Fill the hdr with data. If the buffer is encrypted we have no choice
6520 	 * but to copy the data into b_rabd. If the hdr is compressed, the data
6521 	 * we want is available from the zio, otherwise we can take it from
6522 	 * the buf.
6523 	 *
6524 	 * We might be able to share the buf's data with the hdr here. However,
6525 	 * doing so would cause the ARC to be full of linear ABDs if we write a
6526 	 * lot of shareable data. As a compromise, we check whether scattered
6527 	 * ABDs are allowed, and assume that if they are then the user wants
6528 	 * the ARC to be primarily filled with them regardless of the data being
6529 	 * written. Therefore, if they're allowed then we allocate one and copy
6530 	 * the data into it; otherwise, we share the data directly if we can.
6531 	 */
6532 	if (ARC_BUF_ENCRYPTED(buf)) {
6533 		ASSERT3U(psize, >, 0);
6534 		ASSERT(ARC_BUF_COMPRESSED(buf));
6535 		arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6536 		abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6537 	} else if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6538 		/*
6539 		 * Ideally, we would always copy the io_abd into b_pabd, but the
6540 		 * user may have disabled compressed ARC, thus we must check the
6541 		 * hdr's compression setting rather than the io_bp's.
6542 		 */
6543 		if (BP_IS_ENCRYPTED(bp)) {
6544 			ASSERT3U(psize, >, 0);
6545 			arc_hdr_alloc_pabd(hdr,
6546 			    ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6547 			abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6548 		} else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6549 		    !ARC_BUF_COMPRESSED(buf)) {
6550 			ASSERT3U(psize, >, 0);
6551 			arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT);
6552 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6553 		} else {
6554 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6555 			arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT);
6556 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6557 			    arc_buf_size(buf));
6558 		}
6559 	} else {
6560 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6561 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6562 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6563 		arc_share_buf(hdr, buf);
6564 	}
6565 
6566 out:
6567 	arc_hdr_verify(hdr, bp);
6568 }
6569 
6570 static void
6571 arc_write_children_ready(zio_t *zio)
6572 {
6573 	arc_write_callback_t *callback = zio->io_private;
6574 	arc_buf_t *buf = callback->awcb_buf;
6575 
6576 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
6577 }
6578 
6579 /*
6580  * The SPA calls this callback for each physical write that happens on behalf
6581  * of a logical write.  See the comment in dbuf_write_physdone() for details.
6582  */
6583 static void
6584 arc_write_physdone(zio_t *zio)
6585 {
6586 	arc_write_callback_t *cb = zio->io_private;
6587 	if (cb->awcb_physdone != NULL)
6588 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6589 }
6590 
6591 static void
6592 arc_write_done(zio_t *zio)
6593 {
6594 	arc_write_callback_t *callback = zio->io_private;
6595 	arc_buf_t *buf = callback->awcb_buf;
6596 	arc_buf_hdr_t *hdr = buf->b_hdr;
6597 
6598 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6599 
6600 	if (zio->io_error == 0) {
6601 		arc_hdr_verify(hdr, zio->io_bp);
6602 
6603 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6604 			buf_discard_identity(hdr);
6605 		} else {
6606 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6607 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6608 		}
6609 	} else {
6610 		ASSERT(HDR_EMPTY(hdr));
6611 	}
6612 
6613 	/*
6614 	 * If the block to be written was all-zero or compressed enough to be
6615 	 * embedded in the BP, no write was performed so there will be no
6616 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
6617 	 * (and uncached).
6618 	 */
6619 	if (!HDR_EMPTY(hdr)) {
6620 		arc_buf_hdr_t *exists;
6621 		kmutex_t *hash_lock;
6622 
6623 		ASSERT3U(zio->io_error, ==, 0);
6624 
6625 		arc_cksum_verify(buf);
6626 
6627 		exists = buf_hash_insert(hdr, &hash_lock);
6628 		if (exists != NULL) {
6629 			/*
6630 			 * This can only happen if we overwrite for
6631 			 * sync-to-convergence, because we remove
6632 			 * buffers from the hash table when we arc_free().
6633 			 */
6634 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6635 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6636 					panic("bad overwrite, hdr=%p exists=%p",
6637 					    (void *)hdr, (void *)exists);
6638 				ASSERT(zfs_refcount_is_zero(
6639 				    &exists->b_l1hdr.b_refcnt));
6640 				arc_change_state(arc_anon, exists, hash_lock);
6641 				arc_hdr_destroy(exists);
6642 				mutex_exit(hash_lock);
6643 				exists = buf_hash_insert(hdr, &hash_lock);
6644 				ASSERT3P(exists, ==, NULL);
6645 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6646 				/* nopwrite */
6647 				ASSERT(zio->io_prop.zp_nopwrite);
6648 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6649 					panic("bad nopwrite, hdr=%p exists=%p",
6650 					    (void *)hdr, (void *)exists);
6651 			} else {
6652 				/* Dedup */
6653 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6654 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6655 				ASSERT(BP_GET_DEDUP(zio->io_bp));
6656 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6657 			}
6658 		}
6659 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6660 		/* if it's not anon, we are doing a scrub */
6661 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6662 			arc_access(hdr, hash_lock);
6663 		mutex_exit(hash_lock);
6664 	} else {
6665 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6666 	}
6667 
6668 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6669 	callback->awcb_done(zio, buf, callback->awcb_private);
6670 
6671 	abd_put(zio->io_abd);
6672 	kmem_free(callback, sizeof (arc_write_callback_t));
6673 }
6674 
6675 zio_t *
6676 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6677     boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6678     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6679     arc_write_done_func_t *done, void *private, zio_priority_t priority,
6680     int zio_flags, const zbookmark_phys_t *zb)
6681 {
6682 	arc_buf_hdr_t *hdr = buf->b_hdr;
6683 	arc_write_callback_t *callback;
6684 	zio_t *zio;
6685 	zio_prop_t localprop = *zp;
6686 
6687 	ASSERT3P(ready, !=, NULL);
6688 	ASSERT3P(done, !=, NULL);
6689 	ASSERT(!HDR_IO_ERROR(hdr));
6690 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6691 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6692 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6693 	if (l2arc)
6694 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6695 
6696 	if (ARC_BUF_ENCRYPTED(buf)) {
6697 		ASSERT(ARC_BUF_COMPRESSED(buf));
6698 		localprop.zp_encrypt = B_TRUE;
6699 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6700 		/* CONSTCOND */
6701 		localprop.zp_byteorder =
6702 		    (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
6703 		    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
6704 		bcopy(hdr->b_crypt_hdr.b_salt, localprop.zp_salt,
6705 		    ZIO_DATA_SALT_LEN);
6706 		bcopy(hdr->b_crypt_hdr.b_iv, localprop.zp_iv,
6707 		    ZIO_DATA_IV_LEN);
6708 		bcopy(hdr->b_crypt_hdr.b_mac, localprop.zp_mac,
6709 		    ZIO_DATA_MAC_LEN);
6710 		if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
6711 			localprop.zp_nopwrite = B_FALSE;
6712 			localprop.zp_copies =
6713 			    MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
6714 		}
6715 		zio_flags |= ZIO_FLAG_RAW;
6716 	} else if (ARC_BUF_COMPRESSED(buf)) {
6717 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6718 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6719 		zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6720 	}
6721 
6722 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6723 	callback->awcb_ready = ready;
6724 	callback->awcb_children_ready = children_ready;
6725 	callback->awcb_physdone = physdone;
6726 	callback->awcb_done = done;
6727 	callback->awcb_private = private;
6728 	callback->awcb_buf = buf;
6729 
6730 	/*
6731 	 * The hdr's b_pabd is now stale, free it now. A new data block
6732 	 * will be allocated when the zio pipeline calls arc_write_ready().
6733 	 */
6734 	if (hdr->b_l1hdr.b_pabd != NULL) {
6735 		/*
6736 		 * If the buf is currently sharing the data block with
6737 		 * the hdr then we need to break that relationship here.
6738 		 * The hdr will remain with a NULL data pointer and the
6739 		 * buf will take sole ownership of the block.
6740 		 */
6741 		if (arc_buf_is_shared(buf)) {
6742 			arc_unshare_buf(hdr, buf);
6743 		} else {
6744 			arc_hdr_free_pabd(hdr, B_FALSE);
6745 		}
6746 		VERIFY3P(buf->b_data, !=, NULL);
6747 	}
6748 
6749 	if (HDR_HAS_RABD(hdr))
6750 		arc_hdr_free_pabd(hdr, B_TRUE);
6751 
6752 	if (!(zio_flags & ZIO_FLAG_RAW))
6753 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6754 
6755 	ASSERT(!arc_buf_is_shared(buf));
6756 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6757 
6758 	zio = zio_write(pio, spa, txg, bp,
6759 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6760 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6761 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
6762 	    arc_write_physdone, arc_write_done, callback,
6763 	    priority, zio_flags, zb);
6764 
6765 	return (zio);
6766 }
6767 
6768 static int
6769 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
6770 {
6771 #ifdef _KERNEL
6772 	uint64_t available_memory = ptob(freemem);
6773 
6774 
6775 	if (freemem > physmem * arc_lotsfree_percent / 100)
6776 		return (0);
6777 
6778 	if (txg > spa->spa_lowmem_last_txg) {
6779 		spa->spa_lowmem_last_txg = txg;
6780 		spa->spa_lowmem_page_load = 0;
6781 	}
6782 	/*
6783 	 * If we are in pageout, we know that memory is already tight,
6784 	 * the arc is already going to be evicting, so we just want to
6785 	 * continue to let page writes occur as quickly as possible.
6786 	 */
6787 	if (curproc == proc_pageout) {
6788 		if (spa->spa_lowmem_page_load >
6789 		    MAX(ptob(minfree), available_memory) / 4)
6790 			return (SET_ERROR(ERESTART));
6791 		/* Note: reserve is inflated, so we deflate */
6792 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
6793 		return (0);
6794 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
6795 		/* memory is low, delay before restarting */
6796 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6797 		return (SET_ERROR(EAGAIN));
6798 	}
6799 	spa->spa_lowmem_page_load = 0;
6800 #endif /* _KERNEL */
6801 	return (0);
6802 }
6803 
6804 void
6805 arc_tempreserve_clear(uint64_t reserve)
6806 {
6807 	atomic_add_64(&arc_tempreserve, -reserve);
6808 	ASSERT((int64_t)arc_tempreserve >= 0);
6809 }
6810 
6811 int
6812 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
6813 {
6814 	int error;
6815 	uint64_t anon_size;
6816 
6817 	if (reserve > arc_c/4 && !arc_no_grow)
6818 		arc_c = MIN(arc_c_max, reserve * 4);
6819 	if (reserve > arc_c)
6820 		return (SET_ERROR(ENOMEM));
6821 
6822 	/*
6823 	 * Don't count loaned bufs as in flight dirty data to prevent long
6824 	 * network delays from blocking transactions that are ready to be
6825 	 * assigned to a txg.
6826 	 */
6827 
6828 	/* assert that it has not wrapped around */
6829 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6830 
6831 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
6832 	    arc_loaned_bytes), 0);
6833 
6834 	/*
6835 	 * Writes will, almost always, require additional memory allocations
6836 	 * in order to compress/encrypt/etc the data.  We therefore need to
6837 	 * make sure that there is sufficient available memory for this.
6838 	 */
6839 	error = arc_memory_throttle(spa, reserve, txg);
6840 	if (error != 0)
6841 		return (error);
6842 
6843 	/*
6844 	 * Throttle writes when the amount of dirty data in the cache
6845 	 * gets too large.  We try to keep the cache less than half full
6846 	 * of dirty blocks so that our sync times don't grow too large.
6847 	 *
6848 	 * In the case of one pool being built on another pool, we want
6849 	 * to make sure we don't end up throttling the lower (backing)
6850 	 * pool when the upper pool is the majority contributor to dirty
6851 	 * data. To insure we make forward progress during throttling, we
6852 	 * also check the current pool's net dirty data and only throttle
6853 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6854 	 * data in the cache.
6855 	 *
6856 	 * Note: if two requests come in concurrently, we might let them
6857 	 * both succeed, when one of them should fail.  Not a huge deal.
6858 	 */
6859 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6860 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
6861 
6862 	if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
6863 	    anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
6864 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
6865 		uint64_t meta_esize =
6866 		    zfs_refcount_count(
6867 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6868 		uint64_t data_esize =
6869 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6870 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6871 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6872 		    arc_tempreserve >> 10, meta_esize >> 10,
6873 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
6874 		return (SET_ERROR(ERESTART));
6875 	}
6876 	atomic_add_64(&arc_tempreserve, reserve);
6877 	return (0);
6878 }
6879 
6880 static void
6881 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6882     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6883 {
6884 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
6885 	evict_data->value.ui64 =
6886 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6887 	evict_metadata->value.ui64 =
6888 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6889 }
6890 
6891 static int
6892 arc_kstat_update(kstat_t *ksp, int rw)
6893 {
6894 	arc_stats_t *as = ksp->ks_data;
6895 
6896 	if (rw == KSTAT_WRITE) {
6897 		return (EACCES);
6898 	} else {
6899 		arc_kstat_update_state(arc_anon,
6900 		    &as->arcstat_anon_size,
6901 		    &as->arcstat_anon_evictable_data,
6902 		    &as->arcstat_anon_evictable_metadata);
6903 		arc_kstat_update_state(arc_mru,
6904 		    &as->arcstat_mru_size,
6905 		    &as->arcstat_mru_evictable_data,
6906 		    &as->arcstat_mru_evictable_metadata);
6907 		arc_kstat_update_state(arc_mru_ghost,
6908 		    &as->arcstat_mru_ghost_size,
6909 		    &as->arcstat_mru_ghost_evictable_data,
6910 		    &as->arcstat_mru_ghost_evictable_metadata);
6911 		arc_kstat_update_state(arc_mfu,
6912 		    &as->arcstat_mfu_size,
6913 		    &as->arcstat_mfu_evictable_data,
6914 		    &as->arcstat_mfu_evictable_metadata);
6915 		arc_kstat_update_state(arc_mfu_ghost,
6916 		    &as->arcstat_mfu_ghost_size,
6917 		    &as->arcstat_mfu_ghost_evictable_data,
6918 		    &as->arcstat_mfu_ghost_evictable_metadata);
6919 
6920 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6921 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6922 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6923 		ARCSTAT(arcstat_metadata_size) =
6924 		    aggsum_value(&astat_metadata_size);
6925 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6926 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
6927 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6928 	}
6929 
6930 	return (0);
6931 }
6932 
6933 /*
6934  * This function *must* return indices evenly distributed between all
6935  * sublists of the multilist. This is needed due to how the ARC eviction
6936  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6937  * distributed between all sublists and uses this assumption when
6938  * deciding which sublist to evict from and how much to evict from it.
6939  */
6940 unsigned int
6941 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6942 {
6943 	arc_buf_hdr_t *hdr = obj;
6944 
6945 	/*
6946 	 * We rely on b_dva to generate evenly distributed index
6947 	 * numbers using buf_hash below. So, as an added precaution,
6948 	 * let's make sure we never add empty buffers to the arc lists.
6949 	 */
6950 	ASSERT(!HDR_EMPTY(hdr));
6951 
6952 	/*
6953 	 * The assumption here, is the hash value for a given
6954 	 * arc_buf_hdr_t will remain constant throughout its lifetime
6955 	 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
6956 	 * Thus, we don't need to store the header's sublist index
6957 	 * on insertion, as this index can be recalculated on removal.
6958 	 *
6959 	 * Also, the low order bits of the hash value are thought to be
6960 	 * distributed evenly. Otherwise, in the case that the multilist
6961 	 * has a power of two number of sublists, each sublists' usage
6962 	 * would not be evenly distributed.
6963 	 */
6964 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6965 	    multilist_get_num_sublists(ml));
6966 }
6967 
6968 static void
6969 arc_state_init(void)
6970 {
6971 	arc_anon = &ARC_anon;
6972 	arc_mru = &ARC_mru;
6973 	arc_mru_ghost = &ARC_mru_ghost;
6974 	arc_mfu = &ARC_mfu;
6975 	arc_mfu_ghost = &ARC_mfu_ghost;
6976 	arc_l2c_only = &ARC_l2c_only;
6977 
6978 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
6979 	    multilist_create(sizeof (arc_buf_hdr_t),
6980 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6981 	    arc_state_multilist_index_func);
6982 	arc_mru->arcs_list[ARC_BUFC_DATA] =
6983 	    multilist_create(sizeof (arc_buf_hdr_t),
6984 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6985 	    arc_state_multilist_index_func);
6986 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6987 	    multilist_create(sizeof (arc_buf_hdr_t),
6988 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6989 	    arc_state_multilist_index_func);
6990 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6991 	    multilist_create(sizeof (arc_buf_hdr_t),
6992 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6993 	    arc_state_multilist_index_func);
6994 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6995 	    multilist_create(sizeof (arc_buf_hdr_t),
6996 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6997 	    arc_state_multilist_index_func);
6998 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
6999 	    multilist_create(sizeof (arc_buf_hdr_t),
7000 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7001 	    arc_state_multilist_index_func);
7002 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
7003 	    multilist_create(sizeof (arc_buf_hdr_t),
7004 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7005 	    arc_state_multilist_index_func);
7006 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
7007 	    multilist_create(sizeof (arc_buf_hdr_t),
7008 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7009 	    arc_state_multilist_index_func);
7010 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
7011 	    multilist_create(sizeof (arc_buf_hdr_t),
7012 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7013 	    arc_state_multilist_index_func);
7014 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
7015 	    multilist_create(sizeof (arc_buf_hdr_t),
7016 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
7017 	    arc_state_multilist_index_func);
7018 
7019 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7020 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7021 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7022 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7023 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7024 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7025 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7026 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7027 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7028 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7029 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7030 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7031 
7032 	zfs_refcount_create(&arc_anon->arcs_size);
7033 	zfs_refcount_create(&arc_mru->arcs_size);
7034 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
7035 	zfs_refcount_create(&arc_mfu->arcs_size);
7036 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7037 	zfs_refcount_create(&arc_l2c_only->arcs_size);
7038 
7039 	aggsum_init(&arc_meta_used, 0);
7040 	aggsum_init(&arc_size, 0);
7041 	aggsum_init(&astat_data_size, 0);
7042 	aggsum_init(&astat_metadata_size, 0);
7043 	aggsum_init(&astat_hdr_size, 0);
7044 	aggsum_init(&astat_other_size, 0);
7045 	aggsum_init(&astat_l2_hdr_size, 0);
7046 
7047 	arc_anon->arcs_state = ARC_STATE_ANON;
7048 	arc_mru->arcs_state = ARC_STATE_MRU;
7049 	arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7050 	arc_mfu->arcs_state = ARC_STATE_MFU;
7051 	arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7052 	arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
7053 }
7054 
7055 static void
7056 arc_state_fini(void)
7057 {
7058 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7059 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7060 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7061 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7062 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7063 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7064 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7065 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7066 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7067 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7068 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7069 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7070 
7071 	zfs_refcount_destroy(&arc_anon->arcs_size);
7072 	zfs_refcount_destroy(&arc_mru->arcs_size);
7073 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7074 	zfs_refcount_destroy(&arc_mfu->arcs_size);
7075 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7076 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7077 
7078 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
7079 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7080 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7081 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7082 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
7083 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7084 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
7085 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7086 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7087 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
7088 
7089 	aggsum_fini(&arc_meta_used);
7090 	aggsum_fini(&arc_size);
7091 	aggsum_fini(&astat_data_size);
7092 	aggsum_fini(&astat_metadata_size);
7093 	aggsum_fini(&astat_hdr_size);
7094 	aggsum_fini(&astat_other_size);
7095 	aggsum_fini(&astat_l2_hdr_size);
7096 
7097 }
7098 
7099 uint64_t
7100 arc_max_bytes(void)
7101 {
7102 	return (arc_c_max);
7103 }
7104 
7105 void
7106 arc_init(void)
7107 {
7108 	/*
7109 	 * allmem is "all memory that we could possibly use".
7110 	 */
7111 #ifdef _KERNEL
7112 	uint64_t allmem = ptob(physmem - swapfs_minfree);
7113 #else
7114 	uint64_t allmem = (physmem * PAGESIZE) / 2;
7115 #endif
7116 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
7117 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
7118 
7119 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
7120 	arc_c_min = MAX(allmem / 32, 64 << 20);
7121 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
7122 	if (allmem >= 1 << 30)
7123 		arc_c_max = allmem - (1 << 30);
7124 	else
7125 		arc_c_max = arc_c_min;
7126 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
7127 
7128 	/*
7129 	 * In userland, there's only the memory pressure that we artificially
7130 	 * create (see arc_available_memory()).  Don't let arc_c get too
7131 	 * small, because it can cause transactions to be larger than
7132 	 * arc_c, causing arc_tempreserve_space() to fail.
7133 	 */
7134 #ifndef _KERNEL
7135 	arc_c_min = arc_c_max / 2;
7136 #endif
7137 
7138 	/*
7139 	 * Allow the tunables to override our calculations if they are
7140 	 * reasonable (ie. over 64MB)
7141 	 */
7142 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
7143 		arc_c_max = zfs_arc_max;
7144 		arc_c_min = MIN(arc_c_min, arc_c_max);
7145 	}
7146 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
7147 		arc_c_min = zfs_arc_min;
7148 
7149 	arc_c = arc_c_max;
7150 	arc_p = (arc_c >> 1);
7151 
7152 	/* limit meta-data to 1/4 of the arc capacity */
7153 	arc_meta_limit = arc_c_max / 4;
7154 
7155 #ifdef _KERNEL
7156 	/*
7157 	 * Metadata is stored in the kernel's heap.  Don't let us
7158 	 * use more than half the heap for the ARC.
7159 	 */
7160 	arc_meta_limit = MIN(arc_meta_limit,
7161 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
7162 #endif
7163 
7164 	/* Allow the tunable to override if it is reasonable */
7165 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
7166 		arc_meta_limit = zfs_arc_meta_limit;
7167 
7168 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
7169 		arc_c_min = arc_meta_limit / 2;
7170 
7171 	if (zfs_arc_meta_min > 0) {
7172 		arc_meta_min = zfs_arc_meta_min;
7173 	} else {
7174 		arc_meta_min = arc_c_min / 2;
7175 	}
7176 
7177 	if (zfs_arc_grow_retry > 0)
7178 		arc_grow_retry = zfs_arc_grow_retry;
7179 
7180 	if (zfs_arc_shrink_shift > 0)
7181 		arc_shrink_shift = zfs_arc_shrink_shift;
7182 
7183 	/*
7184 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
7185 	 */
7186 	if (arc_no_grow_shift >= arc_shrink_shift)
7187 		arc_no_grow_shift = arc_shrink_shift - 1;
7188 
7189 	if (zfs_arc_p_min_shift > 0)
7190 		arc_p_min_shift = zfs_arc_p_min_shift;
7191 
7192 	/* if kmem_flags are set, lets try to use less memory */
7193 	if (kmem_debugging())
7194 		arc_c = arc_c / 2;
7195 	if (arc_c < arc_c_min)
7196 		arc_c = arc_c_min;
7197 
7198 	arc_state_init();
7199 
7200 	/*
7201 	 * The arc must be "uninitialized", so that hdr_recl() (which is
7202 	 * registered by buf_init()) will not access arc_reap_zthr before
7203 	 * it is created.
7204 	 */
7205 	ASSERT(!arc_initialized);
7206 	buf_init();
7207 
7208 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7209 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7210 
7211 	if (arc_ksp != NULL) {
7212 		arc_ksp->ks_data = &arc_stats;
7213 		arc_ksp->ks_update = arc_kstat_update;
7214 		kstat_install(arc_ksp);
7215 	}
7216 
7217 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
7218 	    arc_adjust_cb, NULL);
7219 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
7220 	    arc_reap_cb, NULL, SEC2NSEC(1));
7221 
7222 	arc_initialized = B_TRUE;
7223 	arc_warm = B_FALSE;
7224 
7225 	/*
7226 	 * Calculate maximum amount of dirty data per pool.
7227 	 *
7228 	 * If it has been set by /etc/system, take that.
7229 	 * Otherwise, use a percentage of physical memory defined by
7230 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
7231 	 * zfs_dirty_data_max_max (default 4GB).
7232 	 */
7233 	if (zfs_dirty_data_max == 0) {
7234 		zfs_dirty_data_max = physmem * PAGESIZE *
7235 		    zfs_dirty_data_max_percent / 100;
7236 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7237 		    zfs_dirty_data_max_max);
7238 	}
7239 }
7240 
7241 void
7242 arc_fini(void)
7243 {
7244 	/* Use B_TRUE to ensure *all* buffers are evicted */
7245 	arc_flush(NULL, B_TRUE);
7246 
7247 	arc_initialized = B_FALSE;
7248 
7249 	if (arc_ksp != NULL) {
7250 		kstat_delete(arc_ksp);
7251 		arc_ksp = NULL;
7252 	}
7253 
7254 	(void) zthr_cancel(arc_adjust_zthr);
7255 	zthr_destroy(arc_adjust_zthr);
7256 
7257 	(void) zthr_cancel(arc_reap_zthr);
7258 	zthr_destroy(arc_reap_zthr);
7259 
7260 	mutex_destroy(&arc_adjust_lock);
7261 	cv_destroy(&arc_adjust_waiters_cv);
7262 
7263 	/*
7264 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
7265 	 * trigger the release of kmem magazines, which can callback to
7266 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
7267 	 */
7268 	buf_fini();
7269 	arc_state_fini();
7270 
7271 	ASSERT0(arc_loaned_bytes);
7272 }
7273 
7274 /*
7275  * Level 2 ARC
7276  *
7277  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7278  * It uses dedicated storage devices to hold cached data, which are populated
7279  * using large infrequent writes.  The main role of this cache is to boost
7280  * the performance of random read workloads.  The intended L2ARC devices
7281  * include short-stroked disks, solid state disks, and other media with
7282  * substantially faster read latency than disk.
7283  *
7284  *                 +-----------------------+
7285  *                 |         ARC           |
7286  *                 +-----------------------+
7287  *                    |         ^     ^
7288  *                    |         |     |
7289  *      l2arc_feed_thread()    arc_read()
7290  *                    |         |     |
7291  *                    |  l2arc read   |
7292  *                    V         |     |
7293  *               +---------------+    |
7294  *               |     L2ARC     |    |
7295  *               +---------------+    |
7296  *                   |    ^           |
7297  *          l2arc_write() |           |
7298  *                   |    |           |
7299  *                   V    |           |
7300  *                 +-------+      +-------+
7301  *                 | vdev  |      | vdev  |
7302  *                 | cache |      | cache |
7303  *                 +-------+      +-------+
7304  *                 +=========+     .-----.
7305  *                 :  L2ARC  :    |-_____-|
7306  *                 : devices :    | Disks |
7307  *                 +=========+    `-_____-'
7308  *
7309  * Read requests are satisfied from the following sources, in order:
7310  *
7311  *	1) ARC
7312  *	2) vdev cache of L2ARC devices
7313  *	3) L2ARC devices
7314  *	4) vdev cache of disks
7315  *	5) disks
7316  *
7317  * Some L2ARC device types exhibit extremely slow write performance.
7318  * To accommodate for this there are some significant differences between
7319  * the L2ARC and traditional cache design:
7320  *
7321  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
7322  * the ARC behave as usual, freeing buffers and placing headers on ghost
7323  * lists.  The ARC does not send buffers to the L2ARC during eviction as
7324  * this would add inflated write latencies for all ARC memory pressure.
7325  *
7326  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7327  * It does this by periodically scanning buffers from the eviction-end of
7328  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7329  * not already there. It scans until a headroom of buffers is satisfied,
7330  * which itself is a buffer for ARC eviction. If a compressible buffer is
7331  * found during scanning and selected for writing to an L2ARC device, we
7332  * temporarily boost scanning headroom during the next scan cycle to make
7333  * sure we adapt to compression effects (which might significantly reduce
7334  * the data volume we write to L2ARC). The thread that does this is
7335  * l2arc_feed_thread(), illustrated below; example sizes are included to
7336  * provide a better sense of ratio than this diagram:
7337  *
7338  *	       head -->                        tail
7339  *	        +---------------------+----------+
7340  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
7341  *	        +---------------------+----------+   |   o L2ARC eligible
7342  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
7343  *	        +---------------------+----------+   |
7344  *	             15.9 Gbytes      ^ 32 Mbytes    |
7345  *	                           headroom          |
7346  *	                                      l2arc_feed_thread()
7347  *	                                             |
7348  *	                 l2arc write hand <--[oooo]--'
7349  *	                         |           8 Mbyte
7350  *	                         |          write max
7351  *	                         V
7352  *		  +==============================+
7353  *	L2ARC dev |####|#|###|###|    |####| ... |
7354  *	          +==============================+
7355  *	                     32 Gbytes
7356  *
7357  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7358  * evicted, then the L2ARC has cached a buffer much sooner than it probably
7359  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
7360  * safe to say that this is an uncommon case, since buffers at the end of
7361  * the ARC lists have moved there due to inactivity.
7362  *
7363  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7364  * then the L2ARC simply misses copying some buffers.  This serves as a
7365  * pressure valve to prevent heavy read workloads from both stalling the ARC
7366  * with waits and clogging the L2ARC with writes.  This also helps prevent
7367  * the potential for the L2ARC to churn if it attempts to cache content too
7368  * quickly, such as during backups of the entire pool.
7369  *
7370  * 5. After system boot and before the ARC has filled main memory, there are
7371  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7372  * lists can remain mostly static.  Instead of searching from tail of these
7373  * lists as pictured, the l2arc_feed_thread() will search from the list heads
7374  * for eligible buffers, greatly increasing its chance of finding them.
7375  *
7376  * The L2ARC device write speed is also boosted during this time so that
7377  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
7378  * there are no L2ARC reads, and no fear of degrading read performance
7379  * through increased writes.
7380  *
7381  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7382  * the vdev queue can aggregate them into larger and fewer writes.  Each
7383  * device is written to in a rotor fashion, sweeping writes through
7384  * available space then repeating.
7385  *
7386  * 7. The L2ARC does not store dirty content.  It never needs to flush
7387  * write buffers back to disk based storage.
7388  *
7389  * 8. If an ARC buffer is written (and dirtied) which also exists in the
7390  * L2ARC, the now stale L2ARC buffer is immediately dropped.
7391  *
7392  * The performance of the L2ARC can be tweaked by a number of tunables, which
7393  * may be necessary for different workloads:
7394  *
7395  *	l2arc_write_max		max write bytes per interval
7396  *	l2arc_write_boost	extra write bytes during device warmup
7397  *	l2arc_noprefetch	skip caching prefetched buffers
7398  *	l2arc_headroom		number of max device writes to precache
7399  *	l2arc_headroom_boost	when we find compressed buffers during ARC
7400  *				scanning, we multiply headroom by this
7401  *				percentage factor for the next scan cycle,
7402  *				since more compressed buffers are likely to
7403  *				be present
7404  *	l2arc_feed_secs		seconds between L2ARC writing
7405  *
7406  * Tunables may be removed or added as future performance improvements are
7407  * integrated, and also may become zpool properties.
7408  *
7409  * There are three key functions that control how the L2ARC warms up:
7410  *
7411  *	l2arc_write_eligible()	check if a buffer is eligible to cache
7412  *	l2arc_write_size()	calculate how much to write
7413  *	l2arc_write_interval()	calculate sleep delay between writes
7414  *
7415  * These three functions determine what to write, how much, and how quickly
7416  * to send writes.
7417  *
7418  * L2ARC persistence:
7419  *
7420  * When writing buffers to L2ARC, we periodically add some metadata to
7421  * make sure we can pick them up after reboot, thus dramatically reducing
7422  * the impact that any downtime has on the performance of storage systems
7423  * with large caches.
7424  *
7425  * The implementation works fairly simply by integrating the following two
7426  * modifications:
7427  *
7428  * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
7429  *    which is an additional piece of metadata which describes what's been
7430  *    written. This allows us to rebuild the arc_buf_hdr_t structures of the
7431  *    main ARC buffers. There are 2 linked-lists of log blocks headed by
7432  *    dh_start_lbps[2]. We alternate which chain we append to, so they are
7433  *    time-wise and offset-wise interleaved, but that is an optimization rather
7434  *    than for correctness. The log block also includes a pointer to the
7435  *    previous block in its chain.
7436  *
7437  * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
7438  *    for our header bookkeeping purposes. This contains a device header,
7439  *    which contains our top-level reference structures. We update it each
7440  *    time we write a new log block, so that we're able to locate it in the
7441  *    L2ARC device. If this write results in an inconsistent device header
7442  *    (e.g. due to power failure), we detect this by verifying the header's
7443  *    checksum and simply fail to reconstruct the L2ARC after reboot.
7444  *
7445  * Implementation diagram:
7446  *
7447  * +=== L2ARC device (not to scale) ======================================+
7448  * |       ___two newest log block pointers__.__________                  |
7449  * |      /                                   \dh_start_lbps[1]           |
7450  * |	 /				       \         \dh_start_lbps[0]|
7451  * |.___/__.                                    V         V               |
7452  * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
7453  * ||   hdr|      ^         /^       /^        /         /                |
7454  * |+------+  ...--\-------/  \-----/--\------/         /                 |
7455  * |                \--------------/    \--------------/                  |
7456  * +======================================================================+
7457  *
7458  * As can be seen on the diagram, rather than using a simple linked list,
7459  * we use a pair of linked lists with alternating elements. This is a
7460  * performance enhancement due to the fact that we only find out the
7461  * address of the next log block access once the current block has been
7462  * completely read in. Obviously, this hurts performance, because we'd be
7463  * keeping the device's I/O queue at only a 1 operation deep, thus
7464  * incurring a large amount of I/O round-trip latency. Having two lists
7465  * allows us to fetch two log blocks ahead of where we are currently
7466  * rebuilding L2ARC buffers.
7467  *
7468  * On-device data structures:
7469  *
7470  * L2ARC device header:	l2arc_dev_hdr_phys_t
7471  * L2ARC log block:	l2arc_log_blk_phys_t
7472  *
7473  * L2ARC reconstruction:
7474  *
7475  * When writing data, we simply write in the standard rotary fashion,
7476  * evicting buffers as we go and simply writing new data over them (writing
7477  * a new log block every now and then). This obviously means that once we
7478  * loop around the end of the device, we will start cutting into an already
7479  * committed log block (and its referenced data buffers), like so:
7480  *
7481  *    current write head__       __old tail
7482  *                        \     /
7483  *                        V    V
7484  * <--|bufs |lb |bufs |lb |    |bufs |lb |bufs |lb |-->
7485  *                         ^    ^^^^^^^^^___________________________________
7486  *                         |                                                \
7487  *                   <<nextwrite>> may overwrite this blk and/or its bufs --'
7488  *
7489  * When importing the pool, we detect this situation and use it to stop
7490  * our scanning process (see l2arc_rebuild).
7491  *
7492  * There is one significant caveat to consider when rebuilding ARC contents
7493  * from an L2ARC device: what about invalidated buffers? Given the above
7494  * construction, we cannot update blocks which we've already written to amend
7495  * them to remove buffers which were invalidated. Thus, during reconstruction,
7496  * we might be populating the cache with buffers for data that's not on the
7497  * main pool anymore, or may have been overwritten!
7498  *
7499  * As it turns out, this isn't a problem. Every arc_read request includes
7500  * both the DVA and, crucially, the birth TXG of the BP the caller is
7501  * looking for. So even if the cache were populated by completely rotten
7502  * blocks for data that had been long deleted and/or overwritten, we'll
7503  * never actually return bad data from the cache, since the DVA with the
7504  * birth TXG uniquely identify a block in space and time - once created,
7505  * a block is immutable on disk. The worst thing we have done is wasted
7506  * some time and memory at l2arc rebuild to reconstruct outdated ARC
7507  * entries that will get dropped from the l2arc as it is being updated
7508  * with new blocks.
7509  *
7510  * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
7511  * hand are not restored. This is done by saving the offset (in bytes)
7512  * l2arc_evict() has evicted to in the L2ARC device header and taking it
7513  * into account when restoring buffers.
7514  */
7515 
7516 static boolean_t
7517 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7518 {
7519 	/*
7520 	 * A buffer is *not* eligible for the L2ARC if it:
7521 	 * 1. belongs to a different spa.
7522 	 * 2. is already cached on the L2ARC.
7523 	 * 3. has an I/O in progress (it may be an incomplete read).
7524 	 * 4. is flagged not eligible (zfs property).
7525 	 * 5. is a prefetch and l2arc_noprefetch is set.
7526 	 */
7527 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
7528 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr) ||
7529 	    (l2arc_noprefetch && HDR_PREFETCH(hdr)))
7530 		return (B_FALSE);
7531 
7532 	return (B_TRUE);
7533 }
7534 
7535 static uint64_t
7536 l2arc_write_size(l2arc_dev_t *dev)
7537 {
7538 	uint64_t size, dev_size;
7539 
7540 	/*
7541 	 * Make sure our globals have meaningful values in case the user
7542 	 * altered them.
7543 	 */
7544 	size = l2arc_write_max;
7545 	if (size == 0) {
7546 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7547 		    "be greater than zero, resetting it to the default (%d)",
7548 		    L2ARC_WRITE_SIZE);
7549 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
7550 	}
7551 
7552 	if (arc_warm == B_FALSE)
7553 		size += l2arc_write_boost;
7554 
7555 	/*
7556 	 * Make sure the write size does not exceed the size of the cache
7557 	 * device. This is important in l2arc_evict(), otherwise infinite
7558 	 * iteration can occur.
7559 	 */
7560 	dev_size = dev->l2ad_end - dev->l2ad_start;
7561 	if ((size + l2arc_log_blk_overhead(size, dev)) >= dev_size) {
7562 		cmn_err(CE_NOTE, "l2arc_write_max or l2arc_write_boost "
7563 		    "plus the overhead of log blocks (persistent L2ARC, "
7564 		    "%" PRIu64 " bytes) exceeds the size of the cache device "
7565 		    "(guid %" PRIu64 "), resetting them to the default (%d)",
7566 		    l2arc_log_blk_overhead(size, dev),
7567 		    dev->l2ad_vdev->vdev_guid, L2ARC_WRITE_SIZE);
7568 		size = l2arc_write_max = l2arc_write_boost = L2ARC_WRITE_SIZE;
7569 
7570 		if (arc_warm == B_FALSE)
7571 			size += l2arc_write_boost;
7572 	}
7573 
7574 	return (size);
7575 
7576 }
7577 
7578 static clock_t
7579 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7580 {
7581 	clock_t interval, next, now;
7582 
7583 	/*
7584 	 * If the ARC lists are busy, increase our write rate; if the
7585 	 * lists are stale, idle back.  This is achieved by checking
7586 	 * how much we previously wrote - if it was more than half of
7587 	 * what we wanted, schedule the next write much sooner.
7588 	 */
7589 	if (l2arc_feed_again && wrote > (wanted / 2))
7590 		interval = (hz * l2arc_feed_min_ms) / 1000;
7591 	else
7592 		interval = hz * l2arc_feed_secs;
7593 
7594 	now = ddi_get_lbolt();
7595 	next = MAX(now, MIN(now + interval, began + interval));
7596 
7597 	return (next);
7598 }
7599 
7600 /*
7601  * Cycle through L2ARC devices.  This is how L2ARC load balances.
7602  * If a device is returned, this also returns holding the spa config lock.
7603  */
7604 static l2arc_dev_t *
7605 l2arc_dev_get_next(void)
7606 {
7607 	l2arc_dev_t *first, *next = NULL;
7608 
7609 	/*
7610 	 * Lock out the removal of spas (spa_namespace_lock), then removal
7611 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
7612 	 * both locks will be dropped and a spa config lock held instead.
7613 	 */
7614 	mutex_enter(&spa_namespace_lock);
7615 	mutex_enter(&l2arc_dev_mtx);
7616 
7617 	/* if there are no vdevs, there is nothing to do */
7618 	if (l2arc_ndev == 0)
7619 		goto out;
7620 
7621 	first = NULL;
7622 	next = l2arc_dev_last;
7623 	do {
7624 		/* loop around the list looking for a non-faulted vdev */
7625 		if (next == NULL) {
7626 			next = list_head(l2arc_dev_list);
7627 		} else {
7628 			next = list_next(l2arc_dev_list, next);
7629 			if (next == NULL)
7630 				next = list_head(l2arc_dev_list);
7631 		}
7632 
7633 		/* if we have come back to the start, bail out */
7634 		if (first == NULL)
7635 			first = next;
7636 		else if (next == first)
7637 			break;
7638 
7639 	} while (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild);
7640 
7641 	/* if we were unable to find any usable vdevs, return NULL */
7642 	if (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild)
7643 		next = NULL;
7644 
7645 	l2arc_dev_last = next;
7646 
7647 out:
7648 	mutex_exit(&l2arc_dev_mtx);
7649 
7650 	/*
7651 	 * Grab the config lock to prevent the 'next' device from being
7652 	 * removed while we are writing to it.
7653 	 */
7654 	if (next != NULL)
7655 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7656 	mutex_exit(&spa_namespace_lock);
7657 
7658 	return (next);
7659 }
7660 
7661 /*
7662  * Free buffers that were tagged for destruction.
7663  */
7664 static void
7665 l2arc_do_free_on_write()
7666 {
7667 	list_t *buflist;
7668 	l2arc_data_free_t *df, *df_prev;
7669 
7670 	mutex_enter(&l2arc_free_on_write_mtx);
7671 	buflist = l2arc_free_on_write;
7672 
7673 	for (df = list_tail(buflist); df; df = df_prev) {
7674 		df_prev = list_prev(buflist, df);
7675 		ASSERT3P(df->l2df_abd, !=, NULL);
7676 		abd_free(df->l2df_abd);
7677 		list_remove(buflist, df);
7678 		kmem_free(df, sizeof (l2arc_data_free_t));
7679 	}
7680 
7681 	mutex_exit(&l2arc_free_on_write_mtx);
7682 }
7683 
7684 /*
7685  * A write to a cache device has completed.  Update all headers to allow
7686  * reads from these buffers to begin.
7687  */
7688 static void
7689 l2arc_write_done(zio_t *zio)
7690 {
7691 	l2arc_write_callback_t	*cb;
7692 	l2arc_lb_abd_buf_t	*abd_buf;
7693 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
7694 	l2arc_dev_t		*dev;
7695 	l2arc_dev_hdr_phys_t	*l2dhdr;
7696 	list_t			*buflist;
7697 	arc_buf_hdr_t		*head, *hdr, *hdr_prev;
7698 	kmutex_t		*hash_lock;
7699 	int64_t			bytes_dropped = 0;
7700 
7701 	cb = zio->io_private;
7702 	ASSERT3P(cb, !=, NULL);
7703 	dev = cb->l2wcb_dev;
7704 	l2dhdr = dev->l2ad_dev_hdr;
7705 	ASSERT3P(dev, !=, NULL);
7706 	head = cb->l2wcb_head;
7707 	ASSERT3P(head, !=, NULL);
7708 	buflist = &dev->l2ad_buflist;
7709 	ASSERT3P(buflist, !=, NULL);
7710 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7711 	    l2arc_write_callback_t *, cb);
7712 
7713 	/*
7714 	 * All writes completed, or an error was hit.
7715 	 */
7716 top:
7717 	mutex_enter(&dev->l2ad_mtx);
7718 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7719 		hdr_prev = list_prev(buflist, hdr);
7720 
7721 		hash_lock = HDR_LOCK(hdr);
7722 
7723 		/*
7724 		 * We cannot use mutex_enter or else we can deadlock
7725 		 * with l2arc_write_buffers (due to swapping the order
7726 		 * the hash lock and l2ad_mtx are taken).
7727 		 */
7728 		if (!mutex_tryenter(hash_lock)) {
7729 			/*
7730 			 * Missed the hash lock. We must retry so we
7731 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
7732 			 */
7733 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7734 
7735 			/*
7736 			 * We don't want to rescan the headers we've
7737 			 * already marked as having been written out, so
7738 			 * we reinsert the head node so we can pick up
7739 			 * where we left off.
7740 			 */
7741 			list_remove(buflist, head);
7742 			list_insert_after(buflist, hdr, head);
7743 
7744 			mutex_exit(&dev->l2ad_mtx);
7745 
7746 			/*
7747 			 * We wait for the hash lock to become available
7748 			 * to try and prevent busy waiting, and increase
7749 			 * the chance we'll be able to acquire the lock
7750 			 * the next time around.
7751 			 */
7752 			mutex_enter(hash_lock);
7753 			mutex_exit(hash_lock);
7754 			goto top;
7755 		}
7756 
7757 		/*
7758 		 * We could not have been moved into the arc_l2c_only
7759 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
7760 		 * bit being set. Let's just ensure that's being enforced.
7761 		 */
7762 		ASSERT(HDR_HAS_L1HDR(hdr));
7763 
7764 		if (zio->io_error != 0) {
7765 			/*
7766 			 * Error - drop L2ARC entry.
7767 			 */
7768 			list_remove(buflist, hdr);
7769 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7770 
7771 			uint64_t psize = HDR_GET_PSIZE(hdr);
7772 			l2arc_hdr_arcstats_decrement(hdr);
7773 
7774 			bytes_dropped +=
7775 			    vdev_psize_to_asize(dev->l2ad_vdev, psize);
7776 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
7777 			    arc_hdr_size(hdr), hdr);
7778 		}
7779 
7780 		/*
7781 		 * Allow ARC to begin reads and ghost list evictions to
7782 		 * this L2ARC entry.
7783 		 */
7784 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7785 
7786 		mutex_exit(hash_lock);
7787 	}
7788 
7789 	/*
7790 	 * Free the allocated abd buffers for writing the log blocks.
7791 	 * If the zio failed reclaim the allocated space and remove the
7792 	 * pointers to these log blocks from the log block pointer list
7793 	 * of the L2ARC device.
7794 	 */
7795 	while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
7796 		abd_free(abd_buf->abd);
7797 		zio_buf_free(abd_buf, sizeof (*abd_buf));
7798 		if (zio->io_error != 0) {
7799 			lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
7800 			/*
7801 			 * L2BLK_GET_PSIZE returns aligned size for log
7802 			 * blocks.
7803 			 */
7804 			uint64_t asize =
7805 			    L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
7806 			bytes_dropped += asize;
7807 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
7808 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
7809 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
7810 			    lb_ptr_buf);
7811 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
7812 			kmem_free(lb_ptr_buf->lb_ptr,
7813 			    sizeof (l2arc_log_blkptr_t));
7814 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
7815 		}
7816 	}
7817 	list_destroy(&cb->l2wcb_abd_list);
7818 
7819 	if (zio->io_error != 0) {
7820 		ARCSTAT_BUMP(arcstat_l2_writes_error);
7821 
7822 		/*
7823 		 * Restore the lbps array in the header to its previous state.
7824 		 * If the list of log block pointers is empty, zero out the
7825 		 * log block pointers in the device header.
7826 		 */
7827 		lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
7828 		for (int i = 0; i < 2; i++) {
7829 			if (lb_ptr_buf == NULL) {
7830 				/*
7831 				 * If the list is empty zero out the device
7832 				 * header. Otherwise zero out the second log
7833 				 * block pointer in the header.
7834 				 */
7835 				if (i == 0) {
7836 					bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
7837 				} else {
7838 					bzero(&l2dhdr->dh_start_lbps[i],
7839 					    sizeof (l2arc_log_blkptr_t));
7840 				}
7841 				break;
7842 			}
7843 			bcopy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[i],
7844 			    sizeof (l2arc_log_blkptr_t));
7845 			lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
7846 			    lb_ptr_buf);
7847 		}
7848 	}
7849 
7850 	atomic_inc_64(&l2arc_writes_done);
7851 	list_remove(buflist, head);
7852 	ASSERT(!HDR_HAS_L1HDR(head));
7853 	kmem_cache_free(hdr_l2only_cache, head);
7854 	mutex_exit(&dev->l2ad_mtx);
7855 
7856 	ASSERT(dev->l2ad_vdev != NULL);
7857 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7858 
7859 	l2arc_do_free_on_write();
7860 
7861 	kmem_free(cb, sizeof (l2arc_write_callback_t));
7862 }
7863 
7864 static int
7865 l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
7866 {
7867 	int ret;
7868 	spa_t *spa = zio->io_spa;
7869 	arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
7870 	blkptr_t *bp = zio->io_bp;
7871 	uint8_t salt[ZIO_DATA_SALT_LEN];
7872 	uint8_t iv[ZIO_DATA_IV_LEN];
7873 	uint8_t mac[ZIO_DATA_MAC_LEN];
7874 	boolean_t no_crypt = B_FALSE;
7875 
7876 	/*
7877 	 * ZIL data is never be written to the L2ARC, so we don't need
7878 	 * special handling for its unique MAC storage.
7879 	 */
7880 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
7881 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
7882 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7883 
7884 	/*
7885 	 * If the data was encrypted, decrypt it now. Note that
7886 	 * we must check the bp here and not the hdr, since the
7887 	 * hdr does not have its encryption parameters updated
7888 	 * until arc_read_done().
7889 	 */
7890 	if (BP_IS_ENCRYPTED(bp)) {
7891 		abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
7892 		    B_TRUE);
7893 
7894 		zio_crypt_decode_params_bp(bp, salt, iv);
7895 		zio_crypt_decode_mac_bp(bp, mac);
7896 
7897 		ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
7898 		    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
7899 		    salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
7900 		    hdr->b_l1hdr.b_pabd, &no_crypt);
7901 		if (ret != 0) {
7902 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
7903 			goto error;
7904 		}
7905 
7906 		/*
7907 		 * If we actually performed decryption, replace b_pabd
7908 		 * with the decrypted data. Otherwise we can just throw
7909 		 * our decryption buffer away.
7910 		 */
7911 		if (!no_crypt) {
7912 			arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
7913 			    arc_hdr_size(hdr), hdr);
7914 			hdr->b_l1hdr.b_pabd = eabd;
7915 			zio->io_abd = eabd;
7916 		} else {
7917 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
7918 		}
7919 	}
7920 
7921 	/*
7922 	 * If the L2ARC block was compressed, but ARC compression
7923 	 * is disabled we decompress the data into a new buffer and
7924 	 * replace the existing data.
7925 	 */
7926 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
7927 	    !HDR_COMPRESSION_ENABLED(hdr)) {
7928 		abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
7929 		    B_TRUE);
7930 		void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
7931 
7932 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
7933 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
7934 		    HDR_GET_LSIZE(hdr));
7935 		if (ret != 0) {
7936 			abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
7937 			arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
7938 			goto error;
7939 		}
7940 
7941 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
7942 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
7943 		    arc_hdr_size(hdr), hdr);
7944 		hdr->b_l1hdr.b_pabd = cabd;
7945 		zio->io_abd = cabd;
7946 		zio->io_size = HDR_GET_LSIZE(hdr);
7947 	}
7948 
7949 	return (0);
7950 
7951 error:
7952 	return (ret);
7953 }
7954 
7955 
7956 /*
7957  * A read to a cache device completed.  Validate buffer contents before
7958  * handing over to the regular ARC routines.
7959  */
7960 static void
7961 l2arc_read_done(zio_t *zio)
7962 {
7963 	int tfm_error = 0;
7964 	l2arc_read_callback_t *cb = zio->io_private;
7965 	arc_buf_hdr_t *hdr;
7966 	kmutex_t *hash_lock;
7967 	boolean_t valid_cksum;
7968 	boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
7969 	    (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
7970 
7971 	ASSERT3P(zio->io_vd, !=, NULL);
7972 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7973 
7974 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7975 
7976 	ASSERT3P(cb, !=, NULL);
7977 	hdr = cb->l2rcb_hdr;
7978 	ASSERT3P(hdr, !=, NULL);
7979 
7980 	hash_lock = HDR_LOCK(hdr);
7981 	mutex_enter(hash_lock);
7982 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7983 
7984 	/*
7985 	 * If the data was read into a temporary buffer,
7986 	 * move it and free the buffer.
7987 	 */
7988 	if (cb->l2rcb_abd != NULL) {
7989 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7990 		if (zio->io_error == 0) {
7991 			if (using_rdata) {
7992 				abd_copy(hdr->b_crypt_hdr.b_rabd,
7993 				    cb->l2rcb_abd, arc_hdr_size(hdr));
7994 			} else {
7995 				abd_copy(hdr->b_l1hdr.b_pabd,
7996 				    cb->l2rcb_abd, arc_hdr_size(hdr));
7997 			}
7998 		}
7999 
8000 		/*
8001 		 * The following must be done regardless of whether
8002 		 * there was an error:
8003 		 * - free the temporary buffer
8004 		 * - point zio to the real ARC buffer
8005 		 * - set zio size accordingly
8006 		 * These are required because zio is either re-used for
8007 		 * an I/O of the block in the case of the error
8008 		 * or the zio is passed to arc_read_done() and it
8009 		 * needs real data.
8010 		 */
8011 		abd_free(cb->l2rcb_abd);
8012 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
8013 
8014 		if (using_rdata) {
8015 			ASSERT(HDR_HAS_RABD(hdr));
8016 			zio->io_abd = zio->io_orig_abd =
8017 			    hdr->b_crypt_hdr.b_rabd;
8018 		} else {
8019 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8020 			zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
8021 		}
8022 	}
8023 
8024 	ASSERT3P(zio->io_abd, !=, NULL);
8025 
8026 	/*
8027 	 * Check this survived the L2ARC journey.
8028 	 */
8029 	ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8030 	    (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8031 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
8032 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
8033 
8034 	valid_cksum = arc_cksum_is_equal(hdr, zio);
8035 
8036 	/*
8037 	 * b_rabd will always match the data as it exists on disk if it is
8038 	 * being used. Therefore if we are reading into b_rabd we do not
8039 	 * attempt to untransform the data.
8040 	 */
8041 	if (valid_cksum && !using_rdata)
8042 		tfm_error = l2arc_untransform(zio, cb);
8043 
8044 	if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8045 	    !HDR_L2_EVICTED(hdr)) {
8046 		mutex_exit(hash_lock);
8047 		zio->io_private = hdr;
8048 		arc_read_done(zio);
8049 	} else {
8050 		/*
8051 		 * Buffer didn't survive caching.  Increment stats and
8052 		 * reissue to the original storage device.
8053 		 */
8054 		if (zio->io_error != 0) {
8055 			ARCSTAT_BUMP(arcstat_l2_io_error);
8056 		} else {
8057 			zio->io_error = SET_ERROR(EIO);
8058 		}
8059 		if (!valid_cksum || tfm_error != 0)
8060 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8061 
8062 		/*
8063 		 * If there's no waiter, issue an async i/o to the primary
8064 		 * storage now.  If there *is* a waiter, the caller must
8065 		 * issue the i/o in a context where it's OK to block.
8066 		 */
8067 		if (zio->io_waiter == NULL) {
8068 			zio_t *pio = zio_unique_parent(zio);
8069 			void *abd = (using_rdata) ?
8070 			    hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
8071 
8072 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8073 
8074 			zio = zio_read(pio, zio->io_spa, zio->io_bp,
8075 			    abd, zio->io_size, arc_read_done,
8076 			    hdr, zio->io_priority, cb->l2rcb_flags,
8077 			    &cb->l2rcb_zb);
8078 
8079 			/*
8080 			 * Original ZIO will be freed, so we need to update
8081 			 * ARC header with the new ZIO pointer to be used
8082 			 * by zio_change_priority() in arc_read().
8083 			 */
8084 			for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
8085 			    acb != NULL; acb = acb->acb_next)
8086 				acb->acb_zio_head = zio;
8087 
8088 			mutex_exit(hash_lock);
8089 			zio_nowait(zio);
8090 		} else {
8091 			mutex_exit(hash_lock);
8092 		}
8093 	}
8094 
8095 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8096 }
8097 
8098 /*
8099  * This is the list priority from which the L2ARC will search for pages to
8100  * cache.  This is used within loops (0..3) to cycle through lists in the
8101  * desired order.  This order can have a significant effect on cache
8102  * performance.
8103  *
8104  * Currently the metadata lists are hit first, MFU then MRU, followed by
8105  * the data lists.  This function returns a locked list, and also returns
8106  * the lock pointer.
8107  */
8108 static multilist_sublist_t *
8109 l2arc_sublist_lock(int list_num)
8110 {
8111 	multilist_t *ml = NULL;
8112 	unsigned int idx;
8113 
8114 	ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
8115 
8116 	switch (list_num) {
8117 	case 0:
8118 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
8119 		break;
8120 	case 1:
8121 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
8122 		break;
8123 	case 2:
8124 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
8125 		break;
8126 	case 3:
8127 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
8128 		break;
8129 	default:
8130 		return (NULL);
8131 	}
8132 
8133 	/*
8134 	 * Return a randomly-selected sublist. This is acceptable
8135 	 * because the caller feeds only a little bit of data for each
8136 	 * call (8MB). Subsequent calls will result in different
8137 	 * sublists being selected.
8138 	 */
8139 	idx = multilist_get_random_index(ml);
8140 	return (multilist_sublist_lock(ml, idx));
8141 }
8142 
8143 /*
8144  * Calculates the maximum overhead of L2ARC metadata log blocks for a given
8145  * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
8146  * overhead in processing to make sure there is enough headroom available
8147  * when writing buffers.
8148  */
8149 static inline uint64_t
8150 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
8151 {
8152 	if (dev->l2ad_log_entries == 0) {
8153 		return (0);
8154 	} else {
8155 		uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
8156 
8157 		uint64_t log_blocks = (log_entries +
8158 		    dev->l2ad_log_entries - 1) /
8159 		    dev->l2ad_log_entries;
8160 
8161 		return (vdev_psize_to_asize(dev->l2ad_vdev,
8162 		    sizeof (l2arc_log_blk_phys_t)) * log_blocks);
8163 	}
8164 }
8165 
8166 /*
8167  * Evict buffers from the device write hand to the distance specified in
8168  * bytes. This distance may span populated buffers, it may span nothing.
8169  * This is clearing a region on the L2ARC device ready for writing.
8170  * If the 'all' boolean is set, every buffer is evicted.
8171  */
8172 static void
8173 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
8174 {
8175 	list_t *buflist;
8176 	arc_buf_hdr_t *hdr, *hdr_prev;
8177 	kmutex_t *hash_lock;
8178 	uint64_t taddr;
8179 	l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
8180 	boolean_t rerun;
8181 
8182 	buflist = &dev->l2ad_buflist;
8183 
8184 	/*
8185 	 * We need to add in the worst case scenario of log block overhead.
8186 	 */
8187 	distance += l2arc_log_blk_overhead(distance, dev);
8188 
8189 top:
8190 	rerun = B_FALSE;
8191 	if (dev->l2ad_hand >= (dev->l2ad_end - distance)) {
8192 		/*
8193 		 * When there is no space to accommodate upcoming writes,
8194 		 * evict to the end. Then bump the write and evict hands
8195 		 * to the start and iterate. This iteration does not
8196 		 * happen indefinitely as we make sure in
8197 		 * l2arc_write_size() that when the write hand is reset,
8198 		 * the write size does not exceed the end of the device.
8199 		 */
8200 		rerun = B_TRUE;
8201 		taddr = dev->l2ad_end;
8202 	} else {
8203 		taddr = dev->l2ad_hand + distance;
8204 	}
8205 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
8206 	    uint64_t, taddr, boolean_t, all);
8207 
8208 	/*
8209 	 * This check has to be placed after deciding whether to iterate
8210 	 * (rerun).
8211 	 */
8212 	if (!all && dev->l2ad_first) {
8213 		/*
8214 		 * This is the first sweep through the device. There is
8215 		 * nothing to evict.
8216 		 */
8217 		goto out;
8218 	}
8219 
8220 	/*
8221 	 * When rebuilding L2ARC we retrieve the evict hand from the header of
8222 	 * the device. Of note, l2arc_evict() does not actually delete buffers
8223 	 * from the cache device, but keeping track of the evict hand will be
8224 	 * useful when TRIM is implemented.
8225 	 */
8226 	dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
8227 
8228 retry:
8229 	mutex_enter(&dev->l2ad_mtx);
8230 	/*
8231 	 * We have to account for evicted log blocks. Run vdev_space_update()
8232 	 * on log blocks whose offset (in bytes) is before the evicted offset
8233 	 * (in bytes) by searching in the list of pointers to log blocks
8234 	 * present in the L2ARC device.
8235 	 */
8236 	for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
8237 	    lb_ptr_buf = lb_ptr_buf_prev) {
8238 
8239 		lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
8240 
8241 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
8242 		uint64_t asize = L2BLK_GET_PSIZE(
8243 		    (lb_ptr_buf->lb_ptr)->lbp_prop);
8244 
8245 		/*
8246 		 * We don't worry about log blocks left behind (ie
8247 		 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
8248 		 * will never write more than l2arc_evict() evicts.
8249 		 */
8250 		if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
8251 			break;
8252 		} else {
8253 			vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
8254 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8255 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8256 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8257 			    lb_ptr_buf);
8258 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8259 			list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
8260 			kmem_free(lb_ptr_buf->lb_ptr,
8261 			    sizeof (l2arc_log_blkptr_t));
8262 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8263 		}
8264 	}
8265 
8266 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
8267 		hdr_prev = list_prev(buflist, hdr);
8268 
8269 		ASSERT(!HDR_EMPTY(hdr));
8270 		hash_lock = HDR_LOCK(hdr);
8271 
8272 		/*
8273 		 * We cannot use mutex_enter or else we can deadlock
8274 		 * with l2arc_write_buffers (due to swapping the order
8275 		 * the hash lock and l2ad_mtx are taken).
8276 		 */
8277 		if (!mutex_tryenter(hash_lock)) {
8278 			/*
8279 			 * Missed the hash lock.  Retry.
8280 			 */
8281 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
8282 			mutex_exit(&dev->l2ad_mtx);
8283 			mutex_enter(hash_lock);
8284 			mutex_exit(hash_lock);
8285 			goto retry;
8286 		}
8287 
8288 		/*
8289 		 * A header can't be on this list if it doesn't have L2 header.
8290 		 */
8291 		ASSERT(HDR_HAS_L2HDR(hdr));
8292 
8293 		/* Ensure this header has finished being written. */
8294 		ASSERT(!HDR_L2_WRITING(hdr));
8295 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8296 
8297 		if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
8298 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
8299 			/*
8300 			 * We've evicted to the target address,
8301 			 * or the end of the device.
8302 			 */
8303 			mutex_exit(hash_lock);
8304 			break;
8305 		}
8306 
8307 		if (!HDR_HAS_L1HDR(hdr)) {
8308 			ASSERT(!HDR_L2_READING(hdr));
8309 			/*
8310 			 * This doesn't exist in the ARC.  Destroy.
8311 			 * arc_hdr_destroy() will call list_remove()
8312 			 * and decrement arcstat_l2_lsize.
8313 			 */
8314 			arc_change_state(arc_anon, hdr, hash_lock);
8315 			arc_hdr_destroy(hdr);
8316 		} else {
8317 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
8318 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
8319 			/*
8320 			 * Invalidate issued or about to be issued
8321 			 * reads, since we may be about to write
8322 			 * over this location.
8323 			 */
8324 			if (HDR_L2_READING(hdr)) {
8325 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
8326 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
8327 			}
8328 
8329 			arc_hdr_l2hdr_destroy(hdr);
8330 		}
8331 		mutex_exit(hash_lock);
8332 	}
8333 	mutex_exit(&dev->l2ad_mtx);
8334 
8335 out:
8336 	/*
8337 	 * We need to check if we evict all buffers, otherwise we may iterate
8338 	 * unnecessarily.
8339 	 */
8340 	if (!all && rerun) {
8341 		/*
8342 		 * Bump device hand to the device start if it is approaching the
8343 		 * end. l2arc_evict() has already evicted ahead for this case.
8344 		 */
8345 		dev->l2ad_hand = dev->l2ad_start;
8346 		dev->l2ad_evict = dev->l2ad_start;
8347 		dev->l2ad_first = B_FALSE;
8348 		goto top;
8349 	}
8350 
8351 	ASSERT3U(dev->l2ad_hand + distance, <, dev->l2ad_end);
8352 	if (!dev->l2ad_first)
8353 		ASSERT3U(dev->l2ad_hand, <, dev->l2ad_evict);
8354 }
8355 
8356 /*
8357  * Handle any abd transforms that might be required for writing to the L2ARC.
8358  * If successful, this function will always return an abd with the data
8359  * transformed as it is on disk in a new abd of asize bytes.
8360  */
8361 static int
8362 l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
8363     abd_t **abd_out)
8364 {
8365 	int ret;
8366 	void *tmp = NULL;
8367 	abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
8368 	enum zio_compress compress = HDR_GET_COMPRESS(hdr);
8369 	uint64_t psize = HDR_GET_PSIZE(hdr);
8370 	uint64_t size = arc_hdr_size(hdr);
8371 	boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
8372 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
8373 	dsl_crypto_key_t *dck = NULL;
8374 	uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
8375 	boolean_t no_crypt = B_FALSE;
8376 
8377 	ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8378 	    !HDR_COMPRESSION_ENABLED(hdr)) ||
8379 	    HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
8380 	ASSERT3U(psize, <=, asize);
8381 
8382 	/*
8383 	 * If this data simply needs its own buffer, we simply allocate it
8384 	 * and copy the data. This may be done to eliminate a dependency on a
8385 	 * shared buffer or to reallocate the buffer to match asize.
8386 	 */
8387 	if (HDR_HAS_RABD(hdr) && asize != psize) {
8388 		ASSERT3U(asize, >=, psize);
8389 		to_write = abd_alloc_for_io(asize, ismd);
8390 		abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
8391 		if (psize != asize)
8392 			abd_zero_off(to_write, psize, asize - psize);
8393 		goto out;
8394 	}
8395 
8396 	if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
8397 	    !HDR_ENCRYPTED(hdr)) {
8398 		ASSERT3U(size, ==, psize);
8399 		to_write = abd_alloc_for_io(asize, ismd);
8400 		abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8401 		if (size != asize)
8402 			abd_zero_off(to_write, size, asize - size);
8403 		goto out;
8404 	}
8405 
8406 	if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
8407 		cabd = abd_alloc_for_io(asize, ismd);
8408 		tmp = abd_borrow_buf(cabd, asize);
8409 
8410 		psize = zio_compress_data(compress, to_write, tmp, size);
8411 		ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
8412 		if (psize < asize)
8413 			bzero((char *)tmp + psize, asize - psize);
8414 		psize = HDR_GET_PSIZE(hdr);
8415 		abd_return_buf_copy(cabd, tmp, asize);
8416 		to_write = cabd;
8417 	}
8418 
8419 	if (HDR_ENCRYPTED(hdr)) {
8420 		eabd = abd_alloc_for_io(asize, ismd);
8421 
8422 		/*
8423 		 * If the dataset was disowned before the buffer
8424 		 * made it to this point, the key to re-encrypt
8425 		 * it won't be available. In this case we simply
8426 		 * won't write the buffer to the L2ARC.
8427 		 */
8428 		ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
8429 		    FTAG, &dck);
8430 		if (ret != 0)
8431 			goto error;
8432 
8433 		ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
8434 		    hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
8435 		    hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
8436 		    &no_crypt);
8437 		if (ret != 0)
8438 			goto error;
8439 
8440 		if (no_crypt)
8441 			abd_copy(eabd, to_write, psize);
8442 
8443 		if (psize != asize)
8444 			abd_zero_off(eabd, psize, asize - psize);
8445 
8446 		/* assert that the MAC we got here matches the one we saved */
8447 		ASSERT0(bcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
8448 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8449 
8450 		if (to_write == cabd)
8451 			abd_free(cabd);
8452 
8453 		to_write = eabd;
8454 	}
8455 
8456 out:
8457 	ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
8458 	*abd_out = to_write;
8459 	return (0);
8460 
8461 error:
8462 	if (dck != NULL)
8463 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8464 	if (cabd != NULL)
8465 		abd_free(cabd);
8466 	if (eabd != NULL)
8467 		abd_free(eabd);
8468 
8469 	*abd_out = NULL;
8470 	return (ret);
8471 }
8472 
8473 static void
8474 l2arc_blk_fetch_done(zio_t *zio)
8475 {
8476 	l2arc_read_callback_t *cb;
8477 
8478 	cb = zio->io_private;
8479 	if (cb->l2rcb_abd != NULL)
8480 		abd_put(cb->l2rcb_abd);
8481 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8482 }
8483 
8484 /*
8485  * Find and write ARC buffers to the L2ARC device.
8486  *
8487  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
8488  * for reading until they have completed writing.
8489  * The headroom_boost is an in-out parameter used to maintain headroom boost
8490  * state between calls to this function.
8491  *
8492  * Returns the number of bytes actually written (which may be smaller than
8493  * the delta by which the device hand has changed due to alignment and the
8494  * writing of log blocks).
8495  */
8496 static uint64_t
8497 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
8498 {
8499 	arc_buf_hdr_t		*hdr, *hdr_prev, *head;
8500 	uint64_t		write_asize, write_psize, write_lsize, headroom;
8501 	boolean_t		full;
8502 	l2arc_write_callback_t	*cb = NULL;
8503 	zio_t			*pio, *wzio;
8504 	uint64_t		guid = spa_load_guid(spa);
8505 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
8506 
8507 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
8508 
8509 	pio = NULL;
8510 	write_lsize = write_asize = write_psize = 0;
8511 	full = B_FALSE;
8512 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
8513 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
8514 
8515 	/*
8516 	 * Copy buffers for L2ARC writing.
8517 	 */
8518 	for (int try = 0; try < L2ARC_FEED_TYPES; try++) {
8519 		/*
8520 		 * If try == 1 or 3, we cache MRU metadata and data
8521 		 * respectively.
8522 		 */
8523 		if (l2arc_mfuonly) {
8524 			if (try == 1 || try == 3)
8525 				continue;
8526 		}
8527 
8528 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
8529 		uint64_t passed_sz = 0;
8530 
8531 		VERIFY3P(mls, !=, NULL);
8532 
8533 		/*
8534 		 * L2ARC fast warmup.
8535 		 *
8536 		 * Until the ARC is warm and starts to evict, read from the
8537 		 * head of the ARC lists rather than the tail.
8538 		 */
8539 		if (arc_warm == B_FALSE)
8540 			hdr = multilist_sublist_head(mls);
8541 		else
8542 			hdr = multilist_sublist_tail(mls);
8543 
8544 		headroom = target_sz * l2arc_headroom;
8545 		if (zfs_compressed_arc_enabled)
8546 			headroom = (headroom * l2arc_headroom_boost) / 100;
8547 
8548 		for (; hdr; hdr = hdr_prev) {
8549 			kmutex_t *hash_lock;
8550 			abd_t *to_write = NULL;
8551 
8552 			if (arc_warm == B_FALSE)
8553 				hdr_prev = multilist_sublist_next(mls, hdr);
8554 			else
8555 				hdr_prev = multilist_sublist_prev(mls, hdr);
8556 
8557 			hash_lock = HDR_LOCK(hdr);
8558 			if (!mutex_tryenter(hash_lock)) {
8559 				/*
8560 				 * Skip this buffer rather than waiting.
8561 				 */
8562 				continue;
8563 			}
8564 
8565 			passed_sz += HDR_GET_LSIZE(hdr);
8566 			if (l2arc_headroom != 0 && passed_sz > headroom) {
8567 				/*
8568 				 * Searched too far.
8569 				 */
8570 				mutex_exit(hash_lock);
8571 				break;
8572 			}
8573 
8574 			if (!l2arc_write_eligible(guid, hdr)) {
8575 				mutex_exit(hash_lock);
8576 				continue;
8577 			}
8578 
8579 			/*
8580 			 * We rely on the L1 portion of the header below, so
8581 			 * it's invalid for this header to have been evicted out
8582 			 * of the ghost cache, prior to being written out. The
8583 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8584 			 */
8585 			ASSERT(HDR_HAS_L1HDR(hdr));
8586 
8587 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8588 			ASSERT3U(arc_hdr_size(hdr), >, 0);
8589 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
8590 			    HDR_HAS_RABD(hdr));
8591 			uint64_t psize = HDR_GET_PSIZE(hdr);
8592 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
8593 			    psize);
8594 
8595 			if ((write_asize + asize) > target_sz) {
8596 				full = B_TRUE;
8597 				mutex_exit(hash_lock);
8598 				break;
8599 			}
8600 
8601 			/*
8602 			 * We rely on the L1 portion of the header below, so
8603 			 * it's invalid for this header to have been evicted out
8604 			 * of the ghost cache, prior to being written out. The
8605 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8606 			 */
8607 			arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
8608 			ASSERT(HDR_HAS_L1HDR(hdr));
8609 
8610 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8611 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
8612 			    HDR_HAS_RABD(hdr));
8613 			ASSERT3U(arc_hdr_size(hdr), >, 0);
8614 
8615 			/*
8616 			 * If this header has b_rabd, we can use this since it
8617 			 * must always match the data exactly as it exists on
8618 			 * disk. Otherwise, the L2ARC can normally use the
8619 			 * hdr's data, but if we're sharing data between the
8620 			 * hdr and one of its bufs, L2ARC needs its own copy of
8621 			 * the data so that the ZIO below can't race with the
8622 			 * buf consumer. To ensure that this copy will be
8623 			 * available for the lifetime of the ZIO and be cleaned
8624 			 * up afterwards, we add it to the l2arc_free_on_write
8625 			 * queue. If we need to apply any transforms to the
8626 			 * data (compression, encryption) we will also need the
8627 			 * extra buffer.
8628 			 */
8629 			if (HDR_HAS_RABD(hdr) && psize == asize) {
8630 				to_write = hdr->b_crypt_hdr.b_rabd;
8631 			} else if ((HDR_COMPRESSION_ENABLED(hdr) ||
8632 			    HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
8633 			    !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
8634 			    psize == asize) {
8635 				to_write = hdr->b_l1hdr.b_pabd;
8636 			} else {
8637 				int ret;
8638 				arc_buf_contents_t type = arc_buf_type(hdr);
8639 
8640 				ret = l2arc_apply_transforms(spa, hdr, asize,
8641 				    &to_write);
8642 				if (ret != 0) {
8643 					arc_hdr_clear_flags(hdr,
8644 					    ARC_FLAG_L2_WRITING);
8645 					mutex_exit(hash_lock);
8646 					continue;
8647 				}
8648 
8649 				l2arc_free_abd_on_write(to_write, asize, type);
8650 			}
8651 
8652 			if (pio == NULL) {
8653 				/*
8654 				 * Insert a dummy header on the buflist so
8655 				 * l2arc_write_done() can find where the
8656 				 * write buffers begin without searching.
8657 				 */
8658 				mutex_enter(&dev->l2ad_mtx);
8659 				list_insert_head(&dev->l2ad_buflist, head);
8660 				mutex_exit(&dev->l2ad_mtx);
8661 
8662 				cb = kmem_alloc(
8663 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
8664 				cb->l2wcb_dev = dev;
8665 				cb->l2wcb_head = head;
8666 				/*
8667 				 * Create a list to save allocated abd buffers
8668 				 * for l2arc_log_blk_commit().
8669 				 */
8670 				list_create(&cb->l2wcb_abd_list,
8671 				    sizeof (l2arc_lb_abd_buf_t),
8672 				    offsetof(l2arc_lb_abd_buf_t, node));
8673 				pio = zio_root(spa, l2arc_write_done, cb,
8674 				    ZIO_FLAG_CANFAIL);
8675 			}
8676 
8677 			hdr->b_l2hdr.b_dev = dev;
8678 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
8679 			hdr->b_l2hdr.b_arcs_state =
8680 			    hdr->b_l1hdr.b_state->arcs_state;
8681 			arc_hdr_set_flags(hdr,
8682 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
8683 
8684 			mutex_enter(&dev->l2ad_mtx);
8685 			list_insert_head(&dev->l2ad_buflist, hdr);
8686 			mutex_exit(&dev->l2ad_mtx);
8687 
8688 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
8689 			    arc_hdr_size(hdr), hdr);
8690 
8691 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
8692 			    hdr->b_l2hdr.b_daddr, asize, to_write,
8693 			    ZIO_CHECKSUM_OFF, NULL, hdr,
8694 			    ZIO_PRIORITY_ASYNC_WRITE,
8695 			    ZIO_FLAG_CANFAIL, B_FALSE);
8696 
8697 			write_lsize += HDR_GET_LSIZE(hdr);
8698 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
8699 			    zio_t *, wzio);
8700 
8701 			write_psize += psize;
8702 			write_asize += asize;
8703 			dev->l2ad_hand += asize;
8704 			l2arc_hdr_arcstats_increment(hdr);
8705 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
8706 
8707 			mutex_exit(hash_lock);
8708 
8709 			/*
8710 			 * Append buf info to current log and commit if full.
8711 			 * arcstat_l2_{size,asize} kstats are updated
8712 			 * internally.
8713 			 */
8714 			if (l2arc_log_blk_insert(dev, hdr))
8715 				l2arc_log_blk_commit(dev, pio, cb);
8716 
8717 			(void) zio_nowait(wzio);
8718 		}
8719 
8720 		multilist_sublist_unlock(mls);
8721 
8722 		if (full == B_TRUE)
8723 			break;
8724 	}
8725 
8726 	/* No buffers selected for writing? */
8727 	if (pio == NULL) {
8728 		ASSERT0(write_lsize);
8729 		ASSERT(!HDR_HAS_L1HDR(head));
8730 		kmem_cache_free(hdr_l2only_cache, head);
8731 
8732 		/*
8733 		 * Although we did not write any buffers l2ad_evict may
8734 		 * have advanced.
8735 		 */
8736 		if (dev->l2ad_evict != l2dhdr->dh_evict)
8737 			l2arc_dev_hdr_update(dev);
8738 
8739 		return (0);
8740 	}
8741 
8742 	if (!dev->l2ad_first)
8743 		ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
8744 
8745 	ASSERT3U(write_asize, <=, target_sz);
8746 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
8747 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
8748 
8749 	dev->l2ad_writing = B_TRUE;
8750 	(void) zio_wait(pio);
8751 	dev->l2ad_writing = B_FALSE;
8752 
8753 	/*
8754 	 * Update the device header after the zio completes as
8755 	 * l2arc_write_done() may have updated the memory holding the log block
8756 	 * pointers in the device header.
8757 	 */
8758 	l2arc_dev_hdr_update(dev);
8759 
8760 	return (write_asize);
8761 }
8762 
8763 static boolean_t
8764 l2arc_hdr_limit_reached(void)
8765 {
8766 	int64_t s = aggsum_upper_bound(&astat_l2_hdr_size);
8767 
8768 	return (arc_reclaim_needed() || (s > arc_meta_limit * 3 / 4) ||
8769 	    (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
8770 }
8771 
8772 /*
8773  * This thread feeds the L2ARC at regular intervals.  This is the beating
8774  * heart of the L2ARC.
8775  */
8776 /* ARGSUSED */
8777 static void
8778 l2arc_feed_thread(void *unused)
8779 {
8780 	callb_cpr_t cpr;
8781 	l2arc_dev_t *dev;
8782 	spa_t *spa;
8783 	uint64_t size, wrote;
8784 	clock_t begin, next = ddi_get_lbolt();
8785 
8786 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
8787 
8788 	mutex_enter(&l2arc_feed_thr_lock);
8789 
8790 	while (l2arc_thread_exit == 0) {
8791 		CALLB_CPR_SAFE_BEGIN(&cpr);
8792 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
8793 		    next);
8794 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
8795 		next = ddi_get_lbolt() + hz;
8796 
8797 		/*
8798 		 * Quick check for L2ARC devices.
8799 		 */
8800 		mutex_enter(&l2arc_dev_mtx);
8801 		if (l2arc_ndev == 0) {
8802 			mutex_exit(&l2arc_dev_mtx);
8803 			continue;
8804 		}
8805 		mutex_exit(&l2arc_dev_mtx);
8806 		begin = ddi_get_lbolt();
8807 
8808 		/*
8809 		 * This selects the next l2arc device to write to, and in
8810 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
8811 		 * will return NULL if there are now no l2arc devices or if
8812 		 * they are all faulted.
8813 		 *
8814 		 * If a device is returned, its spa's config lock is also
8815 		 * held to prevent device removal.  l2arc_dev_get_next()
8816 		 * will grab and release l2arc_dev_mtx.
8817 		 */
8818 		if ((dev = l2arc_dev_get_next()) == NULL)
8819 			continue;
8820 
8821 		spa = dev->l2ad_spa;
8822 		ASSERT3P(spa, !=, NULL);
8823 
8824 		/*
8825 		 * If the pool is read-only then force the feed thread to
8826 		 * sleep a little longer.
8827 		 */
8828 		if (!spa_writeable(spa)) {
8829 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
8830 			spa_config_exit(spa, SCL_L2ARC, dev);
8831 			continue;
8832 		}
8833 
8834 		/*
8835 		 * Avoid contributing to memory pressure.
8836 		 */
8837 		if (l2arc_hdr_limit_reached()) {
8838 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
8839 			spa_config_exit(spa, SCL_L2ARC, dev);
8840 			continue;
8841 		}
8842 
8843 		ARCSTAT_BUMP(arcstat_l2_feeds);
8844 
8845 		size = l2arc_write_size(dev);
8846 
8847 		/*
8848 		 * Evict L2ARC buffers that will be overwritten.
8849 		 */
8850 		l2arc_evict(dev, size, B_FALSE);
8851 
8852 		/*
8853 		 * Write ARC buffers.
8854 		 */
8855 		wrote = l2arc_write_buffers(spa, dev, size);
8856 
8857 		/*
8858 		 * Calculate interval between writes.
8859 		 */
8860 		next = l2arc_write_interval(begin, size, wrote);
8861 		spa_config_exit(spa, SCL_L2ARC, dev);
8862 	}
8863 
8864 	l2arc_thread_exit = 0;
8865 	cv_broadcast(&l2arc_feed_thr_cv);
8866 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
8867 	thread_exit();
8868 }
8869 
8870 boolean_t
8871 l2arc_vdev_present(vdev_t *vd)
8872 {
8873 	return (l2arc_vdev_get(vd) != NULL);
8874 }
8875 
8876 /*
8877  * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
8878  * the vdev_t isn't an L2ARC device.
8879  */
8880 static l2arc_dev_t *
8881 l2arc_vdev_get(vdev_t *vd)
8882 {
8883 	l2arc_dev_t	*dev;
8884 
8885 	mutex_enter(&l2arc_dev_mtx);
8886 	for (dev = list_head(l2arc_dev_list); dev != NULL;
8887 	    dev = list_next(l2arc_dev_list, dev)) {
8888 		if (dev->l2ad_vdev == vd)
8889 			break;
8890 	}
8891 	mutex_exit(&l2arc_dev_mtx);
8892 
8893 	return (dev);
8894 }
8895 
8896 /*
8897  * Add a vdev for use by the L2ARC.  By this point the spa has already
8898  * validated the vdev and opened it.
8899  */
8900 void
8901 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
8902 {
8903 	l2arc_dev_t		*adddev;
8904 	uint64_t		l2dhdr_asize;
8905 
8906 	ASSERT(!l2arc_vdev_present(vd));
8907 
8908 	/*
8909 	 * Create a new l2arc device entry.
8910 	 */
8911 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
8912 	adddev->l2ad_spa = spa;
8913 	adddev->l2ad_vdev = vd;
8914 	/* leave extra size for an l2arc device header */
8915 	l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
8916 	    MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
8917 	adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
8918 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
8919 	ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
8920 	adddev->l2ad_hand = adddev->l2ad_start;
8921 	adddev->l2ad_evict = adddev->l2ad_start;
8922 	adddev->l2ad_first = B_TRUE;
8923 	adddev->l2ad_writing = B_FALSE;
8924 	adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
8925 
8926 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
8927 	/*
8928 	 * This is a list of all ARC buffers that are still valid on the
8929 	 * device.
8930 	 */
8931 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
8932 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
8933 
8934 	/*
8935 	 * This is a list of pointers to log blocks that are still present
8936 	 * on the device.
8937 	 */
8938 	list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
8939 	    offsetof(l2arc_lb_ptr_buf_t, node));
8940 
8941 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
8942 	zfs_refcount_create(&adddev->l2ad_alloc);
8943 	zfs_refcount_create(&adddev->l2ad_lb_asize);
8944 	zfs_refcount_create(&adddev->l2ad_lb_count);
8945 
8946 	/*
8947 	 * Add device to global list
8948 	 */
8949 	mutex_enter(&l2arc_dev_mtx);
8950 	list_insert_head(l2arc_dev_list, adddev);
8951 	atomic_inc_64(&l2arc_ndev);
8952 	mutex_exit(&l2arc_dev_mtx);
8953 
8954 	/*
8955 	 * Decide if vdev is eligible for L2ARC rebuild
8956 	 */
8957 	l2arc_rebuild_vdev(adddev->l2ad_vdev, B_FALSE);
8958 }
8959 
8960 void
8961 l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
8962 {
8963 	l2arc_dev_t		*dev = NULL;
8964 	l2arc_dev_hdr_phys_t	*l2dhdr;
8965 	uint64_t		l2dhdr_asize;
8966 	spa_t			*spa;
8967 
8968 	dev = l2arc_vdev_get(vd);
8969 	ASSERT3P(dev, !=, NULL);
8970 	spa = dev->l2ad_spa;
8971 	l2dhdr = dev->l2ad_dev_hdr;
8972 	l2dhdr_asize = dev->l2ad_dev_hdr_asize;
8973 
8974 	/*
8975 	 * The L2ARC has to hold at least the payload of one log block for
8976 	 * them to be restored (persistent L2ARC). The payload of a log block
8977 	 * depends on the amount of its log entries. We always write log blocks
8978 	 * with 1022 entries. How many of them are committed or restored depends
8979 	 * on the size of the L2ARC device. Thus the maximum payload of
8980 	 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
8981 	 * is less than that, we reduce the amount of committed and restored
8982 	 * log entries per block so as to enable persistence.
8983 	 */
8984 	if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
8985 		dev->l2ad_log_entries = 0;
8986 	} else {
8987 		dev->l2ad_log_entries = MIN((dev->l2ad_end -
8988 		    dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
8989 		    L2ARC_LOG_BLK_MAX_ENTRIES);
8990 	}
8991 
8992 	/*
8993 	 * Read the device header, if an error is returned do not rebuild L2ARC.
8994 	 */
8995 	if (l2arc_dev_hdr_read(dev) == 0 && dev->l2ad_log_entries > 0) {
8996 		/*
8997 		 * If we are onlining a cache device (vdev_reopen) that was
8998 		 * still present (l2arc_vdev_present()) and rebuild is enabled,
8999 		 * we should evict all ARC buffers and pointers to log blocks
9000 		 * and reclaim their space before restoring its contents to
9001 		 * L2ARC.
9002 		 */
9003 		if (reopen) {
9004 			if (!l2arc_rebuild_enabled) {
9005 				return;
9006 			} else {
9007 				l2arc_evict(dev, 0, B_TRUE);
9008 				/* start a new log block */
9009 				dev->l2ad_log_ent_idx = 0;
9010 				dev->l2ad_log_blk_payload_asize = 0;
9011 				dev->l2ad_log_blk_payload_start = 0;
9012 			}
9013 		}
9014 		/*
9015 		 * Just mark the device as pending for a rebuild. We won't
9016 		 * be starting a rebuild in line here as it would block pool
9017 		 * import. Instead spa_load_impl will hand that off to an
9018 		 * async task which will call l2arc_spa_rebuild_start.
9019 		 */
9020 		dev->l2ad_rebuild = B_TRUE;
9021 	} else if (spa_writeable(spa)) {
9022 		/*
9023 		 * In this case create a new header. We zero out the memory
9024 		 * holding the header to reset dh_start_lbps.
9025 		 */
9026 		bzero(l2dhdr, l2dhdr_asize);
9027 		l2arc_dev_hdr_update(dev);
9028 	}
9029 }
9030 
9031 /*
9032  * Remove a vdev from the L2ARC.
9033  */
9034 void
9035 l2arc_remove_vdev(vdev_t *vd)
9036 {
9037 	l2arc_dev_t *remdev = NULL;
9038 
9039 	/*
9040 	 * Find the device by vdev
9041 	 */
9042 	remdev = l2arc_vdev_get(vd);
9043 	ASSERT3P(remdev, !=, NULL);
9044 
9045 	/*
9046 	 * Cancel any ongoing or scheduled rebuild.
9047 	 */
9048 	mutex_enter(&l2arc_rebuild_thr_lock);
9049 	if (remdev->l2ad_rebuild_began == B_TRUE) {
9050 		remdev->l2ad_rebuild_cancel = B_TRUE;
9051 		while (remdev->l2ad_rebuild == B_TRUE)
9052 			cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
9053 	}
9054 	mutex_exit(&l2arc_rebuild_thr_lock);
9055 
9056 	/*
9057 	 * Remove device from global list
9058 	 */
9059 	mutex_enter(&l2arc_dev_mtx);
9060 	list_remove(l2arc_dev_list, remdev);
9061 	l2arc_dev_last = NULL;		/* may have been invalidated */
9062 	atomic_dec_64(&l2arc_ndev);
9063 	mutex_exit(&l2arc_dev_mtx);
9064 
9065 	/*
9066 	 * Clear all buflists and ARC references.  L2ARC device flush.
9067 	 */
9068 	l2arc_evict(remdev, 0, B_TRUE);
9069 	list_destroy(&remdev->l2ad_buflist);
9070 	ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
9071 	list_destroy(&remdev->l2ad_lbptr_list);
9072 	mutex_destroy(&remdev->l2ad_mtx);
9073 	zfs_refcount_destroy(&remdev->l2ad_alloc);
9074 	zfs_refcount_destroy(&remdev->l2ad_lb_asize);
9075 	zfs_refcount_destroy(&remdev->l2ad_lb_count);
9076 	kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
9077 	kmem_free(remdev, sizeof (l2arc_dev_t));
9078 }
9079 
9080 void
9081 l2arc_init(void)
9082 {
9083 	l2arc_thread_exit = 0;
9084 	l2arc_ndev = 0;
9085 	l2arc_writes_sent = 0;
9086 	l2arc_writes_done = 0;
9087 
9088 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9089 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
9090 	mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9091 	cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
9092 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
9093 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
9094 
9095 	l2arc_dev_list = &L2ARC_dev_list;
9096 	l2arc_free_on_write = &L2ARC_free_on_write;
9097 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
9098 	    offsetof(l2arc_dev_t, l2ad_node));
9099 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
9100 	    offsetof(l2arc_data_free_t, l2df_list_node));
9101 }
9102 
9103 void
9104 l2arc_fini(void)
9105 {
9106 	/*
9107 	 * This is called from dmu_fini(), which is called from spa_fini();
9108 	 * Because of this, we can assume that all l2arc devices have
9109 	 * already been removed when the pools themselves were removed.
9110 	 */
9111 
9112 	l2arc_do_free_on_write();
9113 
9114 	mutex_destroy(&l2arc_feed_thr_lock);
9115 	cv_destroy(&l2arc_feed_thr_cv);
9116 	mutex_destroy(&l2arc_rebuild_thr_lock);
9117 	cv_destroy(&l2arc_rebuild_thr_cv);
9118 	mutex_destroy(&l2arc_dev_mtx);
9119 	mutex_destroy(&l2arc_free_on_write_mtx);
9120 
9121 	list_destroy(l2arc_dev_list);
9122 	list_destroy(l2arc_free_on_write);
9123 }
9124 
9125 void
9126 l2arc_start(void)
9127 {
9128 	if (!(spa_mode_global & FWRITE))
9129 		return;
9130 
9131 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
9132 	    TS_RUN, minclsyspri);
9133 }
9134 
9135 void
9136 l2arc_stop(void)
9137 {
9138 	if (!(spa_mode_global & FWRITE))
9139 		return;
9140 
9141 	mutex_enter(&l2arc_feed_thr_lock);
9142 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
9143 	l2arc_thread_exit = 1;
9144 	while (l2arc_thread_exit != 0)
9145 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
9146 	mutex_exit(&l2arc_feed_thr_lock);
9147 }
9148 
9149 /*
9150  * Punches out rebuild threads for the L2ARC devices in a spa. This should
9151  * be called after pool import from the spa async thread, since starting
9152  * these threads directly from spa_import() will make them part of the
9153  * "zpool import" context and delay process exit (and thus pool import).
9154  */
9155 void
9156 l2arc_spa_rebuild_start(spa_t *spa)
9157 {
9158 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
9159 
9160 	/*
9161 	 * Locate the spa's l2arc devices and kick off rebuild threads.
9162 	 */
9163 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
9164 		l2arc_dev_t *dev =
9165 		    l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
9166 		if (dev == NULL) {
9167 			/* Don't attempt a rebuild if the vdev is UNAVAIL */
9168 			continue;
9169 		}
9170 		mutex_enter(&l2arc_rebuild_thr_lock);
9171 		if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
9172 			dev->l2ad_rebuild_began = B_TRUE;
9173 			(void) thread_create(NULL, 0,
9174 			    (void (*)(void *))l2arc_dev_rebuild_start,
9175 			    dev, 0, &p0, TS_RUN, minclsyspri);
9176 		}
9177 		mutex_exit(&l2arc_rebuild_thr_lock);
9178 	}
9179 }
9180 
9181 /*
9182  * Main entry point for L2ARC rebuilding.
9183  */
9184 static void
9185 l2arc_dev_rebuild_start(l2arc_dev_t *dev)
9186 {
9187 	VERIFY(!dev->l2ad_rebuild_cancel);
9188 	VERIFY(dev->l2ad_rebuild);
9189 	(void) l2arc_rebuild(dev);
9190 	mutex_enter(&l2arc_rebuild_thr_lock);
9191 	dev->l2ad_rebuild_began = B_FALSE;
9192 	dev->l2ad_rebuild = B_FALSE;
9193 	mutex_exit(&l2arc_rebuild_thr_lock);
9194 
9195 	thread_exit();
9196 }
9197 
9198 /*
9199  * This function implements the actual L2ARC metadata rebuild. It:
9200  * starts reading the log block chain and restores each block's contents
9201  * to memory (reconstructing arc_buf_hdr_t's).
9202  *
9203  * Operation stops under any of the following conditions:
9204  *
9205  * 1) We reach the end of the log block chain.
9206  * 2) We encounter *any* error condition (cksum errors, io errors)
9207  */
9208 static int
9209 l2arc_rebuild(l2arc_dev_t *dev)
9210 {
9211 	vdev_t			*vd = dev->l2ad_vdev;
9212 	spa_t			*spa = vd->vdev_spa;
9213 	int			err = 0;
9214 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9215 	l2arc_log_blk_phys_t	*this_lb, *next_lb;
9216 	zio_t			*this_io = NULL, *next_io = NULL;
9217 	l2arc_log_blkptr_t	lbps[2];
9218 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
9219 	boolean_t		lock_held;
9220 
9221 	this_lb = kmem_zalloc(sizeof (*this_lb), KM_SLEEP);
9222 	next_lb = kmem_zalloc(sizeof (*next_lb), KM_SLEEP);
9223 
9224 	/*
9225 	 * We prevent device removal while issuing reads to the device,
9226 	 * then during the rebuilding phases we drop this lock again so
9227 	 * that a spa_unload or device remove can be initiated - this is
9228 	 * safe, because the spa will signal us to stop before removing
9229 	 * our device and wait for us to stop.
9230 	 */
9231 	spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
9232 	lock_held = B_TRUE;
9233 
9234 	/*
9235 	 * Retrieve the persistent L2ARC device state.
9236 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9237 	 */
9238 	dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
9239 	dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
9240 	    L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
9241 	    dev->l2ad_start);
9242 	dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
9243 
9244 	/*
9245 	 * In case the zfs module parameter l2arc_rebuild_enabled is false
9246 	 * we do not start the rebuild process.
9247 	 */
9248 	if (!l2arc_rebuild_enabled)
9249 		goto out;
9250 
9251 	/* Prepare the rebuild process */
9252 	bcopy(l2dhdr->dh_start_lbps, lbps, sizeof (lbps));
9253 
9254 	/* Start the rebuild process */
9255 	for (;;) {
9256 		if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
9257 			break;
9258 
9259 		if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
9260 		    this_lb, next_lb, this_io, &next_io)) != 0)
9261 			goto out;
9262 
9263 		/*
9264 		 * Our memory pressure valve. If the system is running low
9265 		 * on memory, rather than swamping memory with new ARC buf
9266 		 * hdrs, we opt not to rebuild the L2ARC. At this point,
9267 		 * however, we have already set up our L2ARC dev to chain in
9268 		 * new metadata log blocks, so the user may choose to offline/
9269 		 * online the L2ARC dev at a later time (or re-import the pool)
9270 		 * to reconstruct it (when there's less memory pressure).
9271 		 */
9272 		if (l2arc_hdr_limit_reached()) {
9273 			ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
9274 			cmn_err(CE_NOTE, "System running low on memory, "
9275 			    "aborting L2ARC rebuild.");
9276 			err = SET_ERROR(ENOMEM);
9277 			goto out;
9278 		}
9279 
9280 		spa_config_exit(spa, SCL_L2ARC, vd);
9281 		lock_held = B_FALSE;
9282 
9283 		/*
9284 		 * Now that we know that the next_lb checks out alright, we
9285 		 * can start reconstruction from this log block.
9286 		 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9287 		 */
9288 		uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
9289 		l2arc_log_blk_restore(dev, this_lb, asize);
9290 
9291 		/*
9292 		 * log block restored, include its pointer in the list of
9293 		 * pointers to log blocks present in the L2ARC device.
9294 		 */
9295 		lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
9296 		lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
9297 		    KM_SLEEP);
9298 		bcopy(&lbps[0], lb_ptr_buf->lb_ptr,
9299 		    sizeof (l2arc_log_blkptr_t));
9300 		mutex_enter(&dev->l2ad_mtx);
9301 		list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
9302 		ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
9303 		ARCSTAT_BUMP(arcstat_l2_log_blk_count);
9304 		zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
9305 		zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
9306 		mutex_exit(&dev->l2ad_mtx);
9307 		vdev_space_update(vd, asize, 0, 0);
9308 
9309 		/* BEGIN CSTYLED */
9310 		/*
9311 		 * Protection against loops of log blocks:
9312 		 *
9313 		 *				       l2ad_hand  l2ad_evict
9314 		 *                                         V          V
9315 		 * l2ad_start |=======================================| l2ad_end
9316 		 *             -----|||----|||---|||----|||
9317 		 *                  (3)    (2)   (1)    (0)
9318 		 *             ---|||---|||----|||---|||
9319 		 *		  (7)   (6)    (5)   (4)
9320 		 *
9321 		 * In this situation the pointer of log block (4) passes
9322 		 * l2arc_log_blkptr_valid() but the log block should not be
9323 		 * restored as it is overwritten by the payload of log block
9324 		 * (0). Only log blocks (0)-(3) should be restored. We check
9325 		 * whether l2ad_evict lies in between the payload starting
9326 		 * offset of the next log block (lbps[1].lbp_payload_start)
9327 		 * and the payload starting offset of the present log block
9328 		 * (lbps[0].lbp_payload_start). If true and this isn't the
9329 		 * first pass, we are looping from the beginning and we should
9330 		 * stop.
9331 		 */
9332 		/* END CSTYLED */
9333 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
9334 		    lbps[0].lbp_payload_start, dev->l2ad_evict) &&
9335 		    !dev->l2ad_first)
9336 			goto out;
9337 
9338 		for (;;) {
9339 			mutex_enter(&l2arc_rebuild_thr_lock);
9340 			if (dev->l2ad_rebuild_cancel) {
9341 				dev->l2ad_rebuild = B_FALSE;
9342 				cv_signal(&l2arc_rebuild_thr_cv);
9343 				mutex_exit(&l2arc_rebuild_thr_lock);
9344 				err = SET_ERROR(ECANCELED);
9345 				goto out;
9346 			}
9347 			mutex_exit(&l2arc_rebuild_thr_lock);
9348 			if (spa_config_tryenter(spa, SCL_L2ARC, vd,
9349 			    RW_READER)) {
9350 				lock_held = B_TRUE;
9351 				break;
9352 			}
9353 			/*
9354 			 * L2ARC config lock held by somebody in writer,
9355 			 * possibly due to them trying to remove us. They'll
9356 			 * likely to want us to shut down, so after a little
9357 			 * delay, we check l2ad_rebuild_cancel and retry
9358 			 * the lock again.
9359 			 */
9360 			delay(1);
9361 		}
9362 
9363 		/*
9364 		 * Continue with the next log block.
9365 		 */
9366 		lbps[0] = lbps[1];
9367 		lbps[1] = this_lb->lb_prev_lbp;
9368 		PTR_SWAP(this_lb, next_lb);
9369 		this_io = next_io;
9370 		next_io = NULL;
9371 	}
9372 
9373 	if (this_io != NULL)
9374 		l2arc_log_blk_fetch_abort(this_io);
9375 out:
9376 	if (next_io != NULL)
9377 		l2arc_log_blk_fetch_abort(next_io);
9378 	kmem_free(this_lb, sizeof (*this_lb));
9379 	kmem_free(next_lb, sizeof (*next_lb));
9380 
9381 	if (!l2arc_rebuild_enabled) {
9382 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9383 		    "disabled");
9384 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
9385 		ARCSTAT_BUMP(arcstat_l2_rebuild_success);
9386 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9387 		    "successful, restored %llu blocks",
9388 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9389 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
9390 		/*
9391 		 * No error but also nothing restored, meaning the lbps array
9392 		 * in the device header points to invalid/non-present log
9393 		 * blocks. Reset the header.
9394 		 */
9395 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9396 		    "no valid log blocks");
9397 		bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
9398 		l2arc_dev_hdr_update(dev);
9399 	} else if (err == ECANCELED) {
9400 		/*
9401 		 * In case the rebuild was canceled do not log to spa history
9402 		 * log as the pool may be in the process of being removed.
9403 		 */
9404 		zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
9405 		    zfs_refcount_count(&dev->l2ad_lb_count));
9406 	} else if (err != 0) {
9407 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9408 		    "aborted, restored %llu blocks",
9409 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9410 	}
9411 
9412 	if (lock_held)
9413 		spa_config_exit(spa, SCL_L2ARC, vd);
9414 
9415 	return (err);
9416 }
9417 
9418 /*
9419  * Attempts to read the device header on the provided L2ARC device and writes
9420  * it to `hdr'. On success, this function returns 0, otherwise the appropriate
9421  * error code is returned.
9422  */
9423 static int
9424 l2arc_dev_hdr_read(l2arc_dev_t *dev)
9425 {
9426 	int			err;
9427 	uint64_t		guid;
9428 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9429 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9430 	abd_t			*abd;
9431 
9432 	guid = spa_guid(dev->l2ad_vdev->vdev_spa);
9433 
9434 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
9435 
9436 	err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
9437 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
9438 	    ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
9439 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
9440 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
9441 	    ZIO_FLAG_SPECULATIVE, B_FALSE));
9442 
9443 	abd_put(abd);
9444 
9445 	if (err != 0) {
9446 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
9447 		zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
9448 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
9449 		return (err);
9450 	}
9451 
9452 	if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
9453 		byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
9454 
9455 	if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
9456 	    l2dhdr->dh_spa_guid != guid ||
9457 	    l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
9458 	    l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
9459 	    l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
9460 	    l2dhdr->dh_end != dev->l2ad_end ||
9461 	    !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
9462 	    l2dhdr->dh_evict)) {
9463 		/*
9464 		 * Attempt to rebuild a device containing no actual dev hdr
9465 		 * or containing a header from some other pool or from another
9466 		 * version of persistent L2ARC.
9467 		 */
9468 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
9469 		return (SET_ERROR(ENOTSUP));
9470 	}
9471 
9472 	return (0);
9473 }
9474 
9475 /*
9476  * Reads L2ARC log blocks from storage and validates their contents.
9477  *
9478  * This function implements a simple fetcher to make sure that while
9479  * we're processing one buffer the L2ARC is already fetching the next
9480  * one in the chain.
9481  *
9482  * The arguments this_lp and next_lp point to the current and next log block
9483  * address in the block chain. Similarly, this_lb and next_lb hold the
9484  * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
9485  *
9486  * The `this_io' and `next_io' arguments are used for block fetching.
9487  * When issuing the first blk IO during rebuild, you should pass NULL for
9488  * `this_io'. This function will then issue a sync IO to read the block and
9489  * also issue an async IO to fetch the next block in the block chain. The
9490  * fetched IO is returned in `next_io'. On subsequent calls to this
9491  * function, pass the value returned in `next_io' from the previous call
9492  * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
9493  * Prior to the call, you should initialize your `next_io' pointer to be
9494  * NULL. If no fetch IO was issued, the pointer is left set at NULL.
9495  *
9496  * On success, this function returns 0, otherwise it returns an appropriate
9497  * error code. On error the fetching IO is aborted and cleared before
9498  * returning from this function. Therefore, if we return `success', the
9499  * caller can assume that we have taken care of cleanup of fetch IOs.
9500  */
9501 static int
9502 l2arc_log_blk_read(l2arc_dev_t *dev,
9503     const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
9504     l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
9505     zio_t *this_io, zio_t **next_io)
9506 {
9507 	int		err = 0;
9508 	zio_cksum_t	cksum;
9509 	abd_t		*abd = NULL;
9510 	uint64_t	asize;
9511 
9512 	ASSERT(this_lbp != NULL && next_lbp != NULL);
9513 	ASSERT(this_lb != NULL && next_lb != NULL);
9514 	ASSERT(next_io != NULL && *next_io == NULL);
9515 	ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
9516 
9517 	/*
9518 	 * Check to see if we have issued the IO for this log block in a
9519 	 * previous run. If not, this is the first call, so issue it now.
9520 	 */
9521 	if (this_io == NULL) {
9522 		this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
9523 		    this_lb);
9524 	}
9525 
9526 	/*
9527 	 * Peek to see if we can start issuing the next IO immediately.
9528 	 */
9529 	if (l2arc_log_blkptr_valid(dev, next_lbp)) {
9530 		/*
9531 		 * Start issuing IO for the next log block early - this
9532 		 * should help keep the L2ARC device busy while we
9533 		 * decompress and restore this log block.
9534 		 */
9535 		*next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
9536 		    next_lb);
9537 	}
9538 
9539 	/* Wait for the IO to read this log block to complete */
9540 	if ((err = zio_wait(this_io)) != 0) {
9541 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
9542 		zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
9543 		    "offset: %llu, vdev guid: %llu", err, this_lbp->lbp_daddr,
9544 		    dev->l2ad_vdev->vdev_guid);
9545 		goto cleanup;
9546 	}
9547 
9548 	/*
9549 	 * Make sure the buffer checks out.
9550 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9551 	 */
9552 	asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
9553 	fletcher_4_native(this_lb, asize, NULL, &cksum);
9554 	if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
9555 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
9556 		zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
9557 		    "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
9558 		    this_lbp->lbp_daddr, dev->l2ad_vdev->vdev_guid,
9559 		    dev->l2ad_hand, dev->l2ad_evict);
9560 		err = SET_ERROR(ECKSUM);
9561 		goto cleanup;
9562 	}
9563 
9564 	/* Now we can take our time decoding this buffer */
9565 	switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
9566 	case ZIO_COMPRESS_OFF:
9567 		break;
9568 	case ZIO_COMPRESS_LZ4:
9569 		abd = abd_alloc_for_io(asize, B_TRUE);
9570 		abd_copy_from_buf_off(abd, this_lb, 0, asize);
9571 		if ((err = zio_decompress_data(
9572 		    L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
9573 		    abd, this_lb, asize, sizeof (*this_lb))) != 0) {
9574 			err = SET_ERROR(EINVAL);
9575 			goto cleanup;
9576 		}
9577 		break;
9578 	default:
9579 		err = SET_ERROR(EINVAL);
9580 		goto cleanup;
9581 	}
9582 	if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
9583 		byteswap_uint64_array(this_lb, sizeof (*this_lb));
9584 	if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
9585 		err = SET_ERROR(EINVAL);
9586 		goto cleanup;
9587 	}
9588 cleanup:
9589 	/* Abort an in-flight fetch I/O in case of error */
9590 	if (err != 0 && *next_io != NULL) {
9591 		l2arc_log_blk_fetch_abort(*next_io);
9592 		*next_io = NULL;
9593 	}
9594 	if (abd != NULL)
9595 		abd_free(abd);
9596 	return (err);
9597 }
9598 
9599 /*
9600  * Restores the payload of a log block to ARC. This creates empty ARC hdr
9601  * entries which only contain an l2arc hdr, essentially restoring the
9602  * buffers to their L2ARC evicted state. This function also updates space
9603  * usage on the L2ARC vdev to make sure it tracks restored buffers.
9604  */
9605 static void
9606 l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
9607     uint64_t lb_asize)
9608 {
9609 	uint64_t	size = 0, asize = 0;
9610 	uint64_t	log_entries = dev->l2ad_log_entries;
9611 
9612 	/*
9613 	 * Usually arc_adapt() is called only for data, not headers, but
9614 	 * since we may allocate significant amount of memory here, let ARC
9615 	 * grow its arc_c.
9616 	 */
9617 	arc_adapt(log_entries * HDR_L2ONLY_SIZE, arc_l2c_only);
9618 
9619 	for (int i = log_entries - 1; i >= 0; i--) {
9620 		/*
9621 		 * Restore goes in the reverse temporal direction to preserve
9622 		 * correct temporal ordering of buffers in the l2ad_buflist.
9623 		 * l2arc_hdr_restore also does a list_insert_tail instead of
9624 		 * list_insert_head on the l2ad_buflist:
9625 		 *
9626 		 *		LIST	l2ad_buflist		LIST
9627 		 *		HEAD  <------ (time) ------	TAIL
9628 		 * direction	+-----+-----+-----+-----+-----+    direction
9629 		 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
9630 		 * fill		+-----+-----+-----+-----+-----+
9631 		 *		^				^
9632 		 *		|				|
9633 		 *		|				|
9634 		 *	l2arc_feed_thread		l2arc_rebuild
9635 		 *	will place new bufs here	restores bufs here
9636 		 *
9637 		 * During l2arc_rebuild() the device is not used by
9638 		 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
9639 		 */
9640 		size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
9641 		asize += vdev_psize_to_asize(dev->l2ad_vdev,
9642 		    L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
9643 		l2arc_hdr_restore(&lb->lb_entries[i], dev);
9644 	}
9645 
9646 	/*
9647 	 * Record rebuild stats:
9648 	 *	size		Logical size of restored buffers in the L2ARC
9649 	 *	asize		Aligned size of restored buffers in the L2ARC
9650 	 */
9651 	ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
9652 	ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
9653 	ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
9654 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
9655 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
9656 	ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
9657 }
9658 
9659 /*
9660  * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
9661  * into a state indicating that it has been evicted to L2ARC.
9662  */
9663 static void
9664 l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
9665 {
9666 	arc_buf_hdr_t		*hdr, *exists;
9667 	kmutex_t		*hash_lock;
9668 	arc_buf_contents_t	type = L2BLK_GET_TYPE((le)->le_prop);
9669 	uint64_t		asize;
9670 
9671 	/*
9672 	 * Do all the allocation before grabbing any locks, this lets us
9673 	 * sleep if memory is full and we don't have to deal with failed
9674 	 * allocations.
9675 	 */
9676 	hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
9677 	    dev, le->le_dva, le->le_daddr,
9678 	    L2BLK_GET_PSIZE((le)->le_prop), le->le_birth,
9679 	    L2BLK_GET_COMPRESS((le)->le_prop),
9680 	    L2BLK_GET_PROTECTED((le)->le_prop),
9681 	    L2BLK_GET_PREFETCH((le)->le_prop),
9682 	    L2BLK_GET_STATE((le)->le_prop));
9683 	asize = vdev_psize_to_asize(dev->l2ad_vdev,
9684 	    L2BLK_GET_PSIZE((le)->le_prop));
9685 
9686 	/*
9687 	 * vdev_space_update() has to be called before arc_hdr_destroy() to
9688 	 * avoid underflow since the latter also calls vdev_space_update().
9689 	 */
9690 	l2arc_hdr_arcstats_increment(hdr);
9691 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9692 
9693 	mutex_enter(&dev->l2ad_mtx);
9694 	list_insert_tail(&dev->l2ad_buflist, hdr);
9695 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
9696 	mutex_exit(&dev->l2ad_mtx);
9697 
9698 	exists = buf_hash_insert(hdr, &hash_lock);
9699 	if (exists) {
9700 		/* Buffer was already cached, no need to restore it. */
9701 		arc_hdr_destroy(hdr);
9702 		/*
9703 		 * If the buffer is already cached, check whether it has
9704 		 * L2ARC metadata. If not, enter them and update the flag.
9705 		 * This is important is case of onlining a cache device, since
9706 		 * we previously evicted all L2ARC metadata from ARC.
9707 		 */
9708 		if (!HDR_HAS_L2HDR(exists)) {
9709 			arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
9710 			exists->b_l2hdr.b_dev = dev;
9711 			exists->b_l2hdr.b_daddr = le->le_daddr;
9712 			exists->b_l2hdr.b_arcs_state =
9713 			    L2BLK_GET_STATE((le)->le_prop);
9714 			mutex_enter(&dev->l2ad_mtx);
9715 			list_insert_tail(&dev->l2ad_buflist, exists);
9716 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
9717 			    arc_hdr_size(exists), exists);
9718 			mutex_exit(&dev->l2ad_mtx);
9719 			l2arc_hdr_arcstats_increment(exists);
9720 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9721 		}
9722 		ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
9723 	}
9724 
9725 	mutex_exit(hash_lock);
9726 }
9727 
9728 /*
9729  * Starts an asynchronous read IO to read a log block. This is used in log
9730  * block reconstruction to start reading the next block before we are done
9731  * decoding and reconstructing the current block, to keep the l2arc device
9732  * nice and hot with read IO to process.
9733  * The returned zio will contain newly allocated memory buffers for the IO
9734  * data which should then be freed by the caller once the zio is no longer
9735  * needed (i.e. due to it having completed). If you wish to abort this
9736  * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
9737  * care of disposing of the allocated buffers correctly.
9738  */
9739 static zio_t *
9740 l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
9741     l2arc_log_blk_phys_t *lb)
9742 {
9743 	uint32_t		asize;
9744 	zio_t			*pio;
9745 	l2arc_read_callback_t	*cb;
9746 
9747 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
9748 	asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
9749 	ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
9750 
9751 	cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
9752 	cb->l2rcb_abd = abd_get_from_buf(lb, asize);
9753 	pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
9754 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
9755 	    ZIO_FLAG_DONT_RETRY);
9756 	(void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
9757 	    cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
9758 	    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
9759 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
9760 
9761 	return (pio);
9762 }
9763 
9764 /*
9765  * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
9766  * buffers allocated for it.
9767  */
9768 static void
9769 l2arc_log_blk_fetch_abort(zio_t *zio)
9770 {
9771 	(void) zio_wait(zio);
9772 }
9773 
9774 /*
9775  * Creates a zio to update the device header on an l2arc device.
9776  */
9777 static void
9778 l2arc_dev_hdr_update(l2arc_dev_t *dev)
9779 {
9780 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9781 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9782 	abd_t			*abd;
9783 	int			err;
9784 
9785 	VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
9786 
9787 	l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
9788 	l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
9789 	l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
9790 	l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
9791 	l2dhdr->dh_log_entries = dev->l2ad_log_entries;
9792 	l2dhdr->dh_evict = dev->l2ad_evict;
9793 	l2dhdr->dh_start = dev->l2ad_start;
9794 	l2dhdr->dh_end = dev->l2ad_end;
9795 	l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
9796 	l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
9797 	l2dhdr->dh_flags = 0;
9798 	if (dev->l2ad_first)
9799 		l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
9800 
9801 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
9802 
9803 	err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
9804 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
9805 	    NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
9806 
9807 	abd_put(abd);
9808 
9809 	if (err != 0) {
9810 		zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
9811 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
9812 	}
9813 }
9814 
9815 /*
9816  * Commits a log block to the L2ARC device. This routine is invoked from
9817  * l2arc_write_buffers when the log block fills up.
9818  * This function allocates some memory to temporarily hold the serialized
9819  * buffer to be written. This is then released in l2arc_write_done.
9820  */
9821 static void
9822 l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
9823 {
9824 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
9825 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9826 	uint64_t		psize, asize;
9827 	zio_t			*wzio;
9828 	l2arc_lb_abd_buf_t	*abd_buf;
9829 	uint8_t			*tmpbuf;
9830 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
9831 
9832 	VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
9833 
9834 	tmpbuf = zio_buf_alloc(sizeof (*lb));
9835 	abd_buf = zio_buf_alloc(sizeof (*abd_buf));
9836 	abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
9837 	lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
9838 	lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
9839 
9840 	/* link the buffer into the block chain */
9841 	lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
9842 	lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
9843 
9844 	/*
9845 	 * l2arc_log_blk_commit() may be called multiple times during a single
9846 	 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
9847 	 * so we can free them in l2arc_write_done() later on.
9848 	 */
9849 	list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
9850 
9851 	/* try to compress the buffer */
9852 	psize = zio_compress_data(ZIO_COMPRESS_LZ4,
9853 	    abd_buf->abd, tmpbuf, sizeof (*lb));
9854 
9855 	/* a log block is never entirely zero */
9856 	ASSERT(psize != 0);
9857 	asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
9858 	ASSERT(asize <= sizeof (*lb));
9859 
9860 	/*
9861 	 * Update the start log block pointer in the device header to point
9862 	 * to the log block we're about to write.
9863 	 */
9864 	l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
9865 	l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
9866 	l2dhdr->dh_start_lbps[0].lbp_payload_asize =
9867 	    dev->l2ad_log_blk_payload_asize;
9868 	l2dhdr->dh_start_lbps[0].lbp_payload_start =
9869 	    dev->l2ad_log_blk_payload_start;
9870 	_NOTE(CONSTCOND)
9871 	L2BLK_SET_LSIZE(
9872 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
9873 	L2BLK_SET_PSIZE(
9874 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
9875 	L2BLK_SET_CHECKSUM(
9876 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
9877 	    ZIO_CHECKSUM_FLETCHER_4);
9878 	if (asize < sizeof (*lb)) {
9879 		/* compression succeeded */
9880 		bzero(tmpbuf + psize, asize - psize);
9881 		L2BLK_SET_COMPRESS(
9882 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
9883 		    ZIO_COMPRESS_LZ4);
9884 	} else {
9885 		/* compression failed */
9886 		bcopy(lb, tmpbuf, sizeof (*lb));
9887 		L2BLK_SET_COMPRESS(
9888 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
9889 		    ZIO_COMPRESS_OFF);
9890 	}
9891 
9892 	/* checksum what we're about to write */
9893 	fletcher_4_native(tmpbuf, asize, NULL,
9894 	    &l2dhdr->dh_start_lbps[0].lbp_cksum);
9895 
9896 	abd_put(abd_buf->abd);
9897 
9898 	/* perform the write itself */
9899 	abd_buf->abd = abd_get_from_buf(tmpbuf, sizeof (*lb));
9900 	abd_take_ownership_of_buf(abd_buf->abd, B_TRUE);
9901 	wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
9902 	    asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
9903 	    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
9904 	DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
9905 	(void) zio_nowait(wzio);
9906 
9907 	dev->l2ad_hand += asize;
9908 	/*
9909 	 * Include the committed log block's pointer  in the list of pointers
9910 	 * to log blocks present in the L2ARC device.
9911 	 */
9912 	bcopy(&l2dhdr->dh_start_lbps[0], lb_ptr_buf->lb_ptr,
9913 	    sizeof (l2arc_log_blkptr_t));
9914 	mutex_enter(&dev->l2ad_mtx);
9915 	list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
9916 	ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
9917 	ARCSTAT_BUMP(arcstat_l2_log_blk_count);
9918 	zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
9919 	zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
9920 	mutex_exit(&dev->l2ad_mtx);
9921 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9922 
9923 	/* bump the kstats */
9924 	ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
9925 	ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
9926 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
9927 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
9928 	    dev->l2ad_log_blk_payload_asize / asize);
9929 
9930 	/* start a new log block */
9931 	dev->l2ad_log_ent_idx = 0;
9932 	dev->l2ad_log_blk_payload_asize = 0;
9933 	dev->l2ad_log_blk_payload_start = 0;
9934 }
9935 
9936 /*
9937  * Validates an L2ARC log block address to make sure that it can be read
9938  * from the provided L2ARC device.
9939  */
9940 boolean_t
9941 l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
9942 {
9943 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
9944 	uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
9945 	uint64_t end = lbp->lbp_daddr + asize - 1;
9946 	uint64_t start = lbp->lbp_payload_start;
9947 	boolean_t evicted = B_FALSE;
9948 
9949 	/* BEGIN CSTYLED */
9950 	/*
9951 	 * A log block is valid if all of the following conditions are true:
9952 	 * - it fits entirely (including its payload) between l2ad_start and
9953 	 *   l2ad_end
9954 	 * - it has a valid size
9955 	 * - neither the log block itself nor part of its payload was evicted
9956 	 *   by l2arc_evict():
9957 	 *
9958 	 *		l2ad_hand          l2ad_evict
9959 	 *		|			 |	lbp_daddr
9960 	 *		|     start		 |	|  end
9961 	 *		|     |			 |	|  |
9962 	 *		V     V		         V	V  V
9963 	 *   l2ad_start ============================================ l2ad_end
9964 	 *                    --------------------------||||
9965 	 *				^		 ^
9966 	 *				|		log block
9967 	 *				payload
9968 	 */
9969 	/* END CSTYLED */
9970 	evicted =
9971 	    l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
9972 	    l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
9973 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
9974 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
9975 
9976 	return (start >= dev->l2ad_start && end <= dev->l2ad_end &&
9977 	    asize > 0 && asize <= sizeof (l2arc_log_blk_phys_t) &&
9978 	    (!evicted || dev->l2ad_first));
9979 }
9980 
9981 /*
9982  * Inserts ARC buffer header `hdr' into the current L2ARC log block on
9983  * the device. The buffer being inserted must be present in L2ARC.
9984  * Returns B_TRUE if the L2ARC log block is full and needs to be committed
9985  * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
9986  */
9987 static boolean_t
9988 l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
9989 {
9990 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
9991 	l2arc_log_ent_phys_t	*le;
9992 
9993 	if (dev->l2ad_log_entries == 0)
9994 		return (B_FALSE);
9995 
9996 	int index = dev->l2ad_log_ent_idx++;
9997 
9998 	ASSERT3S(index, <, dev->l2ad_log_entries);
9999 	ASSERT(HDR_HAS_L2HDR(hdr));
10000 
10001 	le = &lb->lb_entries[index];
10002 	bzero(le, sizeof (*le));
10003 	le->le_dva = hdr->b_dva;
10004 	le->le_birth = hdr->b_birth;
10005 	le->le_daddr = hdr->b_l2hdr.b_daddr;
10006 	if (index == 0)
10007 		dev->l2ad_log_blk_payload_start = le->le_daddr;
10008 	L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
10009 	L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
10010 	L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
10011 	L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
10012 	L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
10013 	L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
10014 	L2BLK_SET_STATE((le)->le_prop, hdr->b_l1hdr.b_state->arcs_state);
10015 
10016 	dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
10017 	    HDR_GET_PSIZE(hdr));
10018 
10019 	return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
10020 }
10021 
10022 /*
10023  * Checks whether a given L2ARC device address sits in a time-sequential
10024  * range. The trick here is that the L2ARC is a rotary buffer, so we can't
10025  * just do a range comparison, we need to handle the situation in which the
10026  * range wraps around the end of the L2ARC device. Arguments:
10027  *	bottom -- Lower end of the range to check (written to earlier).
10028  *	top    -- Upper end of the range to check (written to later).
10029  *	check  -- The address for which we want to determine if it sits in
10030  *		  between the top and bottom.
10031  *
10032  * The 3-way conditional below represents the following cases:
10033  *
10034  *	bottom < top : Sequentially ordered case:
10035  *	  <check>--------+-------------------+
10036  *	                 |  (overlap here?)  |
10037  *	 L2ARC dev       V                   V
10038  *	 |---------------<bottom>============<top>--------------|
10039  *
10040  *	bottom > top: Looped-around case:
10041  *	                      <check>--------+------------------+
10042  *	                                     |  (overlap here?) |
10043  *	 L2ARC dev                           V                  V
10044  *	 |===============<top>---------------<bottom>===========|
10045  *	 ^               ^
10046  *	 |  (or here?)   |
10047  *	 +---------------+---------<check>
10048  *
10049  *	top == bottom : Just a single address comparison.
10050  */
10051 boolean_t
10052 l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
10053 {
10054 	if (bottom < top)
10055 		return (bottom <= check && check <= top);
10056 	else if (bottom > top)
10057 		return (check <= top || bottom <= check);
10058 	else
10059 		return (check == top);
10060 }
10061