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