xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision e3ae4b35c024af1196582063ecee3ab79367227d)
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 	/*
6137 	 * It would be nice to assert that if its DMU metadata (level >
6138 	 * 0 || it's the dnode file), then it must be syncing context.
6139 	 * But we don't know that information at this level.
6140 	 */
6141 
6142 	mutex_enter(&buf->b_evict_lock);
6143 
6144 	arc_buf_hdr_t *hdr = buf->b_hdr;
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 	 * Wait for any other IO for this hdr, as additional
6187 	 * buf(s) could be about to appear, in which case
6188 	 * we would not want to transition hdr to arc_anon.
6189 	 */
6190 	while (HDR_IO_IN_PROGRESS(hdr)) {
6191 		DTRACE_PROBE1(arc_release__io, arc_buf_hdr_t *, hdr);
6192 		cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
6193 	}
6194 
6195 	/*
6196 	 * This assignment is only valid as long as the hash_lock is
6197 	 * held, we must be careful not to reference state or the
6198 	 * b_state field after dropping the lock.
6199 	 */
6200 	arc_state_t *state = hdr->b_l1hdr.b_state;
6201 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6202 	ASSERT3P(state, !=, arc_anon);
6203 
6204 	/* this buffer is not on any list */
6205 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6206 
6207 	if (HDR_HAS_L2HDR(hdr)) {
6208 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6209 
6210 		/*
6211 		 * We have to recheck this conditional again now that
6212 		 * we're holding the l2ad_mtx to prevent a race with
6213 		 * another thread which might be concurrently calling
6214 		 * l2arc_evict(). In that case, l2arc_evict() might have
6215 		 * destroyed the header's L2 portion as we were waiting
6216 		 * to acquire the l2ad_mtx.
6217 		 */
6218 		if (HDR_HAS_L2HDR(hdr))
6219 			arc_hdr_l2hdr_destroy(hdr);
6220 
6221 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6222 	}
6223 
6224 	/*
6225 	 * Do we have more than one buf?
6226 	 */
6227 	if (hdr->b_l1hdr.b_bufcnt > 1) {
6228 		arc_buf_hdr_t *nhdr;
6229 		uint64_t spa = hdr->b_spa;
6230 		uint64_t psize = HDR_GET_PSIZE(hdr);
6231 		uint64_t lsize = HDR_GET_LSIZE(hdr);
6232 		boolean_t protected = HDR_PROTECTED(hdr);
6233 		enum zio_compress compress = arc_hdr_get_compress(hdr);
6234 		arc_buf_contents_t type = arc_buf_type(hdr);
6235 		VERIFY3U(hdr->b_type, ==, type);
6236 
6237 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6238 		(void) remove_reference(hdr, hash_lock, tag);
6239 
6240 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6241 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6242 			ASSERT(ARC_BUF_LAST(buf));
6243 		}
6244 
6245 		/*
6246 		 * Pull the data off of this hdr and attach it to
6247 		 * a new anonymous hdr. Also find the last buffer
6248 		 * in the hdr's buffer list.
6249 		 */
6250 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6251 		ASSERT3P(lastbuf, !=, NULL);
6252 
6253 		/*
6254 		 * If the current arc_buf_t and the hdr are sharing their data
6255 		 * buffer, then we must stop sharing that block.
6256 		 */
6257 		if (arc_buf_is_shared(buf)) {
6258 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6259 			VERIFY(!arc_buf_is_shared(lastbuf));
6260 
6261 			/*
6262 			 * First, sever the block sharing relationship between
6263 			 * buf and the arc_buf_hdr_t.
6264 			 */
6265 			arc_unshare_buf(hdr, buf);
6266 
6267 			/*
6268 			 * Now we need to recreate the hdr's b_pabd. Since we
6269 			 * have lastbuf handy, we try to share with it, but if
6270 			 * we can't then we allocate a new b_pabd and copy the
6271 			 * data from buf into it.
6272 			 */
6273 			if (arc_can_share(hdr, lastbuf)) {
6274 				arc_share_buf(hdr, lastbuf);
6275 			} else {
6276 				arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT);
6277 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6278 				    buf->b_data, psize);
6279 			}
6280 			VERIFY3P(lastbuf->b_data, !=, NULL);
6281 		} else if (HDR_SHARED_DATA(hdr)) {
6282 			/*
6283 			 * Uncompressed shared buffers are always at the end
6284 			 * of the list. Compressed buffers don't have the
6285 			 * same requirements. This makes it hard to
6286 			 * simply assert that the lastbuf is shared so
6287 			 * we rely on the hdr's compression flags to determine
6288 			 * if we have a compressed, shared buffer.
6289 			 */
6290 			ASSERT(arc_buf_is_shared(lastbuf) ||
6291 			    arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF);
6292 			ASSERT(!ARC_BUF_SHARED(buf));
6293 		}
6294 		ASSERT(hdr->b_l1hdr.b_pabd != NULL || HDR_HAS_RABD(hdr));
6295 		ASSERT3P(state, !=, arc_l2c_only);
6296 
6297 		(void) zfs_refcount_remove_many(&state->arcs_size,
6298 		    arc_buf_size(buf), buf);
6299 
6300 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6301 			ASSERT3P(state, !=, arc_l2c_only);
6302 			(void) zfs_refcount_remove_many(
6303 			    &state->arcs_esize[type],
6304 			    arc_buf_size(buf), buf);
6305 		}
6306 
6307 		hdr->b_l1hdr.b_bufcnt -= 1;
6308 		if (ARC_BUF_ENCRYPTED(buf))
6309 			hdr->b_crypt_hdr.b_ebufcnt -= 1;
6310 
6311 		arc_cksum_verify(buf);
6312 		arc_buf_unwatch(buf);
6313 
6314 		/* if this is the last uncompressed buf free the checksum */
6315 		if (!arc_hdr_has_uncompressed_buf(hdr))
6316 			arc_cksum_free(hdr);
6317 
6318 		mutex_exit(hash_lock);
6319 
6320 		/*
6321 		 * Allocate a new hdr. The new hdr will contain a b_pabd
6322 		 * buffer which will be freed in arc_write().
6323 		 */
6324 		nhdr = arc_hdr_alloc(spa, psize, lsize, protected,
6325 		    compress, type, HDR_HAS_RABD(hdr));
6326 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6327 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6328 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
6329 		VERIFY3U(nhdr->b_type, ==, type);
6330 		ASSERT(!HDR_SHARED_DATA(nhdr));
6331 
6332 		nhdr->b_l1hdr.b_buf = buf;
6333 		nhdr->b_l1hdr.b_bufcnt = 1;
6334 		if (ARC_BUF_ENCRYPTED(buf))
6335 			nhdr->b_crypt_hdr.b_ebufcnt = 1;
6336 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6337 		buf->b_hdr = nhdr;
6338 
6339 		mutex_exit(&buf->b_evict_lock);
6340 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
6341 		    arc_buf_size(buf), buf);
6342 	} else {
6343 		mutex_exit(&buf->b_evict_lock);
6344 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6345 		/* protected by hash lock, or hdr is on arc_anon */
6346 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6347 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6348 		arc_change_state(arc_anon, hdr, hash_lock);
6349 		hdr->b_l1hdr.b_arc_access = 0;
6350 
6351 		mutex_exit(hash_lock);
6352 		buf_discard_identity(hdr);
6353 		arc_buf_thaw(buf);
6354 	}
6355 }
6356 
6357 int
6358 arc_released(arc_buf_t *buf)
6359 {
6360 	int released;
6361 
6362 	mutex_enter(&buf->b_evict_lock);
6363 	released = (buf->b_data != NULL &&
6364 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
6365 	mutex_exit(&buf->b_evict_lock);
6366 	return (released);
6367 }
6368 
6369 #ifdef ZFS_DEBUG
6370 int
6371 arc_referenced(arc_buf_t *buf)
6372 {
6373 	int referenced;
6374 
6375 	mutex_enter(&buf->b_evict_lock);
6376 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6377 	mutex_exit(&buf->b_evict_lock);
6378 	return (referenced);
6379 }
6380 #endif
6381 
6382 static void
6383 arc_write_ready(zio_t *zio)
6384 {
6385 	arc_write_callback_t *callback = zio->io_private;
6386 	arc_buf_t *buf = callback->awcb_buf;
6387 	arc_buf_hdr_t *hdr = buf->b_hdr;
6388 	blkptr_t *bp = zio->io_bp;
6389 	uint64_t psize = BP_IS_HOLE(bp) ? 0 : BP_GET_PSIZE(bp);
6390 
6391 	ASSERT(HDR_HAS_L1HDR(hdr));
6392 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6393 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6394 
6395 	/*
6396 	 * If we're reexecuting this zio because the pool suspended, then
6397 	 * cleanup any state that was previously set the first time the
6398 	 * callback was invoked.
6399 	 */
6400 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6401 		arc_cksum_free(hdr);
6402 		arc_buf_unwatch(buf);
6403 		if (hdr->b_l1hdr.b_pabd != NULL) {
6404 			if (arc_buf_is_shared(buf)) {
6405 				arc_unshare_buf(hdr, buf);
6406 			} else {
6407 				arc_hdr_free_pabd(hdr, B_FALSE);
6408 			}
6409 		}
6410 
6411 		if (HDR_HAS_RABD(hdr))
6412 			arc_hdr_free_pabd(hdr, B_TRUE);
6413 	}
6414 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6415 	ASSERT(!HDR_HAS_RABD(hdr));
6416 	ASSERT(!HDR_SHARED_DATA(hdr));
6417 	ASSERT(!arc_buf_is_shared(buf));
6418 
6419 	callback->awcb_ready(zio, buf, callback->awcb_private);
6420 
6421 	if (HDR_IO_IN_PROGRESS(hdr))
6422 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6423 
6424 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6425 
6426 	if (BP_IS_PROTECTED(bp) != !!HDR_PROTECTED(hdr))
6427 		hdr = arc_hdr_realloc_crypt(hdr, BP_IS_PROTECTED(bp));
6428 
6429 	if (BP_IS_PROTECTED(bp)) {
6430 		/* ZIL blocks are written through zio_rewrite */
6431 		ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
6432 		ASSERT(HDR_PROTECTED(hdr));
6433 
6434 		if (BP_SHOULD_BYTESWAP(bp)) {
6435 			if (BP_GET_LEVEL(bp) > 0) {
6436 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
6437 			} else {
6438 				hdr->b_l1hdr.b_byteswap =
6439 				    DMU_OT_BYTESWAP(BP_GET_TYPE(bp));
6440 			}
6441 		} else {
6442 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
6443 		}
6444 
6445 		hdr->b_crypt_hdr.b_ot = BP_GET_TYPE(bp);
6446 		hdr->b_crypt_hdr.b_dsobj = zio->io_bookmark.zb_objset;
6447 		zio_crypt_decode_params_bp(bp, hdr->b_crypt_hdr.b_salt,
6448 		    hdr->b_crypt_hdr.b_iv);
6449 		zio_crypt_decode_mac_bp(bp, hdr->b_crypt_hdr.b_mac);
6450 	}
6451 
6452 	/*
6453 	 * If this block was written for raw encryption but the zio layer
6454 	 * ended up only authenticating it, adjust the buffer flags now.
6455 	 */
6456 	if (BP_IS_AUTHENTICATED(bp) && ARC_BUF_ENCRYPTED(buf)) {
6457 		arc_hdr_set_flags(hdr, ARC_FLAG_NOAUTH);
6458 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6459 		if (BP_GET_COMPRESS(bp) == ZIO_COMPRESS_OFF)
6460 			buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6461 	} else if (BP_IS_HOLE(bp) && ARC_BUF_ENCRYPTED(buf)) {
6462 		buf->b_flags &= ~ARC_BUF_FLAG_ENCRYPTED;
6463 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
6464 	}
6465 
6466 	/* this must be done after the buffer flags are adjusted */
6467 	arc_cksum_compute(buf);
6468 
6469 	enum zio_compress compress;
6470 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
6471 		compress = ZIO_COMPRESS_OFF;
6472 	} else {
6473 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
6474 		compress = BP_GET_COMPRESS(bp);
6475 	}
6476 	HDR_SET_PSIZE(hdr, psize);
6477 	arc_hdr_set_compress(hdr, compress);
6478 
6479 	if (zio->io_error != 0 || psize == 0)
6480 		goto out;
6481 
6482 	/*
6483 	 * Fill the hdr with data. If the buffer is encrypted we have no choice
6484 	 * but to copy the data into b_rabd. If the hdr is compressed, the data
6485 	 * we want is available from the zio, otherwise we can take it from
6486 	 * the buf.
6487 	 *
6488 	 * We might be able to share the buf's data with the hdr here. However,
6489 	 * doing so would cause the ARC to be full of linear ABDs if we write a
6490 	 * lot of shareable data. As a compromise, we check whether scattered
6491 	 * ABDs are allowed, and assume that if they are then the user wants
6492 	 * the ARC to be primarily filled with them regardless of the data being
6493 	 * written. Therefore, if they're allowed then we allocate one and copy
6494 	 * the data into it; otherwise, we share the data directly if we can.
6495 	 */
6496 	if (ARC_BUF_ENCRYPTED(buf)) {
6497 		ASSERT3U(psize, >, 0);
6498 		ASSERT(ARC_BUF_COMPRESSED(buf));
6499 		arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6500 		abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6501 	} else if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6502 		/*
6503 		 * Ideally, we would always copy the io_abd into b_pabd, but the
6504 		 * user may have disabled compressed ARC, thus we must check the
6505 		 * hdr's compression setting rather than the io_bp's.
6506 		 */
6507 		if (BP_IS_ENCRYPTED(bp)) {
6508 			ASSERT3U(psize, >, 0);
6509 			arc_hdr_alloc_pabd(hdr,
6510 			    ARC_HDR_DO_ADAPT|ARC_HDR_ALLOC_RDATA);
6511 			abd_copy(hdr->b_crypt_hdr.b_rabd, zio->io_abd, psize);
6512 		} else if (arc_hdr_get_compress(hdr) != ZIO_COMPRESS_OFF &&
6513 		    !ARC_BUF_COMPRESSED(buf)) {
6514 			ASSERT3U(psize, >, 0);
6515 			arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT);
6516 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6517 		} else {
6518 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6519 			arc_hdr_alloc_pabd(hdr, ARC_HDR_DO_ADAPT);
6520 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6521 			    arc_buf_size(buf));
6522 		}
6523 	} else {
6524 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6525 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6526 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6527 		arc_share_buf(hdr, buf);
6528 	}
6529 
6530 out:
6531 	arc_hdr_verify(hdr, bp);
6532 }
6533 
6534 static void
6535 arc_write_children_ready(zio_t *zio)
6536 {
6537 	arc_write_callback_t *callback = zio->io_private;
6538 	arc_buf_t *buf = callback->awcb_buf;
6539 
6540 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
6541 }
6542 
6543 /*
6544  * The SPA calls this callback for each physical write that happens on behalf
6545  * of a logical write.  See the comment in dbuf_write_physdone() for details.
6546  */
6547 static void
6548 arc_write_physdone(zio_t *zio)
6549 {
6550 	arc_write_callback_t *cb = zio->io_private;
6551 	if (cb->awcb_physdone != NULL)
6552 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6553 }
6554 
6555 static void
6556 arc_write_done(zio_t *zio)
6557 {
6558 	arc_write_callback_t *callback = zio->io_private;
6559 	arc_buf_t *buf = callback->awcb_buf;
6560 	arc_buf_hdr_t *hdr = buf->b_hdr;
6561 
6562 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6563 
6564 	if (zio->io_error == 0) {
6565 		arc_hdr_verify(hdr, zio->io_bp);
6566 
6567 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6568 			buf_discard_identity(hdr);
6569 		} else {
6570 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6571 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6572 		}
6573 	} else {
6574 		ASSERT(HDR_EMPTY(hdr));
6575 	}
6576 
6577 	/*
6578 	 * If the block to be written was all-zero or compressed enough to be
6579 	 * embedded in the BP, no write was performed so there will be no
6580 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
6581 	 * (and uncached).
6582 	 */
6583 	if (!HDR_EMPTY(hdr)) {
6584 		arc_buf_hdr_t *exists;
6585 		kmutex_t *hash_lock;
6586 
6587 		ASSERT3U(zio->io_error, ==, 0);
6588 
6589 		arc_cksum_verify(buf);
6590 
6591 		exists = buf_hash_insert(hdr, &hash_lock);
6592 		if (exists != NULL) {
6593 			/*
6594 			 * This can only happen if we overwrite for
6595 			 * sync-to-convergence, because we remove
6596 			 * buffers from the hash table when we arc_free().
6597 			 */
6598 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6599 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6600 					panic("bad overwrite, hdr=%p exists=%p",
6601 					    (void *)hdr, (void *)exists);
6602 				ASSERT(zfs_refcount_is_zero(
6603 				    &exists->b_l1hdr.b_refcnt));
6604 				arc_change_state(arc_anon, exists, hash_lock);
6605 				arc_hdr_destroy(exists);
6606 				mutex_exit(hash_lock);
6607 				exists = buf_hash_insert(hdr, &hash_lock);
6608 				ASSERT3P(exists, ==, NULL);
6609 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6610 				/* nopwrite */
6611 				ASSERT(zio->io_prop.zp_nopwrite);
6612 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6613 					panic("bad nopwrite, hdr=%p exists=%p",
6614 					    (void *)hdr, (void *)exists);
6615 			} else {
6616 				/* Dedup */
6617 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6618 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6619 				ASSERT(BP_GET_DEDUP(zio->io_bp));
6620 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6621 			}
6622 		}
6623 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6624 		/* if it's not anon, we are doing a scrub */
6625 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6626 			arc_access(hdr, hash_lock);
6627 		mutex_exit(hash_lock);
6628 	} else {
6629 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6630 	}
6631 
6632 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6633 	callback->awcb_done(zio, buf, callback->awcb_private);
6634 
6635 	abd_put(zio->io_abd);
6636 	kmem_free(callback, sizeof (arc_write_callback_t));
6637 }
6638 
6639 zio_t *
6640 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6641     boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6642     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6643     arc_write_done_func_t *done, void *private, zio_priority_t priority,
6644     int zio_flags, const zbookmark_phys_t *zb)
6645 {
6646 	arc_buf_hdr_t *hdr = buf->b_hdr;
6647 	arc_write_callback_t *callback;
6648 	zio_t *zio;
6649 	zio_prop_t localprop = *zp;
6650 
6651 	ASSERT3P(ready, !=, NULL);
6652 	ASSERT3P(done, !=, NULL);
6653 	ASSERT(!HDR_IO_ERROR(hdr));
6654 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6655 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6656 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6657 	if (l2arc)
6658 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6659 
6660 	if (ARC_BUF_ENCRYPTED(buf)) {
6661 		ASSERT(ARC_BUF_COMPRESSED(buf));
6662 		localprop.zp_encrypt = B_TRUE;
6663 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6664 		/* CONSTCOND */
6665 		localprop.zp_byteorder =
6666 		    (hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS) ?
6667 		    ZFS_HOST_BYTEORDER : !ZFS_HOST_BYTEORDER;
6668 		bcopy(hdr->b_crypt_hdr.b_salt, localprop.zp_salt,
6669 		    ZIO_DATA_SALT_LEN);
6670 		bcopy(hdr->b_crypt_hdr.b_iv, localprop.zp_iv,
6671 		    ZIO_DATA_IV_LEN);
6672 		bcopy(hdr->b_crypt_hdr.b_mac, localprop.zp_mac,
6673 		    ZIO_DATA_MAC_LEN);
6674 		if (DMU_OT_IS_ENCRYPTED(localprop.zp_type)) {
6675 			localprop.zp_nopwrite = B_FALSE;
6676 			localprop.zp_copies =
6677 			    MIN(localprop.zp_copies, SPA_DVAS_PER_BP - 1);
6678 		}
6679 		zio_flags |= ZIO_FLAG_RAW;
6680 	} else if (ARC_BUF_COMPRESSED(buf)) {
6681 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6682 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6683 		zio_flags |= ZIO_FLAG_RAW_COMPRESS;
6684 	}
6685 
6686 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6687 	callback->awcb_ready = ready;
6688 	callback->awcb_children_ready = children_ready;
6689 	callback->awcb_physdone = physdone;
6690 	callback->awcb_done = done;
6691 	callback->awcb_private = private;
6692 	callback->awcb_buf = buf;
6693 
6694 	/*
6695 	 * The hdr's b_pabd is now stale, free it now. A new data block
6696 	 * will be allocated when the zio pipeline calls arc_write_ready().
6697 	 */
6698 	if (hdr->b_l1hdr.b_pabd != NULL) {
6699 		/*
6700 		 * If the buf is currently sharing the data block with
6701 		 * the hdr then we need to break that relationship here.
6702 		 * The hdr will remain with a NULL data pointer and the
6703 		 * buf will take sole ownership of the block.
6704 		 */
6705 		if (arc_buf_is_shared(buf)) {
6706 			arc_unshare_buf(hdr, buf);
6707 		} else {
6708 			arc_hdr_free_pabd(hdr, B_FALSE);
6709 		}
6710 		VERIFY3P(buf->b_data, !=, NULL);
6711 	}
6712 
6713 	if (HDR_HAS_RABD(hdr))
6714 		arc_hdr_free_pabd(hdr, B_TRUE);
6715 
6716 	if (!(zio_flags & ZIO_FLAG_RAW))
6717 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6718 
6719 	ASSERT(!arc_buf_is_shared(buf));
6720 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6721 
6722 	zio = zio_write(pio, spa, txg, bp,
6723 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6724 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6725 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
6726 	    arc_write_physdone, arc_write_done, callback,
6727 	    priority, zio_flags, zb);
6728 
6729 	return (zio);
6730 }
6731 
6732 static int
6733 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
6734 {
6735 #ifdef _KERNEL
6736 	uint64_t available_memory = ptob(freemem);
6737 
6738 
6739 	if (freemem > physmem * arc_lotsfree_percent / 100)
6740 		return (0);
6741 
6742 	if (txg > spa->spa_lowmem_last_txg) {
6743 		spa->spa_lowmem_last_txg = txg;
6744 		spa->spa_lowmem_page_load = 0;
6745 	}
6746 	/*
6747 	 * If we are in pageout, we know that memory is already tight,
6748 	 * the arc is already going to be evicting, so we just want to
6749 	 * continue to let page writes occur as quickly as possible.
6750 	 */
6751 	if (curproc == proc_pageout) {
6752 		if (spa->spa_lowmem_page_load >
6753 		    MAX(ptob(minfree), available_memory) / 4)
6754 			return (SET_ERROR(ERESTART));
6755 		/* Note: reserve is inflated, so we deflate */
6756 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
6757 		return (0);
6758 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
6759 		/* memory is low, delay before restarting */
6760 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6761 		return (SET_ERROR(EAGAIN));
6762 	}
6763 	spa->spa_lowmem_page_load = 0;
6764 #endif /* _KERNEL */
6765 	return (0);
6766 }
6767 
6768 void
6769 arc_tempreserve_clear(uint64_t reserve)
6770 {
6771 	atomic_add_64(&arc_tempreserve, -reserve);
6772 	ASSERT((int64_t)arc_tempreserve >= 0);
6773 }
6774 
6775 int
6776 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
6777 {
6778 	int error;
6779 	uint64_t anon_size;
6780 
6781 	if (reserve > arc_c/4 && !arc_no_grow)
6782 		arc_c = MIN(arc_c_max, reserve * 4);
6783 	if (reserve > arc_c)
6784 		return (SET_ERROR(ENOMEM));
6785 
6786 	/*
6787 	 * Don't count loaned bufs as in flight dirty data to prevent long
6788 	 * network delays from blocking transactions that are ready to be
6789 	 * assigned to a txg.
6790 	 */
6791 
6792 	/* assert that it has not wrapped around */
6793 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6794 
6795 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
6796 	    arc_loaned_bytes), 0);
6797 
6798 	/*
6799 	 * Writes will, almost always, require additional memory allocations
6800 	 * in order to compress/encrypt/etc the data.  We therefore need to
6801 	 * make sure that there is sufficient available memory for this.
6802 	 */
6803 	error = arc_memory_throttle(spa, reserve, txg);
6804 	if (error != 0)
6805 		return (error);
6806 
6807 	/*
6808 	 * Throttle writes when the amount of dirty data in the cache
6809 	 * gets too large.  We try to keep the cache less than half full
6810 	 * of dirty blocks so that our sync times don't grow too large.
6811 	 *
6812 	 * In the case of one pool being built on another pool, we want
6813 	 * to make sure we don't end up throttling the lower (backing)
6814 	 * pool when the upper pool is the majority contributor to dirty
6815 	 * data. To insure we make forward progress during throttling, we
6816 	 * also check the current pool's net dirty data and only throttle
6817 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6818 	 * data in the cache.
6819 	 *
6820 	 * Note: if two requests come in concurrently, we might let them
6821 	 * both succeed, when one of them should fail.  Not a huge deal.
6822 	 */
6823 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6824 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
6825 
6826 	if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
6827 	    anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
6828 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
6829 		uint64_t meta_esize =
6830 		    zfs_refcount_count(
6831 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6832 		uint64_t data_esize =
6833 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6834 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6835 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6836 		    arc_tempreserve >> 10, meta_esize >> 10,
6837 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
6838 		return (SET_ERROR(ERESTART));
6839 	}
6840 	atomic_add_64(&arc_tempreserve, reserve);
6841 	return (0);
6842 }
6843 
6844 static void
6845 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6846     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6847 {
6848 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
6849 	evict_data->value.ui64 =
6850 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6851 	evict_metadata->value.ui64 =
6852 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6853 }
6854 
6855 static int
6856 arc_kstat_update(kstat_t *ksp, int rw)
6857 {
6858 	arc_stats_t *as = ksp->ks_data;
6859 
6860 	if (rw == KSTAT_WRITE) {
6861 		return (EACCES);
6862 	} else {
6863 		arc_kstat_update_state(arc_anon,
6864 		    &as->arcstat_anon_size,
6865 		    &as->arcstat_anon_evictable_data,
6866 		    &as->arcstat_anon_evictable_metadata);
6867 		arc_kstat_update_state(arc_mru,
6868 		    &as->arcstat_mru_size,
6869 		    &as->arcstat_mru_evictable_data,
6870 		    &as->arcstat_mru_evictable_metadata);
6871 		arc_kstat_update_state(arc_mru_ghost,
6872 		    &as->arcstat_mru_ghost_size,
6873 		    &as->arcstat_mru_ghost_evictable_data,
6874 		    &as->arcstat_mru_ghost_evictable_metadata);
6875 		arc_kstat_update_state(arc_mfu,
6876 		    &as->arcstat_mfu_size,
6877 		    &as->arcstat_mfu_evictable_data,
6878 		    &as->arcstat_mfu_evictable_metadata);
6879 		arc_kstat_update_state(arc_mfu_ghost,
6880 		    &as->arcstat_mfu_ghost_size,
6881 		    &as->arcstat_mfu_ghost_evictable_data,
6882 		    &as->arcstat_mfu_ghost_evictable_metadata);
6883 
6884 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6885 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6886 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6887 		ARCSTAT(arcstat_metadata_size) =
6888 		    aggsum_value(&astat_metadata_size);
6889 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6890 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
6891 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6892 	}
6893 
6894 	return (0);
6895 }
6896 
6897 /*
6898  * This function *must* return indices evenly distributed between all
6899  * sublists of the multilist. This is needed due to how the ARC eviction
6900  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6901  * distributed between all sublists and uses this assumption when
6902  * deciding which sublist to evict from and how much to evict from it.
6903  */
6904 unsigned int
6905 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6906 {
6907 	arc_buf_hdr_t *hdr = obj;
6908 
6909 	/*
6910 	 * We rely on b_dva to generate evenly distributed index
6911 	 * numbers using buf_hash below. So, as an added precaution,
6912 	 * let's make sure we never add empty buffers to the arc lists.
6913 	 */
6914 	ASSERT(!HDR_EMPTY(hdr));
6915 
6916 	/*
6917 	 * The assumption here, is the hash value for a given
6918 	 * arc_buf_hdr_t will remain constant throughout its lifetime
6919 	 * (i.e. its b_spa, b_dva, and b_birth fields don't change).
6920 	 * Thus, we don't need to store the header's sublist index
6921 	 * on insertion, as this index can be recalculated on removal.
6922 	 *
6923 	 * Also, the low order bits of the hash value are thought to be
6924 	 * distributed evenly. Otherwise, in the case that the multilist
6925 	 * has a power of two number of sublists, each sublists' usage
6926 	 * would not be evenly distributed.
6927 	 */
6928 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6929 	    multilist_get_num_sublists(ml));
6930 }
6931 
6932 static void
6933 arc_state_init(void)
6934 {
6935 	arc_anon = &ARC_anon;
6936 	arc_mru = &ARC_mru;
6937 	arc_mru_ghost = &ARC_mru_ghost;
6938 	arc_mfu = &ARC_mfu;
6939 	arc_mfu_ghost = &ARC_mfu_ghost;
6940 	arc_l2c_only = &ARC_l2c_only;
6941 
6942 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
6943 	    multilist_create(sizeof (arc_buf_hdr_t),
6944 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6945 	    arc_state_multilist_index_func);
6946 	arc_mru->arcs_list[ARC_BUFC_DATA] =
6947 	    multilist_create(sizeof (arc_buf_hdr_t),
6948 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6949 	    arc_state_multilist_index_func);
6950 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6951 	    multilist_create(sizeof (arc_buf_hdr_t),
6952 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6953 	    arc_state_multilist_index_func);
6954 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6955 	    multilist_create(sizeof (arc_buf_hdr_t),
6956 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6957 	    arc_state_multilist_index_func);
6958 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6959 	    multilist_create(sizeof (arc_buf_hdr_t),
6960 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6961 	    arc_state_multilist_index_func);
6962 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
6963 	    multilist_create(sizeof (arc_buf_hdr_t),
6964 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6965 	    arc_state_multilist_index_func);
6966 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6967 	    multilist_create(sizeof (arc_buf_hdr_t),
6968 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6969 	    arc_state_multilist_index_func);
6970 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6971 	    multilist_create(sizeof (arc_buf_hdr_t),
6972 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6973 	    arc_state_multilist_index_func);
6974 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6975 	    multilist_create(sizeof (arc_buf_hdr_t),
6976 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6977 	    arc_state_multilist_index_func);
6978 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6979 	    multilist_create(sizeof (arc_buf_hdr_t),
6980 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6981 	    arc_state_multilist_index_func);
6982 
6983 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6984 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6985 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6986 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6987 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6988 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6989 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6990 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6991 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6992 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6993 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6994 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6995 
6996 	zfs_refcount_create(&arc_anon->arcs_size);
6997 	zfs_refcount_create(&arc_mru->arcs_size);
6998 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
6999 	zfs_refcount_create(&arc_mfu->arcs_size);
7000 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
7001 	zfs_refcount_create(&arc_l2c_only->arcs_size);
7002 
7003 	aggsum_init(&arc_meta_used, 0);
7004 	aggsum_init(&arc_size, 0);
7005 	aggsum_init(&astat_data_size, 0);
7006 	aggsum_init(&astat_metadata_size, 0);
7007 	aggsum_init(&astat_hdr_size, 0);
7008 	aggsum_init(&astat_other_size, 0);
7009 	aggsum_init(&astat_l2_hdr_size, 0);
7010 
7011 	arc_anon->arcs_state = ARC_STATE_ANON;
7012 	arc_mru->arcs_state = ARC_STATE_MRU;
7013 	arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
7014 	arc_mfu->arcs_state = ARC_STATE_MFU;
7015 	arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
7016 	arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
7017 }
7018 
7019 static void
7020 arc_state_fini(void)
7021 {
7022 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
7023 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
7024 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
7025 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
7026 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
7027 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
7028 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
7029 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
7030 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
7031 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
7032 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
7033 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
7034 
7035 	zfs_refcount_destroy(&arc_anon->arcs_size);
7036 	zfs_refcount_destroy(&arc_mru->arcs_size);
7037 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
7038 	zfs_refcount_destroy(&arc_mfu->arcs_size);
7039 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
7040 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
7041 
7042 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
7043 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
7044 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
7045 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7046 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
7047 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7048 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
7049 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7050 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]);
7051 	multilist_destroy(arc_l2c_only->arcs_list[ARC_BUFC_DATA]);
7052 
7053 	aggsum_fini(&arc_meta_used);
7054 	aggsum_fini(&arc_size);
7055 	aggsum_fini(&astat_data_size);
7056 	aggsum_fini(&astat_metadata_size);
7057 	aggsum_fini(&astat_hdr_size);
7058 	aggsum_fini(&astat_other_size);
7059 	aggsum_fini(&astat_l2_hdr_size);
7060 
7061 }
7062 
7063 uint64_t
7064 arc_max_bytes(void)
7065 {
7066 	return (arc_c_max);
7067 }
7068 
7069 void
7070 arc_init(void)
7071 {
7072 	/*
7073 	 * allmem is "all memory that we could possibly use".
7074 	 */
7075 #ifdef _KERNEL
7076 	uint64_t allmem = ptob(physmem - swapfs_minfree);
7077 #else
7078 	uint64_t allmem = (physmem * PAGESIZE) / 2;
7079 #endif
7080 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
7081 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
7082 
7083 	/*
7084 	 * Set the minimum cache size to 1/64 of all memory, with a hard
7085 	 * minimum of 64MB.
7086 	 */
7087 	arc_c_min = MAX(allmem / 64, 64 << 20);
7088 	/*
7089 	 * In a system with a lot of physical memory this will still result in
7090 	 * an ARC size floor that is quite large in absolute terms.  Cap the
7091 	 * growth of the value at 1GB.
7092 	 */
7093 	arc_c_min = MIN(arc_c_min, 1 << 30);
7094 
7095 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
7096 	if (allmem >= 1 << 30)
7097 		arc_c_max = allmem - (1 << 30);
7098 	else
7099 		arc_c_max = arc_c_min;
7100 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
7101 
7102 	/*
7103 	 * In userland, there's only the memory pressure that we artificially
7104 	 * create (see arc_available_memory()).  Don't let arc_c get too
7105 	 * small, because it can cause transactions to be larger than
7106 	 * arc_c, causing arc_tempreserve_space() to fail.
7107 	 */
7108 #ifndef _KERNEL
7109 	arc_c_min = arc_c_max / 2;
7110 #endif
7111 
7112 	/*
7113 	 * Allow the tunables to override our calculations if they are
7114 	 * reasonable (ie. over 64MB)
7115 	 */
7116 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
7117 		arc_c_max = zfs_arc_max;
7118 		arc_c_min = MIN(arc_c_min, arc_c_max);
7119 	}
7120 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
7121 		arc_c_min = zfs_arc_min;
7122 
7123 	arc_c = arc_c_max;
7124 	arc_p = (arc_c >> 1);
7125 
7126 	/* limit meta-data to 1/4 of the arc capacity */
7127 	arc_meta_limit = arc_c_max / 4;
7128 
7129 #ifdef _KERNEL
7130 	/*
7131 	 * Metadata is stored in the kernel's heap.  Don't let us
7132 	 * use more than half the heap for the ARC.
7133 	 */
7134 	arc_meta_limit = MIN(arc_meta_limit,
7135 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
7136 #endif
7137 
7138 	/* Allow the tunable to override if it is reasonable */
7139 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
7140 		arc_meta_limit = zfs_arc_meta_limit;
7141 
7142 	if (zfs_arc_meta_min > 0) {
7143 		arc_meta_min = zfs_arc_meta_min;
7144 	} else {
7145 		arc_meta_min = arc_c_min / 2;
7146 	}
7147 
7148 	if (zfs_arc_grow_retry > 0)
7149 		arc_grow_retry = zfs_arc_grow_retry;
7150 
7151 	if (zfs_arc_shrink_shift > 0)
7152 		arc_shrink_shift = zfs_arc_shrink_shift;
7153 
7154 	/*
7155 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
7156 	 */
7157 	if (arc_no_grow_shift >= arc_shrink_shift)
7158 		arc_no_grow_shift = arc_shrink_shift - 1;
7159 
7160 	if (zfs_arc_p_min_shift > 0)
7161 		arc_p_min_shift = zfs_arc_p_min_shift;
7162 
7163 	/* if kmem_flags are set, lets try to use less memory */
7164 	if (kmem_debugging())
7165 		arc_c = arc_c / 2;
7166 	if (arc_c < arc_c_min)
7167 		arc_c = arc_c_min;
7168 
7169 	arc_state_init();
7170 
7171 	/*
7172 	 * The arc must be "uninitialized", so that hdr_recl() (which is
7173 	 * registered by buf_init()) will not access arc_reap_zthr before
7174 	 * it is created.
7175 	 */
7176 	ASSERT(!arc_initialized);
7177 	buf_init();
7178 
7179 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7180 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7181 
7182 	if (arc_ksp != NULL) {
7183 		arc_ksp->ks_data = &arc_stats;
7184 		arc_ksp->ks_update = arc_kstat_update;
7185 		kstat_install(arc_ksp);
7186 	}
7187 
7188 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
7189 	    arc_adjust_cb, NULL);
7190 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
7191 	    arc_reap_cb, NULL, SEC2NSEC(1));
7192 
7193 	arc_initialized = B_TRUE;
7194 	arc_warm = B_FALSE;
7195 
7196 	/*
7197 	 * Calculate maximum amount of dirty data per pool.
7198 	 *
7199 	 * If it has been set by /etc/system, take that.
7200 	 * Otherwise, use a percentage of physical memory defined by
7201 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
7202 	 * zfs_dirty_data_max_max (default 4GB).
7203 	 */
7204 	if (zfs_dirty_data_max == 0) {
7205 		zfs_dirty_data_max = physmem * PAGESIZE *
7206 		    zfs_dirty_data_max_percent / 100;
7207 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7208 		    zfs_dirty_data_max_max);
7209 	}
7210 }
7211 
7212 void
7213 arc_fini(void)
7214 {
7215 	/* Use B_TRUE to ensure *all* buffers are evicted */
7216 	arc_flush(NULL, B_TRUE);
7217 
7218 	arc_initialized = B_FALSE;
7219 
7220 	if (arc_ksp != NULL) {
7221 		kstat_delete(arc_ksp);
7222 		arc_ksp = NULL;
7223 	}
7224 
7225 	(void) zthr_cancel(arc_adjust_zthr);
7226 	zthr_destroy(arc_adjust_zthr);
7227 
7228 	(void) zthr_cancel(arc_reap_zthr);
7229 	zthr_destroy(arc_reap_zthr);
7230 
7231 	mutex_destroy(&arc_adjust_lock);
7232 	cv_destroy(&arc_adjust_waiters_cv);
7233 
7234 	/*
7235 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
7236 	 * trigger the release of kmem magazines, which can callback to
7237 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
7238 	 */
7239 	buf_fini();
7240 	arc_state_fini();
7241 
7242 	ASSERT0(arc_loaned_bytes);
7243 }
7244 
7245 /*
7246  * Level 2 ARC
7247  *
7248  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7249  * It uses dedicated storage devices to hold cached data, which are populated
7250  * using large infrequent writes.  The main role of this cache is to boost
7251  * the performance of random read workloads.  The intended L2ARC devices
7252  * include short-stroked disks, solid state disks, and other media with
7253  * substantially faster read latency than disk.
7254  *
7255  *                 +-----------------------+
7256  *                 |         ARC           |
7257  *                 +-----------------------+
7258  *                    |         ^     ^
7259  *                    |         |     |
7260  *      l2arc_feed_thread()    arc_read()
7261  *                    |         |     |
7262  *                    |  l2arc read   |
7263  *                    V         |     |
7264  *               +---------------+    |
7265  *               |     L2ARC     |    |
7266  *               +---------------+    |
7267  *                   |    ^           |
7268  *          l2arc_write() |           |
7269  *                   |    |           |
7270  *                   V    |           |
7271  *                 +-------+      +-------+
7272  *                 | vdev  |      | vdev  |
7273  *                 | cache |      | cache |
7274  *                 +-------+      +-------+
7275  *                 +=========+     .-----.
7276  *                 :  L2ARC  :    |-_____-|
7277  *                 : devices :    | Disks |
7278  *                 +=========+    `-_____-'
7279  *
7280  * Read requests are satisfied from the following sources, in order:
7281  *
7282  *	1) ARC
7283  *	2) vdev cache of L2ARC devices
7284  *	3) L2ARC devices
7285  *	4) vdev cache of disks
7286  *	5) disks
7287  *
7288  * Some L2ARC device types exhibit extremely slow write performance.
7289  * To accommodate for this there are some significant differences between
7290  * the L2ARC and traditional cache design:
7291  *
7292  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
7293  * the ARC behave as usual, freeing buffers and placing headers on ghost
7294  * lists.  The ARC does not send buffers to the L2ARC during eviction as
7295  * this would add inflated write latencies for all ARC memory pressure.
7296  *
7297  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7298  * It does this by periodically scanning buffers from the eviction-end of
7299  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7300  * not already there. It scans until a headroom of buffers is satisfied,
7301  * which itself is a buffer for ARC eviction. If a compressible buffer is
7302  * found during scanning and selected for writing to an L2ARC device, we
7303  * temporarily boost scanning headroom during the next scan cycle to make
7304  * sure we adapt to compression effects (which might significantly reduce
7305  * the data volume we write to L2ARC). The thread that does this is
7306  * l2arc_feed_thread(), illustrated below; example sizes are included to
7307  * provide a better sense of ratio than this diagram:
7308  *
7309  *	       head -->                        tail
7310  *	        +---------------------+----------+
7311  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
7312  *	        +---------------------+----------+   |   o L2ARC eligible
7313  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
7314  *	        +---------------------+----------+   |
7315  *	             15.9 Gbytes      ^ 32 Mbytes    |
7316  *	                           headroom          |
7317  *	                                      l2arc_feed_thread()
7318  *	                                             |
7319  *	                 l2arc write hand <--[oooo]--'
7320  *	                         |           8 Mbyte
7321  *	                         |          write max
7322  *	                         V
7323  *		  +==============================+
7324  *	L2ARC dev |####|#|###|###|    |####| ... |
7325  *	          +==============================+
7326  *	                     32 Gbytes
7327  *
7328  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7329  * evicted, then the L2ARC has cached a buffer much sooner than it probably
7330  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
7331  * safe to say that this is an uncommon case, since buffers at the end of
7332  * the ARC lists have moved there due to inactivity.
7333  *
7334  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7335  * then the L2ARC simply misses copying some buffers.  This serves as a
7336  * pressure valve to prevent heavy read workloads from both stalling the ARC
7337  * with waits and clogging the L2ARC with writes.  This also helps prevent
7338  * the potential for the L2ARC to churn if it attempts to cache content too
7339  * quickly, such as during backups of the entire pool.
7340  *
7341  * 5. After system boot and before the ARC has filled main memory, there are
7342  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7343  * lists can remain mostly static.  Instead of searching from tail of these
7344  * lists as pictured, the l2arc_feed_thread() will search from the list heads
7345  * for eligible buffers, greatly increasing its chance of finding them.
7346  *
7347  * The L2ARC device write speed is also boosted during this time so that
7348  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
7349  * there are no L2ARC reads, and no fear of degrading read performance
7350  * through increased writes.
7351  *
7352  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7353  * the vdev queue can aggregate them into larger and fewer writes.  Each
7354  * device is written to in a rotor fashion, sweeping writes through
7355  * available space then repeating.
7356  *
7357  * 7. The L2ARC does not store dirty content.  It never needs to flush
7358  * write buffers back to disk based storage.
7359  *
7360  * 8. If an ARC buffer is written (and dirtied) which also exists in the
7361  * L2ARC, the now stale L2ARC buffer is immediately dropped.
7362  *
7363  * The performance of the L2ARC can be tweaked by a number of tunables, which
7364  * may be necessary for different workloads:
7365  *
7366  *	l2arc_write_max		max write bytes per interval
7367  *	l2arc_write_boost	extra write bytes during device warmup
7368  *	l2arc_noprefetch	skip caching prefetched buffers
7369  *	l2arc_headroom		number of max device writes to precache
7370  *	l2arc_headroom_boost	when we find compressed buffers during ARC
7371  *				scanning, we multiply headroom by this
7372  *				percentage factor for the next scan cycle,
7373  *				since more compressed buffers are likely to
7374  *				be present
7375  *	l2arc_feed_secs		seconds between L2ARC writing
7376  *
7377  * Tunables may be removed or added as future performance improvements are
7378  * integrated, and also may become zpool properties.
7379  *
7380  * There are three key functions that control how the L2ARC warms up:
7381  *
7382  *	l2arc_write_eligible()	check if a buffer is eligible to cache
7383  *	l2arc_write_size()	calculate how much to write
7384  *	l2arc_write_interval()	calculate sleep delay between writes
7385  *
7386  * These three functions determine what to write, how much, and how quickly
7387  * to send writes.
7388  *
7389  * L2ARC persistence:
7390  *
7391  * When writing buffers to L2ARC, we periodically add some metadata to
7392  * make sure we can pick them up after reboot, thus dramatically reducing
7393  * the impact that any downtime has on the performance of storage systems
7394  * with large caches.
7395  *
7396  * The implementation works fairly simply by integrating the following two
7397  * modifications:
7398  *
7399  * *) When writing to the L2ARC, we occasionally write a "l2arc log block",
7400  *    which is an additional piece of metadata which describes what's been
7401  *    written. This allows us to rebuild the arc_buf_hdr_t structures of the
7402  *    main ARC buffers. There are 2 linked-lists of log blocks headed by
7403  *    dh_start_lbps[2]. We alternate which chain we append to, so they are
7404  *    time-wise and offset-wise interleaved, but that is an optimization rather
7405  *    than for correctness. The log block also includes a pointer to the
7406  *    previous block in its chain.
7407  *
7408  * *) We reserve SPA_MINBLOCKSIZE of space at the start of each L2ARC device
7409  *    for our header bookkeeping purposes. This contains a device header,
7410  *    which contains our top-level reference structures. We update it each
7411  *    time we write a new log block, so that we're able to locate it in the
7412  *    L2ARC device. If this write results in an inconsistent device header
7413  *    (e.g. due to power failure), we detect this by verifying the header's
7414  *    checksum and simply fail to reconstruct the L2ARC after reboot.
7415  *
7416  * Implementation diagram:
7417  *
7418  * +=== L2ARC device (not to scale) ======================================+
7419  * |       ___two newest log block pointers__.__________                  |
7420  * |      /                                   \dh_start_lbps[1]           |
7421  * |	 /				       \         \dh_start_lbps[0]|
7422  * |.___/__.                                    V         V               |
7423  * ||L2 dev|....|lb |bufs |lb |bufs |lb |bufs |lb |bufs |lb |---(empty)---|
7424  * ||   hdr|      ^         /^       /^        /         /                |
7425  * |+------+  ...--\-------/  \-----/--\------/         /                 |
7426  * |                \--------------/    \--------------/                  |
7427  * +======================================================================+
7428  *
7429  * As can be seen on the diagram, rather than using a simple linked list,
7430  * we use a pair of linked lists with alternating elements. This is a
7431  * performance enhancement due to the fact that we only find out the
7432  * address of the next log block access once the current block has been
7433  * completely read in. Obviously, this hurts performance, because we'd be
7434  * keeping the device's I/O queue at only a 1 operation deep, thus
7435  * incurring a large amount of I/O round-trip latency. Having two lists
7436  * allows us to fetch two log blocks ahead of where we are currently
7437  * rebuilding L2ARC buffers.
7438  *
7439  * On-device data structures:
7440  *
7441  * L2ARC device header:	l2arc_dev_hdr_phys_t
7442  * L2ARC log block:	l2arc_log_blk_phys_t
7443  *
7444  * L2ARC reconstruction:
7445  *
7446  * When writing data, we simply write in the standard rotary fashion,
7447  * evicting buffers as we go and simply writing new data over them (writing
7448  * a new log block every now and then). This obviously means that once we
7449  * loop around the end of the device, we will start cutting into an already
7450  * committed log block (and its referenced data buffers), like so:
7451  *
7452  *    current write head__       __old tail
7453  *                        \     /
7454  *                        V    V
7455  * <--|bufs |lb |bufs |lb |    |bufs |lb |bufs |lb |-->
7456  *                         ^    ^^^^^^^^^___________________________________
7457  *                         |                                                \
7458  *                   <<nextwrite>> may overwrite this blk and/or its bufs --'
7459  *
7460  * When importing the pool, we detect this situation and use it to stop
7461  * our scanning process (see l2arc_rebuild).
7462  *
7463  * There is one significant caveat to consider when rebuilding ARC contents
7464  * from an L2ARC device: what about invalidated buffers? Given the above
7465  * construction, we cannot update blocks which we've already written to amend
7466  * them to remove buffers which were invalidated. Thus, during reconstruction,
7467  * we might be populating the cache with buffers for data that's not on the
7468  * main pool anymore, or may have been overwritten!
7469  *
7470  * As it turns out, this isn't a problem. Every arc_read request includes
7471  * both the DVA and, crucially, the birth TXG of the BP the caller is
7472  * looking for. So even if the cache were populated by completely rotten
7473  * blocks for data that had been long deleted and/or overwritten, we'll
7474  * never actually return bad data from the cache, since the DVA with the
7475  * birth TXG uniquely identify a block in space and time - once created,
7476  * a block is immutable on disk. The worst thing we have done is wasted
7477  * some time and memory at l2arc rebuild to reconstruct outdated ARC
7478  * entries that will get dropped from the l2arc as it is being updated
7479  * with new blocks.
7480  *
7481  * L2ARC buffers that have been evicted by l2arc_evict() ahead of the write
7482  * hand are not restored. This is done by saving the offset (in bytes)
7483  * l2arc_evict() has evicted to in the L2ARC device header and taking it
7484  * into account when restoring buffers.
7485  */
7486 
7487 static boolean_t
7488 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7489 {
7490 	/*
7491 	 * A buffer is *not* eligible for the L2ARC if it:
7492 	 * 1. belongs to a different spa.
7493 	 * 2. is already cached on the L2ARC.
7494 	 * 3. has an I/O in progress (it may be an incomplete read).
7495 	 * 4. is flagged not eligible (zfs property).
7496 	 * 5. is a prefetch and l2arc_noprefetch is set.
7497 	 */
7498 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
7499 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr) ||
7500 	    (l2arc_noprefetch && HDR_PREFETCH(hdr)))
7501 		return (B_FALSE);
7502 
7503 	return (B_TRUE);
7504 }
7505 
7506 static uint64_t
7507 l2arc_write_size(l2arc_dev_t *dev)
7508 {
7509 	uint64_t size, dev_size;
7510 
7511 	/*
7512 	 * Make sure our globals have meaningful values in case the user
7513 	 * altered them.
7514 	 */
7515 	size = l2arc_write_max;
7516 	if (size == 0) {
7517 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7518 		    "be greater than zero, resetting it to the default (%d)",
7519 		    L2ARC_WRITE_SIZE);
7520 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
7521 	}
7522 
7523 	if (arc_warm == B_FALSE)
7524 		size += l2arc_write_boost;
7525 
7526 	/*
7527 	 * Make sure the write size does not exceed the size of the cache
7528 	 * device. This is important in l2arc_evict(), otherwise infinite
7529 	 * iteration can occur.
7530 	 */
7531 	dev_size = dev->l2ad_end - dev->l2ad_start;
7532 	if ((size + l2arc_log_blk_overhead(size, dev)) >= dev_size) {
7533 		cmn_err(CE_NOTE, "l2arc_write_max or l2arc_write_boost "
7534 		    "plus the overhead of log blocks (persistent L2ARC, "
7535 		    "%" PRIu64 " bytes) exceeds the size of the cache device "
7536 		    "(guid %" PRIu64 "), resetting them to the default (%d)",
7537 		    l2arc_log_blk_overhead(size, dev),
7538 		    dev->l2ad_vdev->vdev_guid, L2ARC_WRITE_SIZE);
7539 		size = l2arc_write_max = l2arc_write_boost = L2ARC_WRITE_SIZE;
7540 
7541 		if (arc_warm == B_FALSE)
7542 			size += l2arc_write_boost;
7543 	}
7544 
7545 	return (size);
7546 
7547 }
7548 
7549 static clock_t
7550 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7551 {
7552 	clock_t interval, next, now;
7553 
7554 	/*
7555 	 * If the ARC lists are busy, increase our write rate; if the
7556 	 * lists are stale, idle back.  This is achieved by checking
7557 	 * how much we previously wrote - if it was more than half of
7558 	 * what we wanted, schedule the next write much sooner.
7559 	 */
7560 	if (l2arc_feed_again && wrote > (wanted / 2))
7561 		interval = (hz * l2arc_feed_min_ms) / 1000;
7562 	else
7563 		interval = hz * l2arc_feed_secs;
7564 
7565 	now = ddi_get_lbolt();
7566 	next = MAX(now, MIN(now + interval, began + interval));
7567 
7568 	return (next);
7569 }
7570 
7571 /*
7572  * Cycle through L2ARC devices.  This is how L2ARC load balances.
7573  * If a device is returned, this also returns holding the spa config lock.
7574  */
7575 static l2arc_dev_t *
7576 l2arc_dev_get_next(void)
7577 {
7578 	l2arc_dev_t *first, *next = NULL;
7579 
7580 	/*
7581 	 * Lock out the removal of spas (spa_namespace_lock), then removal
7582 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
7583 	 * both locks will be dropped and a spa config lock held instead.
7584 	 */
7585 	mutex_enter(&spa_namespace_lock);
7586 	mutex_enter(&l2arc_dev_mtx);
7587 
7588 	/* if there are no vdevs, there is nothing to do */
7589 	if (l2arc_ndev == 0)
7590 		goto out;
7591 
7592 	first = NULL;
7593 	next = l2arc_dev_last;
7594 	do {
7595 		/* loop around the list looking for a non-faulted vdev */
7596 		if (next == NULL) {
7597 			next = list_head(l2arc_dev_list);
7598 		} else {
7599 			next = list_next(l2arc_dev_list, next);
7600 			if (next == NULL)
7601 				next = list_head(l2arc_dev_list);
7602 		}
7603 
7604 		/* if we have come back to the start, bail out */
7605 		if (first == NULL)
7606 			first = next;
7607 		else if (next == first)
7608 			break;
7609 
7610 	} while (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild);
7611 
7612 	/* if we were unable to find any usable vdevs, return NULL */
7613 	if (vdev_is_dead(next->l2ad_vdev) || next->l2ad_rebuild)
7614 		next = NULL;
7615 
7616 	l2arc_dev_last = next;
7617 
7618 out:
7619 	mutex_exit(&l2arc_dev_mtx);
7620 
7621 	/*
7622 	 * Grab the config lock to prevent the 'next' device from being
7623 	 * removed while we are writing to it.
7624 	 */
7625 	if (next != NULL)
7626 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7627 	mutex_exit(&spa_namespace_lock);
7628 
7629 	return (next);
7630 }
7631 
7632 /*
7633  * Free buffers that were tagged for destruction.
7634  */
7635 static void
7636 l2arc_do_free_on_write()
7637 {
7638 	list_t *buflist;
7639 	l2arc_data_free_t *df, *df_prev;
7640 
7641 	mutex_enter(&l2arc_free_on_write_mtx);
7642 	buflist = l2arc_free_on_write;
7643 
7644 	for (df = list_tail(buflist); df; df = df_prev) {
7645 		df_prev = list_prev(buflist, df);
7646 		ASSERT3P(df->l2df_abd, !=, NULL);
7647 		abd_free(df->l2df_abd);
7648 		list_remove(buflist, df);
7649 		kmem_free(df, sizeof (l2arc_data_free_t));
7650 	}
7651 
7652 	mutex_exit(&l2arc_free_on_write_mtx);
7653 }
7654 
7655 /*
7656  * A write to a cache device has completed.  Update all headers to allow
7657  * reads from these buffers to begin.
7658  */
7659 static void
7660 l2arc_write_done(zio_t *zio)
7661 {
7662 	l2arc_write_callback_t	*cb;
7663 	l2arc_lb_abd_buf_t	*abd_buf;
7664 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
7665 	l2arc_dev_t		*dev;
7666 	l2arc_dev_hdr_phys_t	*l2dhdr;
7667 	list_t			*buflist;
7668 	arc_buf_hdr_t		*head, *hdr, *hdr_prev;
7669 	kmutex_t		*hash_lock;
7670 	int64_t			bytes_dropped = 0;
7671 
7672 	cb = zio->io_private;
7673 	ASSERT3P(cb, !=, NULL);
7674 	dev = cb->l2wcb_dev;
7675 	l2dhdr = dev->l2ad_dev_hdr;
7676 	ASSERT3P(dev, !=, NULL);
7677 	head = cb->l2wcb_head;
7678 	ASSERT3P(head, !=, NULL);
7679 	buflist = &dev->l2ad_buflist;
7680 	ASSERT3P(buflist, !=, NULL);
7681 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7682 	    l2arc_write_callback_t *, cb);
7683 
7684 	/*
7685 	 * All writes completed, or an error was hit.
7686 	 */
7687 top:
7688 	mutex_enter(&dev->l2ad_mtx);
7689 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7690 		hdr_prev = list_prev(buflist, hdr);
7691 
7692 		hash_lock = HDR_LOCK(hdr);
7693 
7694 		/*
7695 		 * We cannot use mutex_enter or else we can deadlock
7696 		 * with l2arc_write_buffers (due to swapping the order
7697 		 * the hash lock and l2ad_mtx are taken).
7698 		 */
7699 		if (!mutex_tryenter(hash_lock)) {
7700 			/*
7701 			 * Missed the hash lock. We must retry so we
7702 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
7703 			 */
7704 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7705 
7706 			/*
7707 			 * We don't want to rescan the headers we've
7708 			 * already marked as having been written out, so
7709 			 * we reinsert the head node so we can pick up
7710 			 * where we left off.
7711 			 */
7712 			list_remove(buflist, head);
7713 			list_insert_after(buflist, hdr, head);
7714 
7715 			mutex_exit(&dev->l2ad_mtx);
7716 
7717 			/*
7718 			 * We wait for the hash lock to become available
7719 			 * to try and prevent busy waiting, and increase
7720 			 * the chance we'll be able to acquire the lock
7721 			 * the next time around.
7722 			 */
7723 			mutex_enter(hash_lock);
7724 			mutex_exit(hash_lock);
7725 			goto top;
7726 		}
7727 
7728 		/*
7729 		 * We could not have been moved into the arc_l2c_only
7730 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
7731 		 * bit being set. Let's just ensure that's being enforced.
7732 		 */
7733 		ASSERT(HDR_HAS_L1HDR(hdr));
7734 
7735 		if (zio->io_error != 0) {
7736 			/*
7737 			 * Error - drop L2ARC entry.
7738 			 */
7739 			list_remove(buflist, hdr);
7740 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7741 
7742 			uint64_t psize = HDR_GET_PSIZE(hdr);
7743 			l2arc_hdr_arcstats_decrement(hdr);
7744 
7745 			bytes_dropped +=
7746 			    vdev_psize_to_asize(dev->l2ad_vdev, psize);
7747 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
7748 			    arc_hdr_size(hdr), hdr);
7749 		}
7750 
7751 		/*
7752 		 * Allow ARC to begin reads and ghost list evictions to
7753 		 * this L2ARC entry.
7754 		 */
7755 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7756 
7757 		mutex_exit(hash_lock);
7758 	}
7759 
7760 	/*
7761 	 * Free the allocated abd buffers for writing the log blocks.
7762 	 * If the zio failed reclaim the allocated space and remove the
7763 	 * pointers to these log blocks from the log block pointer list
7764 	 * of the L2ARC device.
7765 	 */
7766 	while ((abd_buf = list_remove_tail(&cb->l2wcb_abd_list)) != NULL) {
7767 		abd_free(abd_buf->abd);
7768 		zio_buf_free(abd_buf, sizeof (*abd_buf));
7769 		if (zio->io_error != 0) {
7770 			lb_ptr_buf = list_remove_head(&dev->l2ad_lbptr_list);
7771 			/*
7772 			 * L2BLK_GET_PSIZE returns aligned size for log
7773 			 * blocks.
7774 			 */
7775 			uint64_t asize =
7776 			    L2BLK_GET_PSIZE((lb_ptr_buf->lb_ptr)->lbp_prop);
7777 			bytes_dropped += asize;
7778 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
7779 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
7780 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
7781 			    lb_ptr_buf);
7782 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
7783 			kmem_free(lb_ptr_buf->lb_ptr,
7784 			    sizeof (l2arc_log_blkptr_t));
7785 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
7786 		}
7787 	}
7788 	list_destroy(&cb->l2wcb_abd_list);
7789 
7790 	if (zio->io_error != 0) {
7791 		ARCSTAT_BUMP(arcstat_l2_writes_error);
7792 
7793 		/*
7794 		 * Restore the lbps array in the header to its previous state.
7795 		 * If the list of log block pointers is empty, zero out the
7796 		 * log block pointers in the device header.
7797 		 */
7798 		lb_ptr_buf = list_head(&dev->l2ad_lbptr_list);
7799 		for (int i = 0; i < 2; i++) {
7800 			if (lb_ptr_buf == NULL) {
7801 				/*
7802 				 * If the list is empty zero out the device
7803 				 * header. Otherwise zero out the second log
7804 				 * block pointer in the header.
7805 				 */
7806 				if (i == 0) {
7807 					bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
7808 				} else {
7809 					bzero(&l2dhdr->dh_start_lbps[i],
7810 					    sizeof (l2arc_log_blkptr_t));
7811 				}
7812 				break;
7813 			}
7814 			bcopy(lb_ptr_buf->lb_ptr, &l2dhdr->dh_start_lbps[i],
7815 			    sizeof (l2arc_log_blkptr_t));
7816 			lb_ptr_buf = list_next(&dev->l2ad_lbptr_list,
7817 			    lb_ptr_buf);
7818 		}
7819 	}
7820 
7821 	atomic_inc_64(&l2arc_writes_done);
7822 	list_remove(buflist, head);
7823 	ASSERT(!HDR_HAS_L1HDR(head));
7824 	kmem_cache_free(hdr_l2only_cache, head);
7825 	mutex_exit(&dev->l2ad_mtx);
7826 
7827 	ASSERT(dev->l2ad_vdev != NULL);
7828 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7829 
7830 	l2arc_do_free_on_write();
7831 
7832 	kmem_free(cb, sizeof (l2arc_write_callback_t));
7833 }
7834 
7835 static int
7836 l2arc_untransform(zio_t *zio, l2arc_read_callback_t *cb)
7837 {
7838 	int ret;
7839 	spa_t *spa = zio->io_spa;
7840 	arc_buf_hdr_t *hdr = cb->l2rcb_hdr;
7841 	blkptr_t *bp = zio->io_bp;
7842 	uint8_t salt[ZIO_DATA_SALT_LEN];
7843 	uint8_t iv[ZIO_DATA_IV_LEN];
7844 	uint8_t mac[ZIO_DATA_MAC_LEN];
7845 	boolean_t no_crypt = B_FALSE;
7846 
7847 	/*
7848 	 * ZIL data is never be written to the L2ARC, so we don't need
7849 	 * special handling for its unique MAC storage.
7850 	 */
7851 	ASSERT3U(BP_GET_TYPE(bp), !=, DMU_OT_INTENT_LOG);
7852 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
7853 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7854 
7855 	/*
7856 	 * If the data was encrypted, decrypt it now. Note that
7857 	 * we must check the bp here and not the hdr, since the
7858 	 * hdr does not have its encryption parameters updated
7859 	 * until arc_read_done().
7860 	 */
7861 	if (BP_IS_ENCRYPTED(bp)) {
7862 		abd_t *eabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
7863 		    B_TRUE);
7864 
7865 		zio_crypt_decode_params_bp(bp, salt, iv);
7866 		zio_crypt_decode_mac_bp(bp, mac);
7867 
7868 		ret = spa_do_crypt_abd(B_FALSE, spa, &cb->l2rcb_zb,
7869 		    BP_GET_TYPE(bp), BP_GET_DEDUP(bp), BP_SHOULD_BYTESWAP(bp),
7870 		    salt, iv, mac, HDR_GET_PSIZE(hdr), eabd,
7871 		    hdr->b_l1hdr.b_pabd, &no_crypt);
7872 		if (ret != 0) {
7873 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
7874 			goto error;
7875 		}
7876 
7877 		/*
7878 		 * If we actually performed decryption, replace b_pabd
7879 		 * with the decrypted data. Otherwise we can just throw
7880 		 * our decryption buffer away.
7881 		 */
7882 		if (!no_crypt) {
7883 			arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
7884 			    arc_hdr_size(hdr), hdr);
7885 			hdr->b_l1hdr.b_pabd = eabd;
7886 			zio->io_abd = eabd;
7887 		} else {
7888 			arc_free_data_abd(hdr, eabd, arc_hdr_size(hdr), hdr);
7889 		}
7890 	}
7891 
7892 	/*
7893 	 * If the L2ARC block was compressed, but ARC compression
7894 	 * is disabled we decompress the data into a new buffer and
7895 	 * replace the existing data.
7896 	 */
7897 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
7898 	    !HDR_COMPRESSION_ENABLED(hdr)) {
7899 		abd_t *cabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr,
7900 		    B_TRUE);
7901 		void *tmp = abd_borrow_buf(cabd, arc_hdr_size(hdr));
7902 
7903 		ret = zio_decompress_data(HDR_GET_COMPRESS(hdr),
7904 		    hdr->b_l1hdr.b_pabd, tmp, HDR_GET_PSIZE(hdr),
7905 		    HDR_GET_LSIZE(hdr));
7906 		if (ret != 0) {
7907 			abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
7908 			arc_free_data_abd(hdr, cabd, arc_hdr_size(hdr), hdr);
7909 			goto error;
7910 		}
7911 
7912 		abd_return_buf_copy(cabd, tmp, arc_hdr_size(hdr));
7913 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
7914 		    arc_hdr_size(hdr), hdr);
7915 		hdr->b_l1hdr.b_pabd = cabd;
7916 		zio->io_abd = cabd;
7917 		zio->io_size = HDR_GET_LSIZE(hdr);
7918 	}
7919 
7920 	return (0);
7921 
7922 error:
7923 	return (ret);
7924 }
7925 
7926 
7927 /*
7928  * A read to a cache device completed.  Validate buffer contents before
7929  * handing over to the regular ARC routines.
7930  */
7931 static void
7932 l2arc_read_done(zio_t *zio)
7933 {
7934 	int tfm_error = 0;
7935 	l2arc_read_callback_t *cb = zio->io_private;
7936 	arc_buf_hdr_t *hdr;
7937 	kmutex_t *hash_lock;
7938 	boolean_t valid_cksum;
7939 	boolean_t using_rdata = (BP_IS_ENCRYPTED(&cb->l2rcb_bp) &&
7940 	    (cb->l2rcb_flags & ZIO_FLAG_RAW_ENCRYPT));
7941 
7942 	ASSERT3P(zio->io_vd, !=, NULL);
7943 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7944 
7945 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7946 
7947 	ASSERT3P(cb, !=, NULL);
7948 	hdr = cb->l2rcb_hdr;
7949 	ASSERT3P(hdr, !=, NULL);
7950 
7951 	hash_lock = HDR_LOCK(hdr);
7952 	mutex_enter(hash_lock);
7953 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7954 
7955 	/*
7956 	 * If the data was read into a temporary buffer,
7957 	 * move it and free the buffer.
7958 	 */
7959 	if (cb->l2rcb_abd != NULL) {
7960 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7961 		if (zio->io_error == 0) {
7962 			if (using_rdata) {
7963 				abd_copy(hdr->b_crypt_hdr.b_rabd,
7964 				    cb->l2rcb_abd, arc_hdr_size(hdr));
7965 			} else {
7966 				abd_copy(hdr->b_l1hdr.b_pabd,
7967 				    cb->l2rcb_abd, arc_hdr_size(hdr));
7968 			}
7969 		}
7970 
7971 		/*
7972 		 * The following must be done regardless of whether
7973 		 * there was an error:
7974 		 * - free the temporary buffer
7975 		 * - point zio to the real ARC buffer
7976 		 * - set zio size accordingly
7977 		 * These are required because zio is either re-used for
7978 		 * an I/O of the block in the case of the error
7979 		 * or the zio is passed to arc_read_done() and it
7980 		 * needs real data.
7981 		 */
7982 		abd_free(cb->l2rcb_abd);
7983 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7984 
7985 		if (using_rdata) {
7986 			ASSERT(HDR_HAS_RABD(hdr));
7987 			zio->io_abd = zio->io_orig_abd =
7988 			    hdr->b_crypt_hdr.b_rabd;
7989 		} else {
7990 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7991 			zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
7992 		}
7993 	}
7994 
7995 	ASSERT3P(zio->io_abd, !=, NULL);
7996 
7997 	/*
7998 	 * Check this survived the L2ARC journey.
7999 	 */
8000 	ASSERT(zio->io_abd == hdr->b_l1hdr.b_pabd ||
8001 	    (HDR_HAS_RABD(hdr) && zio->io_abd == hdr->b_crypt_hdr.b_rabd));
8002 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
8003 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
8004 
8005 	valid_cksum = arc_cksum_is_equal(hdr, zio);
8006 
8007 	/*
8008 	 * b_rabd will always match the data as it exists on disk if it is
8009 	 * being used. Therefore if we are reading into b_rabd we do not
8010 	 * attempt to untransform the data.
8011 	 */
8012 	if (valid_cksum && !using_rdata)
8013 		tfm_error = l2arc_untransform(zio, cb);
8014 
8015 	if (valid_cksum && tfm_error == 0 && zio->io_error == 0 &&
8016 	    !HDR_L2_EVICTED(hdr)) {
8017 		mutex_exit(hash_lock);
8018 		zio->io_private = hdr;
8019 		arc_read_done(zio);
8020 	} else {
8021 		/*
8022 		 * Buffer didn't survive caching.  Increment stats and
8023 		 * reissue to the original storage device.
8024 		 */
8025 		if (zio->io_error != 0) {
8026 			ARCSTAT_BUMP(arcstat_l2_io_error);
8027 		} else {
8028 			zio->io_error = SET_ERROR(EIO);
8029 		}
8030 		if (!valid_cksum || tfm_error != 0)
8031 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
8032 
8033 		/*
8034 		 * If there's no waiter, issue an async i/o to the primary
8035 		 * storage now.  If there *is* a waiter, the caller must
8036 		 * issue the i/o in a context where it's OK to block.
8037 		 */
8038 		if (zio->io_waiter == NULL) {
8039 			zio_t *pio = zio_unique_parent(zio);
8040 			void *abd = (using_rdata) ?
8041 			    hdr->b_crypt_hdr.b_rabd : hdr->b_l1hdr.b_pabd;
8042 
8043 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
8044 
8045 			zio = zio_read(pio, zio->io_spa, zio->io_bp,
8046 			    abd, zio->io_size, arc_read_done,
8047 			    hdr, zio->io_priority, cb->l2rcb_flags,
8048 			    &cb->l2rcb_zb);
8049 
8050 			/*
8051 			 * Original ZIO will be freed, so we need to update
8052 			 * ARC header with the new ZIO pointer to be used
8053 			 * by zio_change_priority() in arc_read().
8054 			 */
8055 			for (struct arc_callback *acb = hdr->b_l1hdr.b_acb;
8056 			    acb != NULL; acb = acb->acb_next)
8057 				acb->acb_zio_head = zio;
8058 
8059 			mutex_exit(hash_lock);
8060 			zio_nowait(zio);
8061 		} else {
8062 			mutex_exit(hash_lock);
8063 		}
8064 	}
8065 
8066 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8067 }
8068 
8069 /*
8070  * This is the list priority from which the L2ARC will search for pages to
8071  * cache.  This is used within loops (0..3) to cycle through lists in the
8072  * desired order.  This order can have a significant effect on cache
8073  * performance.
8074  *
8075  * Currently the metadata lists are hit first, MFU then MRU, followed by
8076  * the data lists.  This function returns a locked list, and also returns
8077  * the lock pointer.
8078  */
8079 static multilist_sublist_t *
8080 l2arc_sublist_lock(int list_num)
8081 {
8082 	multilist_t *ml = NULL;
8083 	unsigned int idx;
8084 
8085 	ASSERT(list_num >= 0 && list_num < L2ARC_FEED_TYPES);
8086 
8087 	switch (list_num) {
8088 	case 0:
8089 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
8090 		break;
8091 	case 1:
8092 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
8093 		break;
8094 	case 2:
8095 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
8096 		break;
8097 	case 3:
8098 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
8099 		break;
8100 	default:
8101 		return (NULL);
8102 	}
8103 
8104 	/*
8105 	 * Return a randomly-selected sublist. This is acceptable
8106 	 * because the caller feeds only a little bit of data for each
8107 	 * call (8MB). Subsequent calls will result in different
8108 	 * sublists being selected.
8109 	 */
8110 	idx = multilist_get_random_index(ml);
8111 	return (multilist_sublist_lock(ml, idx));
8112 }
8113 
8114 /*
8115  * Calculates the maximum overhead of L2ARC metadata log blocks for a given
8116  * L2ARC write size. l2arc_evict and l2arc_write_size need to include this
8117  * overhead in processing to make sure there is enough headroom available
8118  * when writing buffers.
8119  */
8120 static inline uint64_t
8121 l2arc_log_blk_overhead(uint64_t write_sz, l2arc_dev_t *dev)
8122 {
8123 	if (dev->l2ad_log_entries == 0) {
8124 		return (0);
8125 	} else {
8126 		uint64_t log_entries = write_sz >> SPA_MINBLOCKSHIFT;
8127 
8128 		uint64_t log_blocks = (log_entries +
8129 		    dev->l2ad_log_entries - 1) /
8130 		    dev->l2ad_log_entries;
8131 
8132 		return (vdev_psize_to_asize(dev->l2ad_vdev,
8133 		    sizeof (l2arc_log_blk_phys_t)) * log_blocks);
8134 	}
8135 }
8136 
8137 /*
8138  * Evict buffers from the device write hand to the distance specified in
8139  * bytes. This distance may span populated buffers, it may span nothing.
8140  * This is clearing a region on the L2ARC device ready for writing.
8141  * If the 'all' boolean is set, every buffer is evicted.
8142  */
8143 static void
8144 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
8145 {
8146 	list_t *buflist;
8147 	arc_buf_hdr_t *hdr, *hdr_prev;
8148 	kmutex_t *hash_lock;
8149 	uint64_t taddr;
8150 	l2arc_lb_ptr_buf_t *lb_ptr_buf, *lb_ptr_buf_prev;
8151 	boolean_t rerun;
8152 
8153 	buflist = &dev->l2ad_buflist;
8154 
8155 	/*
8156 	 * We need to add in the worst case scenario of log block overhead.
8157 	 */
8158 	distance += l2arc_log_blk_overhead(distance, dev);
8159 
8160 top:
8161 	rerun = B_FALSE;
8162 	if (dev->l2ad_hand >= (dev->l2ad_end - distance)) {
8163 		/*
8164 		 * When there is no space to accommodate upcoming writes,
8165 		 * evict to the end. Then bump the write and evict hands
8166 		 * to the start and iterate. This iteration does not
8167 		 * happen indefinitely as we make sure in
8168 		 * l2arc_write_size() that when the write hand is reset,
8169 		 * the write size does not exceed the end of the device.
8170 		 */
8171 		rerun = B_TRUE;
8172 		taddr = dev->l2ad_end;
8173 	} else {
8174 		taddr = dev->l2ad_hand + distance;
8175 	}
8176 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
8177 	    uint64_t, taddr, boolean_t, all);
8178 
8179 	/*
8180 	 * This check has to be placed after deciding whether to iterate
8181 	 * (rerun).
8182 	 */
8183 	if (!all && dev->l2ad_first) {
8184 		/*
8185 		 * This is the first sweep through the device. There is
8186 		 * nothing to evict.
8187 		 */
8188 		goto out;
8189 	}
8190 
8191 	/*
8192 	 * When rebuilding L2ARC we retrieve the evict hand from the header of
8193 	 * the device. Of note, l2arc_evict() does not actually delete buffers
8194 	 * from the cache device, but keeping track of the evict hand will be
8195 	 * useful when TRIM is implemented.
8196 	 */
8197 	dev->l2ad_evict = MAX(dev->l2ad_evict, taddr);
8198 
8199 retry:
8200 	mutex_enter(&dev->l2ad_mtx);
8201 	/*
8202 	 * We have to account for evicted log blocks. Run vdev_space_update()
8203 	 * on log blocks whose offset (in bytes) is before the evicted offset
8204 	 * (in bytes) by searching in the list of pointers to log blocks
8205 	 * present in the L2ARC device.
8206 	 */
8207 	for (lb_ptr_buf = list_tail(&dev->l2ad_lbptr_list); lb_ptr_buf;
8208 	    lb_ptr_buf = lb_ptr_buf_prev) {
8209 
8210 		lb_ptr_buf_prev = list_prev(&dev->l2ad_lbptr_list, lb_ptr_buf);
8211 
8212 		/* L2BLK_GET_PSIZE returns aligned size for log blocks */
8213 		uint64_t asize = L2BLK_GET_PSIZE(
8214 		    (lb_ptr_buf->lb_ptr)->lbp_prop);
8215 
8216 		/*
8217 		 * We don't worry about log blocks left behind (ie
8218 		 * lbp_payload_start < l2ad_hand) because l2arc_write_buffers()
8219 		 * will never write more than l2arc_evict() evicts.
8220 		 */
8221 		if (!all && l2arc_log_blkptr_valid(dev, lb_ptr_buf->lb_ptr)) {
8222 			break;
8223 		} else {
8224 			vdev_space_update(dev->l2ad_vdev, -asize, 0, 0);
8225 			ARCSTAT_INCR(arcstat_l2_log_blk_asize, -asize);
8226 			ARCSTAT_BUMPDOWN(arcstat_l2_log_blk_count);
8227 			zfs_refcount_remove_many(&dev->l2ad_lb_asize, asize,
8228 			    lb_ptr_buf);
8229 			zfs_refcount_remove(&dev->l2ad_lb_count, lb_ptr_buf);
8230 			list_remove(&dev->l2ad_lbptr_list, lb_ptr_buf);
8231 			kmem_free(lb_ptr_buf->lb_ptr,
8232 			    sizeof (l2arc_log_blkptr_t));
8233 			kmem_free(lb_ptr_buf, sizeof (l2arc_lb_ptr_buf_t));
8234 		}
8235 	}
8236 
8237 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
8238 		hdr_prev = list_prev(buflist, hdr);
8239 
8240 		ASSERT(!HDR_EMPTY(hdr));
8241 		hash_lock = HDR_LOCK(hdr);
8242 
8243 		/*
8244 		 * We cannot use mutex_enter or else we can deadlock
8245 		 * with l2arc_write_buffers (due to swapping the order
8246 		 * the hash lock and l2ad_mtx are taken).
8247 		 */
8248 		if (!mutex_tryenter(hash_lock)) {
8249 			/*
8250 			 * Missed the hash lock.  Retry.
8251 			 */
8252 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
8253 			mutex_exit(&dev->l2ad_mtx);
8254 			mutex_enter(hash_lock);
8255 			mutex_exit(hash_lock);
8256 			goto retry;
8257 		}
8258 
8259 		/*
8260 		 * A header can't be on this list if it doesn't have L2 header.
8261 		 */
8262 		ASSERT(HDR_HAS_L2HDR(hdr));
8263 
8264 		/* Ensure this header has finished being written. */
8265 		ASSERT(!HDR_L2_WRITING(hdr));
8266 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
8267 
8268 		if (!all && (hdr->b_l2hdr.b_daddr >= dev->l2ad_evict ||
8269 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
8270 			/*
8271 			 * We've evicted to the target address,
8272 			 * or the end of the device.
8273 			 */
8274 			mutex_exit(hash_lock);
8275 			break;
8276 		}
8277 
8278 		if (!HDR_HAS_L1HDR(hdr)) {
8279 			ASSERT(!HDR_L2_READING(hdr));
8280 			/*
8281 			 * This doesn't exist in the ARC.  Destroy.
8282 			 * arc_hdr_destroy() will call list_remove()
8283 			 * and decrement arcstat_l2_lsize.
8284 			 */
8285 			arc_change_state(arc_anon, hdr, hash_lock);
8286 			arc_hdr_destroy(hdr);
8287 		} else {
8288 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
8289 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
8290 			/*
8291 			 * Invalidate issued or about to be issued
8292 			 * reads, since we may be about to write
8293 			 * over this location.
8294 			 */
8295 			if (HDR_L2_READING(hdr)) {
8296 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
8297 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
8298 			}
8299 
8300 			arc_hdr_l2hdr_destroy(hdr);
8301 		}
8302 		mutex_exit(hash_lock);
8303 	}
8304 	mutex_exit(&dev->l2ad_mtx);
8305 
8306 out:
8307 	/*
8308 	 * We need to check if we evict all buffers, otherwise we may iterate
8309 	 * unnecessarily.
8310 	 */
8311 	if (!all && rerun) {
8312 		/*
8313 		 * Bump device hand to the device start if it is approaching the
8314 		 * end. l2arc_evict() has already evicted ahead for this case.
8315 		 */
8316 		dev->l2ad_hand = dev->l2ad_start;
8317 		dev->l2ad_evict = dev->l2ad_start;
8318 		dev->l2ad_first = B_FALSE;
8319 		goto top;
8320 	}
8321 
8322 	ASSERT3U(dev->l2ad_hand + distance, <, dev->l2ad_end);
8323 	if (!dev->l2ad_first)
8324 		ASSERT3U(dev->l2ad_hand, <, dev->l2ad_evict);
8325 }
8326 
8327 /*
8328  * Handle any abd transforms that might be required for writing to the L2ARC.
8329  * If successful, this function will always return an abd with the data
8330  * transformed as it is on disk in a new abd of asize bytes.
8331  */
8332 static int
8333 l2arc_apply_transforms(spa_t *spa, arc_buf_hdr_t *hdr, uint64_t asize,
8334     abd_t **abd_out)
8335 {
8336 	int ret;
8337 	void *tmp = NULL;
8338 	abd_t *cabd = NULL, *eabd = NULL, *to_write = hdr->b_l1hdr.b_pabd;
8339 	enum zio_compress compress = HDR_GET_COMPRESS(hdr);
8340 	uint64_t psize = HDR_GET_PSIZE(hdr);
8341 	uint64_t size = arc_hdr_size(hdr);
8342 	boolean_t ismd = HDR_ISTYPE_METADATA(hdr);
8343 	boolean_t bswap = (hdr->b_l1hdr.b_byteswap != DMU_BSWAP_NUMFUNCS);
8344 	dsl_crypto_key_t *dck = NULL;
8345 	uint8_t mac[ZIO_DATA_MAC_LEN] = { 0 };
8346 	boolean_t no_crypt = B_FALSE;
8347 
8348 	ASSERT((HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
8349 	    !HDR_COMPRESSION_ENABLED(hdr)) ||
8350 	    HDR_ENCRYPTED(hdr) || HDR_SHARED_DATA(hdr) || psize != asize);
8351 	ASSERT3U(psize, <=, asize);
8352 
8353 	/*
8354 	 * If this data simply needs its own buffer, we simply allocate it
8355 	 * and copy the data. This may be done to eliminate a dependency on a
8356 	 * shared buffer or to reallocate the buffer to match asize.
8357 	 */
8358 	if (HDR_HAS_RABD(hdr) && asize != psize) {
8359 		ASSERT3U(asize, >=, psize);
8360 		to_write = abd_alloc_for_io(asize, ismd);
8361 		abd_copy(to_write, hdr->b_crypt_hdr.b_rabd, psize);
8362 		if (psize != asize)
8363 			abd_zero_off(to_write, psize, asize - psize);
8364 		goto out;
8365 	}
8366 
8367 	if ((compress == ZIO_COMPRESS_OFF || HDR_COMPRESSION_ENABLED(hdr)) &&
8368 	    !HDR_ENCRYPTED(hdr)) {
8369 		ASSERT3U(size, ==, psize);
8370 		to_write = abd_alloc_for_io(asize, ismd);
8371 		abd_copy(to_write, hdr->b_l1hdr.b_pabd, size);
8372 		if (size != asize)
8373 			abd_zero_off(to_write, size, asize - size);
8374 		goto out;
8375 	}
8376 
8377 	if (compress != ZIO_COMPRESS_OFF && !HDR_COMPRESSION_ENABLED(hdr)) {
8378 		cabd = abd_alloc_for_io(asize, ismd);
8379 		tmp = abd_borrow_buf(cabd, asize);
8380 
8381 		psize = zio_compress_data(compress, to_write, tmp, size);
8382 		ASSERT3U(psize, <=, HDR_GET_PSIZE(hdr));
8383 		if (psize < asize)
8384 			bzero((char *)tmp + psize, asize - psize);
8385 		psize = HDR_GET_PSIZE(hdr);
8386 		abd_return_buf_copy(cabd, tmp, asize);
8387 		to_write = cabd;
8388 	}
8389 
8390 	if (HDR_ENCRYPTED(hdr)) {
8391 		eabd = abd_alloc_for_io(asize, ismd);
8392 
8393 		/*
8394 		 * If the dataset was disowned before the buffer
8395 		 * made it to this point, the key to re-encrypt
8396 		 * it won't be available. In this case we simply
8397 		 * won't write the buffer to the L2ARC.
8398 		 */
8399 		ret = spa_keystore_lookup_key(spa, hdr->b_crypt_hdr.b_dsobj,
8400 		    FTAG, &dck);
8401 		if (ret != 0)
8402 			goto error;
8403 
8404 		ret = zio_do_crypt_abd(B_TRUE, &dck->dck_key,
8405 		    hdr->b_crypt_hdr.b_ot, bswap, hdr->b_crypt_hdr.b_salt,
8406 		    hdr->b_crypt_hdr.b_iv, mac, psize, to_write, eabd,
8407 		    &no_crypt);
8408 		if (ret != 0)
8409 			goto error;
8410 
8411 		if (no_crypt)
8412 			abd_copy(eabd, to_write, psize);
8413 
8414 		if (psize != asize)
8415 			abd_zero_off(eabd, psize, asize - psize);
8416 
8417 		/* assert that the MAC we got here matches the one we saved */
8418 		ASSERT0(bcmp(mac, hdr->b_crypt_hdr.b_mac, ZIO_DATA_MAC_LEN));
8419 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8420 
8421 		if (to_write == cabd)
8422 			abd_free(cabd);
8423 
8424 		to_write = eabd;
8425 	}
8426 
8427 out:
8428 	ASSERT3P(to_write, !=, hdr->b_l1hdr.b_pabd);
8429 	*abd_out = to_write;
8430 	return (0);
8431 
8432 error:
8433 	if (dck != NULL)
8434 		spa_keystore_dsl_key_rele(spa, dck, FTAG);
8435 	if (cabd != NULL)
8436 		abd_free(cabd);
8437 	if (eabd != NULL)
8438 		abd_free(eabd);
8439 
8440 	*abd_out = NULL;
8441 	return (ret);
8442 }
8443 
8444 static void
8445 l2arc_blk_fetch_done(zio_t *zio)
8446 {
8447 	l2arc_read_callback_t *cb;
8448 
8449 	cb = zio->io_private;
8450 	if (cb->l2rcb_abd != NULL)
8451 		abd_put(cb->l2rcb_abd);
8452 	kmem_free(cb, sizeof (l2arc_read_callback_t));
8453 }
8454 
8455 /*
8456  * Find and write ARC buffers to the L2ARC device.
8457  *
8458  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
8459  * for reading until they have completed writing.
8460  * The headroom_boost is an in-out parameter used to maintain headroom boost
8461  * state between calls to this function.
8462  *
8463  * Returns the number of bytes actually written (which may be smaller than
8464  * the delta by which the device hand has changed due to alignment and the
8465  * writing of log blocks).
8466  */
8467 static uint64_t
8468 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
8469 {
8470 	arc_buf_hdr_t		*hdr, *hdr_prev, *head;
8471 	uint64_t		write_asize, write_psize, write_lsize, headroom;
8472 	boolean_t		full;
8473 	l2arc_write_callback_t	*cb = NULL;
8474 	zio_t			*pio, *wzio;
8475 	uint64_t		guid = spa_load_guid(spa);
8476 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
8477 
8478 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
8479 
8480 	pio = NULL;
8481 	write_lsize = write_asize = write_psize = 0;
8482 	full = B_FALSE;
8483 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
8484 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
8485 
8486 	/*
8487 	 * Copy buffers for L2ARC writing.
8488 	 */
8489 	for (int try = 0; try < L2ARC_FEED_TYPES; try++) {
8490 		/*
8491 		 * If try == 1 or 3, we cache MRU metadata and data
8492 		 * respectively.
8493 		 */
8494 		if (l2arc_mfuonly) {
8495 			if (try == 1 || try == 3)
8496 				continue;
8497 		}
8498 
8499 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
8500 		uint64_t passed_sz = 0;
8501 
8502 		VERIFY3P(mls, !=, NULL);
8503 
8504 		/*
8505 		 * L2ARC fast warmup.
8506 		 *
8507 		 * Until the ARC is warm and starts to evict, read from the
8508 		 * head of the ARC lists rather than the tail.
8509 		 */
8510 		if (arc_warm == B_FALSE)
8511 			hdr = multilist_sublist_head(mls);
8512 		else
8513 			hdr = multilist_sublist_tail(mls);
8514 
8515 		headroom = target_sz * l2arc_headroom;
8516 		if (zfs_compressed_arc_enabled)
8517 			headroom = (headroom * l2arc_headroom_boost) / 100;
8518 
8519 		for (; hdr; hdr = hdr_prev) {
8520 			kmutex_t *hash_lock;
8521 			abd_t *to_write = NULL;
8522 
8523 			if (arc_warm == B_FALSE)
8524 				hdr_prev = multilist_sublist_next(mls, hdr);
8525 			else
8526 				hdr_prev = multilist_sublist_prev(mls, hdr);
8527 
8528 			hash_lock = HDR_LOCK(hdr);
8529 			if (!mutex_tryenter(hash_lock)) {
8530 				/*
8531 				 * Skip this buffer rather than waiting.
8532 				 */
8533 				continue;
8534 			}
8535 
8536 			passed_sz += HDR_GET_LSIZE(hdr);
8537 			if (l2arc_headroom != 0 && passed_sz > headroom) {
8538 				/*
8539 				 * Searched too far.
8540 				 */
8541 				mutex_exit(hash_lock);
8542 				break;
8543 			}
8544 
8545 			if (!l2arc_write_eligible(guid, hdr)) {
8546 				mutex_exit(hash_lock);
8547 				continue;
8548 			}
8549 
8550 			ASSERT(HDR_HAS_L1HDR(hdr));
8551 
8552 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8553 			ASSERT3U(arc_hdr_size(hdr), >, 0);
8554 			ASSERT(hdr->b_l1hdr.b_pabd != NULL ||
8555 			    HDR_HAS_RABD(hdr));
8556 			uint64_t psize = HDR_GET_PSIZE(hdr);
8557 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
8558 			    psize);
8559 
8560 			if ((write_asize + asize) > target_sz) {
8561 				full = B_TRUE;
8562 				mutex_exit(hash_lock);
8563 				break;
8564 			}
8565 
8566 			/*
8567 			 * We rely on the L1 portion of the header below, so
8568 			 * it's invalid for this header to have been evicted out
8569 			 * of the ghost cache, prior to being written out. The
8570 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8571 			 */
8572 			arc_hdr_set_flags(hdr, ARC_FLAG_L2_WRITING);
8573 
8574 			/*
8575 			 * If this header has b_rabd, we can use this since it
8576 			 * must always match the data exactly as it exists on
8577 			 * disk. Otherwise, the L2ARC can normally use the
8578 			 * hdr's data, but if we're sharing data between the
8579 			 * hdr and one of its bufs, L2ARC needs its own copy of
8580 			 * the data so that the ZIO below can't race with the
8581 			 * buf consumer. To ensure that this copy will be
8582 			 * available for the lifetime of the ZIO and be cleaned
8583 			 * up afterwards, we add it to the l2arc_free_on_write
8584 			 * queue. If we need to apply any transforms to the
8585 			 * data (compression, encryption) we will also need the
8586 			 * extra buffer.
8587 			 */
8588 			if (HDR_HAS_RABD(hdr) && psize == asize) {
8589 				to_write = hdr->b_crypt_hdr.b_rabd;
8590 			} else if ((HDR_COMPRESSION_ENABLED(hdr) ||
8591 			    HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF) &&
8592 			    !HDR_ENCRYPTED(hdr) && !HDR_SHARED_DATA(hdr) &&
8593 			    psize == asize) {
8594 				to_write = hdr->b_l1hdr.b_pabd;
8595 			} else {
8596 				int ret;
8597 				arc_buf_contents_t type = arc_buf_type(hdr);
8598 
8599 				ret = l2arc_apply_transforms(spa, hdr, asize,
8600 				    &to_write);
8601 				if (ret != 0) {
8602 					arc_hdr_clear_flags(hdr,
8603 					    ARC_FLAG_L2_WRITING);
8604 					mutex_exit(hash_lock);
8605 					continue;
8606 				}
8607 
8608 				l2arc_free_abd_on_write(to_write, asize, type);
8609 			}
8610 
8611 			if (pio == NULL) {
8612 				/*
8613 				 * Insert a dummy header on the buflist so
8614 				 * l2arc_write_done() can find where the
8615 				 * write buffers begin without searching.
8616 				 */
8617 				mutex_enter(&dev->l2ad_mtx);
8618 				list_insert_head(&dev->l2ad_buflist, head);
8619 				mutex_exit(&dev->l2ad_mtx);
8620 
8621 				cb = kmem_alloc(
8622 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
8623 				cb->l2wcb_dev = dev;
8624 				cb->l2wcb_head = head;
8625 				/*
8626 				 * Create a list to save allocated abd buffers
8627 				 * for l2arc_log_blk_commit().
8628 				 */
8629 				list_create(&cb->l2wcb_abd_list,
8630 				    sizeof (l2arc_lb_abd_buf_t),
8631 				    offsetof(l2arc_lb_abd_buf_t, node));
8632 				pio = zio_root(spa, l2arc_write_done, cb,
8633 				    ZIO_FLAG_CANFAIL);
8634 			}
8635 
8636 			hdr->b_l2hdr.b_dev = dev;
8637 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
8638 			hdr->b_l2hdr.b_arcs_state =
8639 			    hdr->b_l1hdr.b_state->arcs_state;
8640 			arc_hdr_set_flags(hdr,
8641 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
8642 
8643 			mutex_enter(&dev->l2ad_mtx);
8644 			list_insert_head(&dev->l2ad_buflist, hdr);
8645 			mutex_exit(&dev->l2ad_mtx);
8646 
8647 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
8648 			    arc_hdr_size(hdr), hdr);
8649 
8650 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
8651 			    hdr->b_l2hdr.b_daddr, asize, to_write,
8652 			    ZIO_CHECKSUM_OFF, NULL, hdr,
8653 			    ZIO_PRIORITY_ASYNC_WRITE,
8654 			    ZIO_FLAG_CANFAIL, B_FALSE);
8655 
8656 			write_lsize += HDR_GET_LSIZE(hdr);
8657 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
8658 			    zio_t *, wzio);
8659 
8660 			write_psize += psize;
8661 			write_asize += asize;
8662 			dev->l2ad_hand += asize;
8663 			l2arc_hdr_arcstats_increment(hdr);
8664 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
8665 
8666 			mutex_exit(hash_lock);
8667 
8668 			/*
8669 			 * Append buf info to current log and commit if full.
8670 			 * arcstat_l2_{size,asize} kstats are updated
8671 			 * internally.
8672 			 */
8673 			if (l2arc_log_blk_insert(dev, hdr))
8674 				l2arc_log_blk_commit(dev, pio, cb);
8675 
8676 			(void) zio_nowait(wzio);
8677 		}
8678 
8679 		multilist_sublist_unlock(mls);
8680 
8681 		if (full == B_TRUE)
8682 			break;
8683 	}
8684 
8685 	/* No buffers selected for writing? */
8686 	if (pio == NULL) {
8687 		ASSERT0(write_lsize);
8688 		ASSERT(!HDR_HAS_L1HDR(head));
8689 		kmem_cache_free(hdr_l2only_cache, head);
8690 
8691 		/*
8692 		 * Although we did not write any buffers l2ad_evict may
8693 		 * have advanced.
8694 		 */
8695 		if (dev->l2ad_evict != l2dhdr->dh_evict)
8696 			l2arc_dev_hdr_update(dev);
8697 
8698 		return (0);
8699 	}
8700 
8701 	if (!dev->l2ad_first)
8702 		ASSERT3U(dev->l2ad_hand, <=, dev->l2ad_evict);
8703 
8704 	ASSERT3U(write_asize, <=, target_sz);
8705 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
8706 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
8707 
8708 	dev->l2ad_writing = B_TRUE;
8709 	(void) zio_wait(pio);
8710 	dev->l2ad_writing = B_FALSE;
8711 
8712 	/*
8713 	 * Update the device header after the zio completes as
8714 	 * l2arc_write_done() may have updated the memory holding the log block
8715 	 * pointers in the device header.
8716 	 */
8717 	l2arc_dev_hdr_update(dev);
8718 
8719 	return (write_asize);
8720 }
8721 
8722 static boolean_t
8723 l2arc_hdr_limit_reached(void)
8724 {
8725 	int64_t s = aggsum_upper_bound(&astat_l2_hdr_size);
8726 
8727 	return (arc_reclaim_needed() || (s > arc_meta_limit * 3 / 4) ||
8728 	    (s > (arc_warm ? arc_c : arc_c_max) * l2arc_meta_percent / 100));
8729 }
8730 
8731 /*
8732  * This thread feeds the L2ARC at regular intervals.  This is the beating
8733  * heart of the L2ARC.
8734  */
8735 /* ARGSUSED */
8736 static void
8737 l2arc_feed_thread(void *unused)
8738 {
8739 	callb_cpr_t cpr;
8740 	l2arc_dev_t *dev;
8741 	spa_t *spa;
8742 	uint64_t size, wrote;
8743 	clock_t begin, next = ddi_get_lbolt();
8744 
8745 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
8746 
8747 	mutex_enter(&l2arc_feed_thr_lock);
8748 
8749 	while (l2arc_thread_exit == 0) {
8750 		CALLB_CPR_SAFE_BEGIN(&cpr);
8751 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
8752 		    next);
8753 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
8754 		next = ddi_get_lbolt() + hz;
8755 
8756 		/*
8757 		 * Quick check for L2ARC devices.
8758 		 */
8759 		mutex_enter(&l2arc_dev_mtx);
8760 		if (l2arc_ndev == 0) {
8761 			mutex_exit(&l2arc_dev_mtx);
8762 			continue;
8763 		}
8764 		mutex_exit(&l2arc_dev_mtx);
8765 		begin = ddi_get_lbolt();
8766 
8767 		/*
8768 		 * This selects the next l2arc device to write to, and in
8769 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
8770 		 * will return NULL if there are now no l2arc devices or if
8771 		 * they are all faulted.
8772 		 *
8773 		 * If a device is returned, its spa's config lock is also
8774 		 * held to prevent device removal.  l2arc_dev_get_next()
8775 		 * will grab and release l2arc_dev_mtx.
8776 		 */
8777 		if ((dev = l2arc_dev_get_next()) == NULL)
8778 			continue;
8779 
8780 		spa = dev->l2ad_spa;
8781 		ASSERT3P(spa, !=, NULL);
8782 
8783 		/*
8784 		 * If the pool is read-only then force the feed thread to
8785 		 * sleep a little longer.
8786 		 */
8787 		if (!spa_writeable(spa)) {
8788 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
8789 			spa_config_exit(spa, SCL_L2ARC, dev);
8790 			continue;
8791 		}
8792 
8793 		/*
8794 		 * Avoid contributing to memory pressure.
8795 		 */
8796 		if (l2arc_hdr_limit_reached()) {
8797 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
8798 			spa_config_exit(spa, SCL_L2ARC, dev);
8799 			continue;
8800 		}
8801 
8802 		ARCSTAT_BUMP(arcstat_l2_feeds);
8803 
8804 		size = l2arc_write_size(dev);
8805 
8806 		/*
8807 		 * Evict L2ARC buffers that will be overwritten.
8808 		 */
8809 		l2arc_evict(dev, size, B_FALSE);
8810 
8811 		/*
8812 		 * Write ARC buffers.
8813 		 */
8814 		wrote = l2arc_write_buffers(spa, dev, size);
8815 
8816 		/*
8817 		 * Calculate interval between writes.
8818 		 */
8819 		next = l2arc_write_interval(begin, size, wrote);
8820 		spa_config_exit(spa, SCL_L2ARC, dev);
8821 	}
8822 
8823 	l2arc_thread_exit = 0;
8824 	cv_broadcast(&l2arc_feed_thr_cv);
8825 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
8826 	thread_exit();
8827 }
8828 
8829 boolean_t
8830 l2arc_vdev_present(vdev_t *vd)
8831 {
8832 	return (l2arc_vdev_get(vd) != NULL);
8833 }
8834 
8835 /*
8836  * Returns the l2arc_dev_t associated with a particular vdev_t or NULL if
8837  * the vdev_t isn't an L2ARC device.
8838  */
8839 static l2arc_dev_t *
8840 l2arc_vdev_get(vdev_t *vd)
8841 {
8842 	l2arc_dev_t	*dev;
8843 
8844 	mutex_enter(&l2arc_dev_mtx);
8845 	for (dev = list_head(l2arc_dev_list); dev != NULL;
8846 	    dev = list_next(l2arc_dev_list, dev)) {
8847 		if (dev->l2ad_vdev == vd)
8848 			break;
8849 	}
8850 	mutex_exit(&l2arc_dev_mtx);
8851 
8852 	return (dev);
8853 }
8854 
8855 /*
8856  * Add a vdev for use by the L2ARC.  By this point the spa has already
8857  * validated the vdev and opened it.
8858  */
8859 void
8860 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
8861 {
8862 	l2arc_dev_t		*adddev;
8863 	uint64_t		l2dhdr_asize;
8864 
8865 	ASSERT(!l2arc_vdev_present(vd));
8866 
8867 	/*
8868 	 * Create a new l2arc device entry.
8869 	 */
8870 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
8871 	adddev->l2ad_spa = spa;
8872 	adddev->l2ad_vdev = vd;
8873 	/* leave extra size for an l2arc device header */
8874 	l2dhdr_asize = adddev->l2ad_dev_hdr_asize =
8875 	    MAX(sizeof (*adddev->l2ad_dev_hdr), 1 << vd->vdev_ashift);
8876 	adddev->l2ad_start = VDEV_LABEL_START_SIZE + l2dhdr_asize;
8877 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
8878 	ASSERT3U(adddev->l2ad_start, <, adddev->l2ad_end);
8879 	adddev->l2ad_hand = adddev->l2ad_start;
8880 	adddev->l2ad_evict = adddev->l2ad_start;
8881 	adddev->l2ad_first = B_TRUE;
8882 	adddev->l2ad_writing = B_FALSE;
8883 	adddev->l2ad_dev_hdr = kmem_zalloc(l2dhdr_asize, KM_SLEEP);
8884 
8885 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
8886 	/*
8887 	 * This is a list of all ARC buffers that are still valid on the
8888 	 * device.
8889 	 */
8890 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
8891 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
8892 
8893 	/*
8894 	 * This is a list of pointers to log blocks that are still present
8895 	 * on the device.
8896 	 */
8897 	list_create(&adddev->l2ad_lbptr_list, sizeof (l2arc_lb_ptr_buf_t),
8898 	    offsetof(l2arc_lb_ptr_buf_t, node));
8899 
8900 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
8901 	zfs_refcount_create(&adddev->l2ad_alloc);
8902 	zfs_refcount_create(&adddev->l2ad_lb_asize);
8903 	zfs_refcount_create(&adddev->l2ad_lb_count);
8904 
8905 	/*
8906 	 * Add device to global list
8907 	 */
8908 	mutex_enter(&l2arc_dev_mtx);
8909 	list_insert_head(l2arc_dev_list, adddev);
8910 	atomic_inc_64(&l2arc_ndev);
8911 	mutex_exit(&l2arc_dev_mtx);
8912 
8913 	/*
8914 	 * Decide if vdev is eligible for L2ARC rebuild
8915 	 */
8916 	l2arc_rebuild_vdev(adddev->l2ad_vdev, B_FALSE);
8917 }
8918 
8919 void
8920 l2arc_rebuild_vdev(vdev_t *vd, boolean_t reopen)
8921 {
8922 	l2arc_dev_t		*dev = NULL;
8923 	l2arc_dev_hdr_phys_t	*l2dhdr;
8924 	uint64_t		l2dhdr_asize;
8925 	spa_t			*spa;
8926 
8927 	dev = l2arc_vdev_get(vd);
8928 	ASSERT3P(dev, !=, NULL);
8929 	spa = dev->l2ad_spa;
8930 	l2dhdr = dev->l2ad_dev_hdr;
8931 	l2dhdr_asize = dev->l2ad_dev_hdr_asize;
8932 
8933 	/*
8934 	 * The L2ARC has to hold at least the payload of one log block for
8935 	 * them to be restored (persistent L2ARC). The payload of a log block
8936 	 * depends on the amount of its log entries. We always write log blocks
8937 	 * with 1022 entries. How many of them are committed or restored depends
8938 	 * on the size of the L2ARC device. Thus the maximum payload of
8939 	 * one log block is 1022 * SPA_MAXBLOCKSIZE = 16GB. If the L2ARC device
8940 	 * is less than that, we reduce the amount of committed and restored
8941 	 * log entries per block so as to enable persistence.
8942 	 */
8943 	if (dev->l2ad_end < l2arc_rebuild_blocks_min_l2size) {
8944 		dev->l2ad_log_entries = 0;
8945 	} else {
8946 		dev->l2ad_log_entries = MIN((dev->l2ad_end -
8947 		    dev->l2ad_start) >> SPA_MAXBLOCKSHIFT,
8948 		    L2ARC_LOG_BLK_MAX_ENTRIES);
8949 	}
8950 
8951 	/*
8952 	 * Read the device header, if an error is returned do not rebuild L2ARC.
8953 	 */
8954 	if (l2arc_dev_hdr_read(dev) == 0 && dev->l2ad_log_entries > 0) {
8955 		/*
8956 		 * If we are onlining a cache device (vdev_reopen) that was
8957 		 * still present (l2arc_vdev_present()) and rebuild is enabled,
8958 		 * we should evict all ARC buffers and pointers to log blocks
8959 		 * and reclaim their space before restoring its contents to
8960 		 * L2ARC.
8961 		 */
8962 		if (reopen) {
8963 			if (!l2arc_rebuild_enabled) {
8964 				return;
8965 			} else {
8966 				l2arc_evict(dev, 0, B_TRUE);
8967 				/* start a new log block */
8968 				dev->l2ad_log_ent_idx = 0;
8969 				dev->l2ad_log_blk_payload_asize = 0;
8970 				dev->l2ad_log_blk_payload_start = 0;
8971 			}
8972 		}
8973 		/*
8974 		 * Just mark the device as pending for a rebuild. We won't
8975 		 * be starting a rebuild in line here as it would block pool
8976 		 * import. Instead spa_load_impl will hand that off to an
8977 		 * async task which will call l2arc_spa_rebuild_start.
8978 		 */
8979 		dev->l2ad_rebuild = B_TRUE;
8980 	} else if (spa_writeable(spa)) {
8981 		/*
8982 		 * In this case create a new header. We zero out the memory
8983 		 * holding the header to reset dh_start_lbps.
8984 		 */
8985 		bzero(l2dhdr, l2dhdr_asize);
8986 		l2arc_dev_hdr_update(dev);
8987 	}
8988 }
8989 
8990 /*
8991  * Remove a vdev from the L2ARC.
8992  */
8993 void
8994 l2arc_remove_vdev(vdev_t *vd)
8995 {
8996 	l2arc_dev_t *remdev = NULL;
8997 
8998 	/*
8999 	 * Find the device by vdev
9000 	 */
9001 	remdev = l2arc_vdev_get(vd);
9002 	ASSERT3P(remdev, !=, NULL);
9003 
9004 	/*
9005 	 * Cancel any ongoing or scheduled rebuild.
9006 	 */
9007 	mutex_enter(&l2arc_rebuild_thr_lock);
9008 	if (remdev->l2ad_rebuild_began == B_TRUE) {
9009 		remdev->l2ad_rebuild_cancel = B_TRUE;
9010 		while (remdev->l2ad_rebuild == B_TRUE)
9011 			cv_wait(&l2arc_rebuild_thr_cv, &l2arc_rebuild_thr_lock);
9012 	}
9013 	mutex_exit(&l2arc_rebuild_thr_lock);
9014 
9015 	/*
9016 	 * Remove device from global list
9017 	 */
9018 	mutex_enter(&l2arc_dev_mtx);
9019 	list_remove(l2arc_dev_list, remdev);
9020 	l2arc_dev_last = NULL;		/* may have been invalidated */
9021 	atomic_dec_64(&l2arc_ndev);
9022 	mutex_exit(&l2arc_dev_mtx);
9023 
9024 	/*
9025 	 * Clear all buflists and ARC references.  L2ARC device flush.
9026 	 */
9027 	l2arc_evict(remdev, 0, B_TRUE);
9028 	list_destroy(&remdev->l2ad_buflist);
9029 	ASSERT(list_is_empty(&remdev->l2ad_lbptr_list));
9030 	list_destroy(&remdev->l2ad_lbptr_list);
9031 	mutex_destroy(&remdev->l2ad_mtx);
9032 	zfs_refcount_destroy(&remdev->l2ad_alloc);
9033 	zfs_refcount_destroy(&remdev->l2ad_lb_asize);
9034 	zfs_refcount_destroy(&remdev->l2ad_lb_count);
9035 	kmem_free(remdev->l2ad_dev_hdr, remdev->l2ad_dev_hdr_asize);
9036 	kmem_free(remdev, sizeof (l2arc_dev_t));
9037 }
9038 
9039 void
9040 l2arc_init(void)
9041 {
9042 	l2arc_thread_exit = 0;
9043 	l2arc_ndev = 0;
9044 	l2arc_writes_sent = 0;
9045 	l2arc_writes_done = 0;
9046 
9047 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9048 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
9049 	mutex_init(&l2arc_rebuild_thr_lock, NULL, MUTEX_DEFAULT, NULL);
9050 	cv_init(&l2arc_rebuild_thr_cv, NULL, CV_DEFAULT, NULL);
9051 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
9052 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
9053 
9054 	l2arc_dev_list = &L2ARC_dev_list;
9055 	l2arc_free_on_write = &L2ARC_free_on_write;
9056 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
9057 	    offsetof(l2arc_dev_t, l2ad_node));
9058 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
9059 	    offsetof(l2arc_data_free_t, l2df_list_node));
9060 }
9061 
9062 void
9063 l2arc_fini(void)
9064 {
9065 	/*
9066 	 * This is called from dmu_fini(), which is called from spa_fini();
9067 	 * Because of this, we can assume that all l2arc devices have
9068 	 * already been removed when the pools themselves were removed.
9069 	 */
9070 
9071 	l2arc_do_free_on_write();
9072 
9073 	mutex_destroy(&l2arc_feed_thr_lock);
9074 	cv_destroy(&l2arc_feed_thr_cv);
9075 	mutex_destroy(&l2arc_rebuild_thr_lock);
9076 	cv_destroy(&l2arc_rebuild_thr_cv);
9077 	mutex_destroy(&l2arc_dev_mtx);
9078 	mutex_destroy(&l2arc_free_on_write_mtx);
9079 
9080 	list_destroy(l2arc_dev_list);
9081 	list_destroy(l2arc_free_on_write);
9082 }
9083 
9084 void
9085 l2arc_start(void)
9086 {
9087 	if (!(spa_mode_global & FWRITE))
9088 		return;
9089 
9090 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
9091 	    TS_RUN, minclsyspri);
9092 }
9093 
9094 void
9095 l2arc_stop(void)
9096 {
9097 	if (!(spa_mode_global & FWRITE))
9098 		return;
9099 
9100 	mutex_enter(&l2arc_feed_thr_lock);
9101 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
9102 	l2arc_thread_exit = 1;
9103 	while (l2arc_thread_exit != 0)
9104 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
9105 	mutex_exit(&l2arc_feed_thr_lock);
9106 }
9107 
9108 /*
9109  * Punches out rebuild threads for the L2ARC devices in a spa. This should
9110  * be called after pool import from the spa async thread, since starting
9111  * these threads directly from spa_import() will make them part of the
9112  * "zpool import" context and delay process exit (and thus pool import).
9113  */
9114 void
9115 l2arc_spa_rebuild_start(spa_t *spa)
9116 {
9117 	ASSERT(MUTEX_HELD(&spa_namespace_lock));
9118 
9119 	/*
9120 	 * Locate the spa's l2arc devices and kick off rebuild threads.
9121 	 */
9122 	for (int i = 0; i < spa->spa_l2cache.sav_count; i++) {
9123 		l2arc_dev_t *dev =
9124 		    l2arc_vdev_get(spa->spa_l2cache.sav_vdevs[i]);
9125 		if (dev == NULL) {
9126 			/* Don't attempt a rebuild if the vdev is UNAVAIL */
9127 			continue;
9128 		}
9129 		mutex_enter(&l2arc_rebuild_thr_lock);
9130 		if (dev->l2ad_rebuild && !dev->l2ad_rebuild_cancel) {
9131 			dev->l2ad_rebuild_began = B_TRUE;
9132 			(void) thread_create(NULL, 0,
9133 			    (void (*)(void *))l2arc_dev_rebuild_start,
9134 			    dev, 0, &p0, TS_RUN, minclsyspri);
9135 		}
9136 		mutex_exit(&l2arc_rebuild_thr_lock);
9137 	}
9138 }
9139 
9140 /*
9141  * Main entry point for L2ARC rebuilding.
9142  */
9143 static void
9144 l2arc_dev_rebuild_start(l2arc_dev_t *dev)
9145 {
9146 	VERIFY(!dev->l2ad_rebuild_cancel);
9147 	VERIFY(dev->l2ad_rebuild);
9148 	(void) l2arc_rebuild(dev);
9149 	mutex_enter(&l2arc_rebuild_thr_lock);
9150 	dev->l2ad_rebuild_began = B_FALSE;
9151 	dev->l2ad_rebuild = B_FALSE;
9152 	mutex_exit(&l2arc_rebuild_thr_lock);
9153 
9154 	thread_exit();
9155 }
9156 
9157 /*
9158  * This function implements the actual L2ARC metadata rebuild. It:
9159  * starts reading the log block chain and restores each block's contents
9160  * to memory (reconstructing arc_buf_hdr_t's).
9161  *
9162  * Operation stops under any of the following conditions:
9163  *
9164  * 1) We reach the end of the log block chain.
9165  * 2) We encounter *any* error condition (cksum errors, io errors)
9166  */
9167 static int
9168 l2arc_rebuild(l2arc_dev_t *dev)
9169 {
9170 	vdev_t			*vd = dev->l2ad_vdev;
9171 	spa_t			*spa = vd->vdev_spa;
9172 	int			err = 0;
9173 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9174 	l2arc_log_blk_phys_t	*this_lb, *next_lb;
9175 	zio_t			*this_io = NULL, *next_io = NULL;
9176 	l2arc_log_blkptr_t	lbps[2];
9177 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
9178 	boolean_t		lock_held;
9179 
9180 	this_lb = kmem_zalloc(sizeof (*this_lb), KM_SLEEP);
9181 	next_lb = kmem_zalloc(sizeof (*next_lb), KM_SLEEP);
9182 
9183 	/*
9184 	 * We prevent device removal while issuing reads to the device,
9185 	 * then during the rebuilding phases we drop this lock again so
9186 	 * that a spa_unload or device remove can be initiated - this is
9187 	 * safe, because the spa will signal us to stop before removing
9188 	 * our device and wait for us to stop.
9189 	 */
9190 	spa_config_enter(spa, SCL_L2ARC, vd, RW_READER);
9191 	lock_held = B_TRUE;
9192 
9193 	/*
9194 	 * Retrieve the persistent L2ARC device state.
9195 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9196 	 */
9197 	dev->l2ad_evict = MAX(l2dhdr->dh_evict, dev->l2ad_start);
9198 	dev->l2ad_hand = MAX(l2dhdr->dh_start_lbps[0].lbp_daddr +
9199 	    L2BLK_GET_PSIZE((&l2dhdr->dh_start_lbps[0])->lbp_prop),
9200 	    dev->l2ad_start);
9201 	dev->l2ad_first = !!(l2dhdr->dh_flags & L2ARC_DEV_HDR_EVICT_FIRST);
9202 
9203 	/*
9204 	 * In case the zfs module parameter l2arc_rebuild_enabled is false
9205 	 * we do not start the rebuild process.
9206 	 */
9207 	if (!l2arc_rebuild_enabled)
9208 		goto out;
9209 
9210 	/* Prepare the rebuild process */
9211 	bcopy(l2dhdr->dh_start_lbps, lbps, sizeof (lbps));
9212 
9213 	/* Start the rebuild process */
9214 	for (;;) {
9215 		if (!l2arc_log_blkptr_valid(dev, &lbps[0]))
9216 			break;
9217 
9218 		if ((err = l2arc_log_blk_read(dev, &lbps[0], &lbps[1],
9219 		    this_lb, next_lb, this_io, &next_io)) != 0)
9220 			goto out;
9221 
9222 		/*
9223 		 * Our memory pressure valve. If the system is running low
9224 		 * on memory, rather than swamping memory with new ARC buf
9225 		 * hdrs, we opt not to rebuild the L2ARC. At this point,
9226 		 * however, we have already set up our L2ARC dev to chain in
9227 		 * new metadata log blocks, so the user may choose to offline/
9228 		 * online the L2ARC dev at a later time (or re-import the pool)
9229 		 * to reconstruct it (when there's less memory pressure).
9230 		 */
9231 		if (l2arc_hdr_limit_reached()) {
9232 			ARCSTAT_BUMP(arcstat_l2_rebuild_abort_lowmem);
9233 			cmn_err(CE_NOTE, "System running low on memory, "
9234 			    "aborting L2ARC rebuild.");
9235 			err = SET_ERROR(ENOMEM);
9236 			goto out;
9237 		}
9238 
9239 		spa_config_exit(spa, SCL_L2ARC, vd);
9240 		lock_held = B_FALSE;
9241 
9242 		/*
9243 		 * Now that we know that the next_lb checks out alright, we
9244 		 * can start reconstruction from this log block.
9245 		 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9246 		 */
9247 		uint64_t asize = L2BLK_GET_PSIZE((&lbps[0])->lbp_prop);
9248 		l2arc_log_blk_restore(dev, this_lb, asize);
9249 
9250 		/*
9251 		 * log block restored, include its pointer in the list of
9252 		 * pointers to log blocks present in the L2ARC device.
9253 		 */
9254 		lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
9255 		lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t),
9256 		    KM_SLEEP);
9257 		bcopy(&lbps[0], lb_ptr_buf->lb_ptr,
9258 		    sizeof (l2arc_log_blkptr_t));
9259 		mutex_enter(&dev->l2ad_mtx);
9260 		list_insert_tail(&dev->l2ad_lbptr_list, lb_ptr_buf);
9261 		ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
9262 		ARCSTAT_BUMP(arcstat_l2_log_blk_count);
9263 		zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
9264 		zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
9265 		mutex_exit(&dev->l2ad_mtx);
9266 		vdev_space_update(vd, asize, 0, 0);
9267 
9268 		/* BEGIN CSTYLED */
9269 		/*
9270 		 * Protection against loops of log blocks:
9271 		 *
9272 		 *				       l2ad_hand  l2ad_evict
9273 		 *                                         V          V
9274 		 * l2ad_start |=======================================| l2ad_end
9275 		 *             -----|||----|||---|||----|||
9276 		 *                  (3)    (2)   (1)    (0)
9277 		 *             ---|||---|||----|||---|||
9278 		 *		  (7)   (6)    (5)   (4)
9279 		 *
9280 		 * In this situation the pointer of log block (4) passes
9281 		 * l2arc_log_blkptr_valid() but the log block should not be
9282 		 * restored as it is overwritten by the payload of log block
9283 		 * (0). Only log blocks (0)-(3) should be restored. We check
9284 		 * whether l2ad_evict lies in between the payload starting
9285 		 * offset of the next log block (lbps[1].lbp_payload_start)
9286 		 * and the payload starting offset of the present log block
9287 		 * (lbps[0].lbp_payload_start). If true and this isn't the
9288 		 * first pass, we are looping from the beginning and we should
9289 		 * stop.
9290 		 */
9291 		/* END CSTYLED */
9292 		if (l2arc_range_check_overlap(lbps[1].lbp_payload_start,
9293 		    lbps[0].lbp_payload_start, dev->l2ad_evict) &&
9294 		    !dev->l2ad_first)
9295 			goto out;
9296 
9297 		for (;;) {
9298 			mutex_enter(&l2arc_rebuild_thr_lock);
9299 			if (dev->l2ad_rebuild_cancel) {
9300 				dev->l2ad_rebuild = B_FALSE;
9301 				cv_signal(&l2arc_rebuild_thr_cv);
9302 				mutex_exit(&l2arc_rebuild_thr_lock);
9303 				err = SET_ERROR(ECANCELED);
9304 				goto out;
9305 			}
9306 			mutex_exit(&l2arc_rebuild_thr_lock);
9307 			if (spa_config_tryenter(spa, SCL_L2ARC, vd,
9308 			    RW_READER)) {
9309 				lock_held = B_TRUE;
9310 				break;
9311 			}
9312 			/*
9313 			 * L2ARC config lock held by somebody in writer,
9314 			 * possibly due to them trying to remove us. They'll
9315 			 * likely to want us to shut down, so after a little
9316 			 * delay, we check l2ad_rebuild_cancel and retry
9317 			 * the lock again.
9318 			 */
9319 			delay(1);
9320 		}
9321 
9322 		/*
9323 		 * Continue with the next log block.
9324 		 */
9325 		lbps[0] = lbps[1];
9326 		lbps[1] = this_lb->lb_prev_lbp;
9327 		PTR_SWAP(this_lb, next_lb);
9328 		this_io = next_io;
9329 		next_io = NULL;
9330 	}
9331 
9332 	if (this_io != NULL)
9333 		l2arc_log_blk_fetch_abort(this_io);
9334 out:
9335 	if (next_io != NULL)
9336 		l2arc_log_blk_fetch_abort(next_io);
9337 	kmem_free(this_lb, sizeof (*this_lb));
9338 	kmem_free(next_lb, sizeof (*next_lb));
9339 
9340 	if (!l2arc_rebuild_enabled) {
9341 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9342 		    "disabled");
9343 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) > 0) {
9344 		ARCSTAT_BUMP(arcstat_l2_rebuild_success);
9345 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9346 		    "successful, restored %llu blocks",
9347 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9348 	} else if (err == 0 && zfs_refcount_count(&dev->l2ad_lb_count) == 0) {
9349 		/*
9350 		 * No error but also nothing restored, meaning the lbps array
9351 		 * in the device header points to invalid/non-present log
9352 		 * blocks. Reset the header.
9353 		 */
9354 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9355 		    "no valid log blocks");
9356 		bzero(l2dhdr, dev->l2ad_dev_hdr_asize);
9357 		l2arc_dev_hdr_update(dev);
9358 	} else if (err == ECANCELED) {
9359 		/*
9360 		 * In case the rebuild was canceled do not log to spa history
9361 		 * log as the pool may be in the process of being removed.
9362 		 */
9363 		zfs_dbgmsg("L2ARC rebuild aborted, restored %llu blocks",
9364 		    zfs_refcount_count(&dev->l2ad_lb_count));
9365 	} else if (err != 0) {
9366 		spa_history_log_internal(spa, "L2ARC rebuild", NULL,
9367 		    "aborted, restored %llu blocks",
9368 		    (u_longlong_t)zfs_refcount_count(&dev->l2ad_lb_count));
9369 	}
9370 
9371 	if (lock_held)
9372 		spa_config_exit(spa, SCL_L2ARC, vd);
9373 
9374 	return (err);
9375 }
9376 
9377 /*
9378  * Attempts to read the device header on the provided L2ARC device and writes
9379  * it to `hdr'. On success, this function returns 0, otherwise the appropriate
9380  * error code is returned.
9381  */
9382 static int
9383 l2arc_dev_hdr_read(l2arc_dev_t *dev)
9384 {
9385 	int			err;
9386 	uint64_t		guid;
9387 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9388 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9389 	abd_t			*abd;
9390 
9391 	guid = spa_guid(dev->l2ad_vdev->vdev_spa);
9392 
9393 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
9394 
9395 	err = zio_wait(zio_read_phys(NULL, dev->l2ad_vdev,
9396 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd,
9397 	    ZIO_CHECKSUM_LABEL, NULL, NULL, ZIO_PRIORITY_SYNC_READ,
9398 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
9399 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
9400 	    ZIO_FLAG_SPECULATIVE, B_FALSE));
9401 
9402 	abd_put(abd);
9403 
9404 	if (err != 0) {
9405 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_dh_errors);
9406 		zfs_dbgmsg("L2ARC IO error (%d) while reading device header, "
9407 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
9408 		return (err);
9409 	}
9410 
9411 	if (l2dhdr->dh_magic == BSWAP_64(L2ARC_DEV_HDR_MAGIC))
9412 		byteswap_uint64_array(l2dhdr, sizeof (*l2dhdr));
9413 
9414 	if (l2dhdr->dh_magic != L2ARC_DEV_HDR_MAGIC ||
9415 	    l2dhdr->dh_spa_guid != guid ||
9416 	    l2dhdr->dh_vdev_guid != dev->l2ad_vdev->vdev_guid ||
9417 	    l2dhdr->dh_version != L2ARC_PERSISTENT_VERSION ||
9418 	    l2dhdr->dh_log_entries != dev->l2ad_log_entries ||
9419 	    l2dhdr->dh_end != dev->l2ad_end ||
9420 	    !l2arc_range_check_overlap(dev->l2ad_start, dev->l2ad_end,
9421 	    l2dhdr->dh_evict)) {
9422 		/*
9423 		 * Attempt to rebuild a device containing no actual dev hdr
9424 		 * or containing a header from some other pool or from another
9425 		 * version of persistent L2ARC.
9426 		 */
9427 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_unsupported);
9428 		return (SET_ERROR(ENOTSUP));
9429 	}
9430 
9431 	return (0);
9432 }
9433 
9434 /*
9435  * Reads L2ARC log blocks from storage and validates their contents.
9436  *
9437  * This function implements a simple fetcher to make sure that while
9438  * we're processing one buffer the L2ARC is already fetching the next
9439  * one in the chain.
9440  *
9441  * The arguments this_lp and next_lp point to the current and next log block
9442  * address in the block chain. Similarly, this_lb and next_lb hold the
9443  * l2arc_log_blk_phys_t's of the current and next L2ARC blk.
9444  *
9445  * The `this_io' and `next_io' arguments are used for block fetching.
9446  * When issuing the first blk IO during rebuild, you should pass NULL for
9447  * `this_io'. This function will then issue a sync IO to read the block and
9448  * also issue an async IO to fetch the next block in the block chain. The
9449  * fetched IO is returned in `next_io'. On subsequent calls to this
9450  * function, pass the value returned in `next_io' from the previous call
9451  * as `this_io' and a fresh `next_io' pointer to hold the next fetch IO.
9452  * Prior to the call, you should initialize your `next_io' pointer to be
9453  * NULL. If no fetch IO was issued, the pointer is left set at NULL.
9454  *
9455  * On success, this function returns 0, otherwise it returns an appropriate
9456  * error code. On error the fetching IO is aborted and cleared before
9457  * returning from this function. Therefore, if we return `success', the
9458  * caller can assume that we have taken care of cleanup of fetch IOs.
9459  */
9460 static int
9461 l2arc_log_blk_read(l2arc_dev_t *dev,
9462     const l2arc_log_blkptr_t *this_lbp, const l2arc_log_blkptr_t *next_lbp,
9463     l2arc_log_blk_phys_t *this_lb, l2arc_log_blk_phys_t *next_lb,
9464     zio_t *this_io, zio_t **next_io)
9465 {
9466 	int		err = 0;
9467 	zio_cksum_t	cksum;
9468 	abd_t		*abd = NULL;
9469 	uint64_t	asize;
9470 
9471 	ASSERT(this_lbp != NULL && next_lbp != NULL);
9472 	ASSERT(this_lb != NULL && next_lb != NULL);
9473 	ASSERT(next_io != NULL && *next_io == NULL);
9474 	ASSERT(l2arc_log_blkptr_valid(dev, this_lbp));
9475 
9476 	/*
9477 	 * Check to see if we have issued the IO for this log block in a
9478 	 * previous run. If not, this is the first call, so issue it now.
9479 	 */
9480 	if (this_io == NULL) {
9481 		this_io = l2arc_log_blk_fetch(dev->l2ad_vdev, this_lbp,
9482 		    this_lb);
9483 	}
9484 
9485 	/*
9486 	 * Peek to see if we can start issuing the next IO immediately.
9487 	 */
9488 	if (l2arc_log_blkptr_valid(dev, next_lbp)) {
9489 		/*
9490 		 * Start issuing IO for the next log block early - this
9491 		 * should help keep the L2ARC device busy while we
9492 		 * decompress and restore this log block.
9493 		 */
9494 		*next_io = l2arc_log_blk_fetch(dev->l2ad_vdev, next_lbp,
9495 		    next_lb);
9496 	}
9497 
9498 	/* Wait for the IO to read this log block to complete */
9499 	if ((err = zio_wait(this_io)) != 0) {
9500 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_io_errors);
9501 		zfs_dbgmsg("L2ARC IO error (%d) while reading log block, "
9502 		    "offset: %llu, vdev guid: %llu", err, this_lbp->lbp_daddr,
9503 		    dev->l2ad_vdev->vdev_guid);
9504 		goto cleanup;
9505 	}
9506 
9507 	/*
9508 	 * Make sure the buffer checks out.
9509 	 * L2BLK_GET_PSIZE returns aligned size for log blocks.
9510 	 */
9511 	asize = L2BLK_GET_PSIZE((this_lbp)->lbp_prop);
9512 	fletcher_4_native(this_lb, asize, NULL, &cksum);
9513 	if (!ZIO_CHECKSUM_EQUAL(cksum, this_lbp->lbp_cksum)) {
9514 		ARCSTAT_BUMP(arcstat_l2_rebuild_abort_cksum_lb_errors);
9515 		zfs_dbgmsg("L2ARC log block cksum failed, offset: %llu, "
9516 		    "vdev guid: %llu, l2ad_hand: %llu, l2ad_evict: %llu",
9517 		    this_lbp->lbp_daddr, dev->l2ad_vdev->vdev_guid,
9518 		    dev->l2ad_hand, dev->l2ad_evict);
9519 		err = SET_ERROR(ECKSUM);
9520 		goto cleanup;
9521 	}
9522 
9523 	/* Now we can take our time decoding this buffer */
9524 	switch (L2BLK_GET_COMPRESS((this_lbp)->lbp_prop)) {
9525 	case ZIO_COMPRESS_OFF:
9526 		break;
9527 	case ZIO_COMPRESS_LZ4:
9528 		abd = abd_alloc_for_io(asize, B_TRUE);
9529 		abd_copy_from_buf_off(abd, this_lb, 0, asize);
9530 		if ((err = zio_decompress_data(
9531 		    L2BLK_GET_COMPRESS((this_lbp)->lbp_prop),
9532 		    abd, this_lb, asize, sizeof (*this_lb))) != 0) {
9533 			err = SET_ERROR(EINVAL);
9534 			goto cleanup;
9535 		}
9536 		break;
9537 	default:
9538 		err = SET_ERROR(EINVAL);
9539 		goto cleanup;
9540 	}
9541 	if (this_lb->lb_magic == BSWAP_64(L2ARC_LOG_BLK_MAGIC))
9542 		byteswap_uint64_array(this_lb, sizeof (*this_lb));
9543 	if (this_lb->lb_magic != L2ARC_LOG_BLK_MAGIC) {
9544 		err = SET_ERROR(EINVAL);
9545 		goto cleanup;
9546 	}
9547 cleanup:
9548 	/* Abort an in-flight fetch I/O in case of error */
9549 	if (err != 0 && *next_io != NULL) {
9550 		l2arc_log_blk_fetch_abort(*next_io);
9551 		*next_io = NULL;
9552 	}
9553 	if (abd != NULL)
9554 		abd_free(abd);
9555 	return (err);
9556 }
9557 
9558 /*
9559  * Restores the payload of a log block to ARC. This creates empty ARC hdr
9560  * entries which only contain an l2arc hdr, essentially restoring the
9561  * buffers to their L2ARC evicted state. This function also updates space
9562  * usage on the L2ARC vdev to make sure it tracks restored buffers.
9563  */
9564 static void
9565 l2arc_log_blk_restore(l2arc_dev_t *dev, const l2arc_log_blk_phys_t *lb,
9566     uint64_t lb_asize)
9567 {
9568 	uint64_t	size = 0, asize = 0;
9569 	uint64_t	log_entries = dev->l2ad_log_entries;
9570 
9571 	/*
9572 	 * Usually arc_adapt() is called only for data, not headers, but
9573 	 * since we may allocate significant amount of memory here, let ARC
9574 	 * grow its arc_c.
9575 	 */
9576 	arc_adapt(log_entries * HDR_L2ONLY_SIZE, arc_l2c_only);
9577 
9578 	for (int i = log_entries - 1; i >= 0; i--) {
9579 		/*
9580 		 * Restore goes in the reverse temporal direction to preserve
9581 		 * correct temporal ordering of buffers in the l2ad_buflist.
9582 		 * l2arc_hdr_restore also does a list_insert_tail instead of
9583 		 * list_insert_head on the l2ad_buflist:
9584 		 *
9585 		 *		LIST	l2ad_buflist		LIST
9586 		 *		HEAD  <------ (time) ------	TAIL
9587 		 * direction	+-----+-----+-----+-----+-----+    direction
9588 		 * of l2arc <== | buf | buf | buf | buf | buf | ===> of rebuild
9589 		 * fill		+-----+-----+-----+-----+-----+
9590 		 *		^				^
9591 		 *		|				|
9592 		 *		|				|
9593 		 *	l2arc_feed_thread		l2arc_rebuild
9594 		 *	will place new bufs here	restores bufs here
9595 		 *
9596 		 * During l2arc_rebuild() the device is not used by
9597 		 * l2arc_feed_thread() as dev->l2ad_rebuild is set to true.
9598 		 */
9599 		size += L2BLK_GET_LSIZE((&lb->lb_entries[i])->le_prop);
9600 		asize += vdev_psize_to_asize(dev->l2ad_vdev,
9601 		    L2BLK_GET_PSIZE((&lb->lb_entries[i])->le_prop));
9602 		l2arc_hdr_restore(&lb->lb_entries[i], dev);
9603 	}
9604 
9605 	/*
9606 	 * Record rebuild stats:
9607 	 *	size		Logical size of restored buffers in the L2ARC
9608 	 *	asize		Aligned size of restored buffers in the L2ARC
9609 	 */
9610 	ARCSTAT_INCR(arcstat_l2_rebuild_size, size);
9611 	ARCSTAT_INCR(arcstat_l2_rebuild_asize, asize);
9612 	ARCSTAT_INCR(arcstat_l2_rebuild_bufs, log_entries);
9613 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, lb_asize);
9614 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio, asize / lb_asize);
9615 	ARCSTAT_BUMP(arcstat_l2_rebuild_log_blks);
9616 }
9617 
9618 /*
9619  * Restores a single ARC buf hdr from a log entry. The ARC buffer is put
9620  * into a state indicating that it has been evicted to L2ARC.
9621  */
9622 static void
9623 l2arc_hdr_restore(const l2arc_log_ent_phys_t *le, l2arc_dev_t *dev)
9624 {
9625 	arc_buf_hdr_t		*hdr, *exists;
9626 	kmutex_t		*hash_lock;
9627 	arc_buf_contents_t	type = L2BLK_GET_TYPE((le)->le_prop);
9628 	uint64_t		asize;
9629 
9630 	/*
9631 	 * Do all the allocation before grabbing any locks, this lets us
9632 	 * sleep if memory is full and we don't have to deal with failed
9633 	 * allocations.
9634 	 */
9635 	hdr = arc_buf_alloc_l2only(L2BLK_GET_LSIZE((le)->le_prop), type,
9636 	    dev, le->le_dva, le->le_daddr,
9637 	    L2BLK_GET_PSIZE((le)->le_prop), le->le_birth,
9638 	    L2BLK_GET_COMPRESS((le)->le_prop),
9639 	    L2BLK_GET_PROTECTED((le)->le_prop),
9640 	    L2BLK_GET_PREFETCH((le)->le_prop),
9641 	    L2BLK_GET_STATE((le)->le_prop));
9642 	asize = vdev_psize_to_asize(dev->l2ad_vdev,
9643 	    L2BLK_GET_PSIZE((le)->le_prop));
9644 
9645 	/*
9646 	 * vdev_space_update() has to be called before arc_hdr_destroy() to
9647 	 * avoid underflow since the latter also calls vdev_space_update().
9648 	 */
9649 	l2arc_hdr_arcstats_increment(hdr);
9650 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9651 
9652 	mutex_enter(&dev->l2ad_mtx);
9653 	list_insert_tail(&dev->l2ad_buflist, hdr);
9654 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
9655 	mutex_exit(&dev->l2ad_mtx);
9656 
9657 	exists = buf_hash_insert(hdr, &hash_lock);
9658 	if (exists) {
9659 		/* Buffer was already cached, no need to restore it. */
9660 		arc_hdr_destroy(hdr);
9661 		/*
9662 		 * If the buffer is already cached, check whether it has
9663 		 * L2ARC metadata. If not, enter them and update the flag.
9664 		 * This is important is case of onlining a cache device, since
9665 		 * we previously evicted all L2ARC metadata from ARC.
9666 		 */
9667 		if (!HDR_HAS_L2HDR(exists)) {
9668 			arc_hdr_set_flags(exists, ARC_FLAG_HAS_L2HDR);
9669 			exists->b_l2hdr.b_dev = dev;
9670 			exists->b_l2hdr.b_daddr = le->le_daddr;
9671 			exists->b_l2hdr.b_arcs_state =
9672 			    L2BLK_GET_STATE((le)->le_prop);
9673 			mutex_enter(&dev->l2ad_mtx);
9674 			list_insert_tail(&dev->l2ad_buflist, exists);
9675 			(void) zfs_refcount_add_many(&dev->l2ad_alloc,
9676 			    arc_hdr_size(exists), exists);
9677 			mutex_exit(&dev->l2ad_mtx);
9678 			l2arc_hdr_arcstats_increment(exists);
9679 			vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9680 		}
9681 		ARCSTAT_BUMP(arcstat_l2_rebuild_bufs_precached);
9682 	}
9683 
9684 	mutex_exit(hash_lock);
9685 }
9686 
9687 /*
9688  * Starts an asynchronous read IO to read a log block. This is used in log
9689  * block reconstruction to start reading the next block before we are done
9690  * decoding and reconstructing the current block, to keep the l2arc device
9691  * nice and hot with read IO to process.
9692  * The returned zio will contain newly allocated memory buffers for the IO
9693  * data which should then be freed by the caller once the zio is no longer
9694  * needed (i.e. due to it having completed). If you wish to abort this
9695  * zio, you should do so using l2arc_log_blk_fetch_abort, which takes
9696  * care of disposing of the allocated buffers correctly.
9697  */
9698 static zio_t *
9699 l2arc_log_blk_fetch(vdev_t *vd, const l2arc_log_blkptr_t *lbp,
9700     l2arc_log_blk_phys_t *lb)
9701 {
9702 	uint32_t		asize;
9703 	zio_t			*pio;
9704 	l2arc_read_callback_t	*cb;
9705 
9706 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
9707 	asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
9708 	ASSERT(asize <= sizeof (l2arc_log_blk_phys_t));
9709 
9710 	cb = kmem_zalloc(sizeof (l2arc_read_callback_t), KM_SLEEP);
9711 	cb->l2rcb_abd = abd_get_from_buf(lb, asize);
9712 	pio = zio_root(vd->vdev_spa, l2arc_blk_fetch_done, cb,
9713 	    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE |
9714 	    ZIO_FLAG_DONT_RETRY);
9715 	(void) zio_nowait(zio_read_phys(pio, vd, lbp->lbp_daddr, asize,
9716 	    cb->l2rcb_abd, ZIO_CHECKSUM_OFF, NULL, NULL,
9717 	    ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
9718 	    ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY, B_FALSE));
9719 
9720 	return (pio);
9721 }
9722 
9723 /*
9724  * Aborts a zio returned from l2arc_log_blk_fetch and frees the data
9725  * buffers allocated for it.
9726  */
9727 static void
9728 l2arc_log_blk_fetch_abort(zio_t *zio)
9729 {
9730 	(void) zio_wait(zio);
9731 }
9732 
9733 /*
9734  * Creates a zio to update the device header on an l2arc device.
9735  */
9736 static void
9737 l2arc_dev_hdr_update(l2arc_dev_t *dev)
9738 {
9739 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9740 	const uint64_t		l2dhdr_asize = dev->l2ad_dev_hdr_asize;
9741 	abd_t			*abd;
9742 	int			err;
9743 
9744 	VERIFY(spa_config_held(dev->l2ad_spa, SCL_STATE_ALL, RW_READER));
9745 
9746 	l2dhdr->dh_magic = L2ARC_DEV_HDR_MAGIC;
9747 	l2dhdr->dh_version = L2ARC_PERSISTENT_VERSION;
9748 	l2dhdr->dh_spa_guid = spa_guid(dev->l2ad_vdev->vdev_spa);
9749 	l2dhdr->dh_vdev_guid = dev->l2ad_vdev->vdev_guid;
9750 	l2dhdr->dh_log_entries = dev->l2ad_log_entries;
9751 	l2dhdr->dh_evict = dev->l2ad_evict;
9752 	l2dhdr->dh_start = dev->l2ad_start;
9753 	l2dhdr->dh_end = dev->l2ad_end;
9754 	l2dhdr->dh_lb_asize = zfs_refcount_count(&dev->l2ad_lb_asize);
9755 	l2dhdr->dh_lb_count = zfs_refcount_count(&dev->l2ad_lb_count);
9756 	l2dhdr->dh_flags = 0;
9757 	if (dev->l2ad_first)
9758 		l2dhdr->dh_flags |= L2ARC_DEV_HDR_EVICT_FIRST;
9759 
9760 	abd = abd_get_from_buf(l2dhdr, l2dhdr_asize);
9761 
9762 	err = zio_wait(zio_write_phys(NULL, dev->l2ad_vdev,
9763 	    VDEV_LABEL_START_SIZE, l2dhdr_asize, abd, ZIO_CHECKSUM_LABEL, NULL,
9764 	    NULL, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE));
9765 
9766 	abd_put(abd);
9767 
9768 	if (err != 0) {
9769 		zfs_dbgmsg("L2ARC IO error (%d) while writing device header, "
9770 		    "vdev guid: %llu", err, dev->l2ad_vdev->vdev_guid);
9771 	}
9772 }
9773 
9774 /*
9775  * Commits a log block to the L2ARC device. This routine is invoked from
9776  * l2arc_write_buffers when the log block fills up.
9777  * This function allocates some memory to temporarily hold the serialized
9778  * buffer to be written. This is then released in l2arc_write_done.
9779  */
9780 static void
9781 l2arc_log_blk_commit(l2arc_dev_t *dev, zio_t *pio, l2arc_write_callback_t *cb)
9782 {
9783 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
9784 	l2arc_dev_hdr_phys_t	*l2dhdr = dev->l2ad_dev_hdr;
9785 	uint64_t		psize, asize;
9786 	zio_t			*wzio;
9787 	l2arc_lb_abd_buf_t	*abd_buf;
9788 	uint8_t			*tmpbuf;
9789 	l2arc_lb_ptr_buf_t	*lb_ptr_buf;
9790 
9791 	VERIFY3S(dev->l2ad_log_ent_idx, ==, dev->l2ad_log_entries);
9792 
9793 	tmpbuf = zio_buf_alloc(sizeof (*lb));
9794 	abd_buf = zio_buf_alloc(sizeof (*abd_buf));
9795 	abd_buf->abd = abd_get_from_buf(lb, sizeof (*lb));
9796 	lb_ptr_buf = kmem_zalloc(sizeof (l2arc_lb_ptr_buf_t), KM_SLEEP);
9797 	lb_ptr_buf->lb_ptr = kmem_zalloc(sizeof (l2arc_log_blkptr_t), KM_SLEEP);
9798 
9799 	/* link the buffer into the block chain */
9800 	lb->lb_prev_lbp = l2dhdr->dh_start_lbps[1];
9801 	lb->lb_magic = L2ARC_LOG_BLK_MAGIC;
9802 
9803 	/*
9804 	 * l2arc_log_blk_commit() may be called multiple times during a single
9805 	 * l2arc_write_buffers() call. Save the allocated abd buffers in a list
9806 	 * so we can free them in l2arc_write_done() later on.
9807 	 */
9808 	list_insert_tail(&cb->l2wcb_abd_list, abd_buf);
9809 
9810 	/* try to compress the buffer */
9811 	psize = zio_compress_data(ZIO_COMPRESS_LZ4,
9812 	    abd_buf->abd, tmpbuf, sizeof (*lb));
9813 
9814 	/* a log block is never entirely zero */
9815 	ASSERT(psize != 0);
9816 	asize = vdev_psize_to_asize(dev->l2ad_vdev, psize);
9817 	ASSERT(asize <= sizeof (*lb));
9818 
9819 	/*
9820 	 * Update the start log block pointer in the device header to point
9821 	 * to the log block we're about to write.
9822 	 */
9823 	l2dhdr->dh_start_lbps[1] = l2dhdr->dh_start_lbps[0];
9824 	l2dhdr->dh_start_lbps[0].lbp_daddr = dev->l2ad_hand;
9825 	l2dhdr->dh_start_lbps[0].lbp_payload_asize =
9826 	    dev->l2ad_log_blk_payload_asize;
9827 	l2dhdr->dh_start_lbps[0].lbp_payload_start =
9828 	    dev->l2ad_log_blk_payload_start;
9829 	_NOTE(CONSTCOND)
9830 	L2BLK_SET_LSIZE(
9831 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, sizeof (*lb));
9832 	L2BLK_SET_PSIZE(
9833 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop, asize);
9834 	L2BLK_SET_CHECKSUM(
9835 	    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
9836 	    ZIO_CHECKSUM_FLETCHER_4);
9837 	if (asize < sizeof (*lb)) {
9838 		/* compression succeeded */
9839 		bzero(tmpbuf + psize, asize - psize);
9840 		L2BLK_SET_COMPRESS(
9841 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
9842 		    ZIO_COMPRESS_LZ4);
9843 	} else {
9844 		/* compression failed */
9845 		bcopy(lb, tmpbuf, sizeof (*lb));
9846 		L2BLK_SET_COMPRESS(
9847 		    (&l2dhdr->dh_start_lbps[0])->lbp_prop,
9848 		    ZIO_COMPRESS_OFF);
9849 	}
9850 
9851 	/* checksum what we're about to write */
9852 	fletcher_4_native(tmpbuf, asize, NULL,
9853 	    &l2dhdr->dh_start_lbps[0].lbp_cksum);
9854 
9855 	abd_put(abd_buf->abd);
9856 
9857 	/* perform the write itself */
9858 	abd_buf->abd = abd_get_from_buf(tmpbuf, sizeof (*lb));
9859 	abd_take_ownership_of_buf(abd_buf->abd, B_TRUE);
9860 	wzio = zio_write_phys(pio, dev->l2ad_vdev, dev->l2ad_hand,
9861 	    asize, abd_buf->abd, ZIO_CHECKSUM_OFF, NULL, NULL,
9862 	    ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_CANFAIL, B_FALSE);
9863 	DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev, zio_t *, wzio);
9864 	(void) zio_nowait(wzio);
9865 
9866 	dev->l2ad_hand += asize;
9867 	/*
9868 	 * Include the committed log block's pointer  in the list of pointers
9869 	 * to log blocks present in the L2ARC device.
9870 	 */
9871 	bcopy(&l2dhdr->dh_start_lbps[0], lb_ptr_buf->lb_ptr,
9872 	    sizeof (l2arc_log_blkptr_t));
9873 	mutex_enter(&dev->l2ad_mtx);
9874 	list_insert_head(&dev->l2ad_lbptr_list, lb_ptr_buf);
9875 	ARCSTAT_INCR(arcstat_l2_log_blk_asize, asize);
9876 	ARCSTAT_BUMP(arcstat_l2_log_blk_count);
9877 	zfs_refcount_add_many(&dev->l2ad_lb_asize, asize, lb_ptr_buf);
9878 	zfs_refcount_add(&dev->l2ad_lb_count, lb_ptr_buf);
9879 	mutex_exit(&dev->l2ad_mtx);
9880 	vdev_space_update(dev->l2ad_vdev, asize, 0, 0);
9881 
9882 	/* bump the kstats */
9883 	ARCSTAT_INCR(arcstat_l2_write_bytes, asize);
9884 	ARCSTAT_BUMP(arcstat_l2_log_blk_writes);
9885 	ARCSTAT_F_AVG(arcstat_l2_log_blk_avg_asize, asize);
9886 	ARCSTAT_F_AVG(arcstat_l2_data_to_meta_ratio,
9887 	    dev->l2ad_log_blk_payload_asize / asize);
9888 
9889 	/* start a new log block */
9890 	dev->l2ad_log_ent_idx = 0;
9891 	dev->l2ad_log_blk_payload_asize = 0;
9892 	dev->l2ad_log_blk_payload_start = 0;
9893 }
9894 
9895 /*
9896  * Validates an L2ARC log block address to make sure that it can be read
9897  * from the provided L2ARC device.
9898  */
9899 boolean_t
9900 l2arc_log_blkptr_valid(l2arc_dev_t *dev, const l2arc_log_blkptr_t *lbp)
9901 {
9902 	/* L2BLK_GET_PSIZE returns aligned size for log blocks */
9903 	uint64_t asize = L2BLK_GET_PSIZE((lbp)->lbp_prop);
9904 	uint64_t end = lbp->lbp_daddr + asize - 1;
9905 	uint64_t start = lbp->lbp_payload_start;
9906 	boolean_t evicted = B_FALSE;
9907 
9908 	/* BEGIN CSTYLED */
9909 	/*
9910 	 * A log block is valid if all of the following conditions are true:
9911 	 * - it fits entirely (including its payload) between l2ad_start and
9912 	 *   l2ad_end
9913 	 * - it has a valid size
9914 	 * - neither the log block itself nor part of its payload was evicted
9915 	 *   by l2arc_evict():
9916 	 *
9917 	 *		l2ad_hand          l2ad_evict
9918 	 *		|			 |	lbp_daddr
9919 	 *		|     start		 |	|  end
9920 	 *		|     |			 |	|  |
9921 	 *		V     V		         V	V  V
9922 	 *   l2ad_start ============================================ l2ad_end
9923 	 *                    --------------------------||||
9924 	 *				^		 ^
9925 	 *				|		log block
9926 	 *				payload
9927 	 */
9928 	/* END CSTYLED */
9929 	evicted =
9930 	    l2arc_range_check_overlap(start, end, dev->l2ad_hand) ||
9931 	    l2arc_range_check_overlap(start, end, dev->l2ad_evict) ||
9932 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, start) ||
9933 	    l2arc_range_check_overlap(dev->l2ad_hand, dev->l2ad_evict, end);
9934 
9935 	return (start >= dev->l2ad_start && end <= dev->l2ad_end &&
9936 	    asize > 0 && asize <= sizeof (l2arc_log_blk_phys_t) &&
9937 	    (!evicted || dev->l2ad_first));
9938 }
9939 
9940 /*
9941  * Inserts ARC buffer header `hdr' into the current L2ARC log block on
9942  * the device. The buffer being inserted must be present in L2ARC.
9943  * Returns B_TRUE if the L2ARC log block is full and needs to be committed
9944  * to L2ARC, or B_FALSE if it still has room for more ARC buffers.
9945  */
9946 static boolean_t
9947 l2arc_log_blk_insert(l2arc_dev_t *dev, const arc_buf_hdr_t *hdr)
9948 {
9949 	l2arc_log_blk_phys_t	*lb = &dev->l2ad_log_blk;
9950 	l2arc_log_ent_phys_t	*le;
9951 
9952 	if (dev->l2ad_log_entries == 0)
9953 		return (B_FALSE);
9954 
9955 	int index = dev->l2ad_log_ent_idx++;
9956 
9957 	ASSERT3S(index, <, dev->l2ad_log_entries);
9958 	ASSERT(HDR_HAS_L2HDR(hdr));
9959 
9960 	le = &lb->lb_entries[index];
9961 	bzero(le, sizeof (*le));
9962 	le->le_dva = hdr->b_dva;
9963 	le->le_birth = hdr->b_birth;
9964 	le->le_daddr = hdr->b_l2hdr.b_daddr;
9965 	if (index == 0)
9966 		dev->l2ad_log_blk_payload_start = le->le_daddr;
9967 	L2BLK_SET_LSIZE((le)->le_prop, HDR_GET_LSIZE(hdr));
9968 	L2BLK_SET_PSIZE((le)->le_prop, HDR_GET_PSIZE(hdr));
9969 	L2BLK_SET_COMPRESS((le)->le_prop, HDR_GET_COMPRESS(hdr));
9970 	L2BLK_SET_TYPE((le)->le_prop, hdr->b_type);
9971 	L2BLK_SET_PROTECTED((le)->le_prop, !!(HDR_PROTECTED(hdr)));
9972 	L2BLK_SET_PREFETCH((le)->le_prop, !!(HDR_PREFETCH(hdr)));
9973 	L2BLK_SET_STATE((le)->le_prop, hdr->b_l1hdr.b_state->arcs_state);
9974 
9975 	dev->l2ad_log_blk_payload_asize += vdev_psize_to_asize(dev->l2ad_vdev,
9976 	    HDR_GET_PSIZE(hdr));
9977 
9978 	return (dev->l2ad_log_ent_idx == dev->l2ad_log_entries);
9979 }
9980 
9981 /*
9982  * Checks whether a given L2ARC device address sits in a time-sequential
9983  * range. The trick here is that the L2ARC is a rotary buffer, so we can't
9984  * just do a range comparison, we need to handle the situation in which the
9985  * range wraps around the end of the L2ARC device. Arguments:
9986  *	bottom -- Lower end of the range to check (written to earlier).
9987  *	top    -- Upper end of the range to check (written to later).
9988  *	check  -- The address for which we want to determine if it sits in
9989  *		  between the top and bottom.
9990  *
9991  * The 3-way conditional below represents the following cases:
9992  *
9993  *	bottom < top : Sequentially ordered case:
9994  *	  <check>--------+-------------------+
9995  *	                 |  (overlap here?)  |
9996  *	 L2ARC dev       V                   V
9997  *	 |---------------<bottom>============<top>--------------|
9998  *
9999  *	bottom > top: Looped-around case:
10000  *	                      <check>--------+------------------+
10001  *	                                     |  (overlap here?) |
10002  *	 L2ARC dev                           V                  V
10003  *	 |===============<top>---------------<bottom>===========|
10004  *	 ^               ^
10005  *	 |  (or here?)   |
10006  *	 +---------------+---------<check>
10007  *
10008  *	top == bottom : Just a single address comparison.
10009  */
10010 boolean_t
10011 l2arc_range_check_overlap(uint64_t bottom, uint64_t top, uint64_t check)
10012 {
10013 	if (bottom < top)
10014 		return (bottom <= check && check <= top);
10015 	else if (bottom > top)
10016 		return (check <= top || bottom <= check);
10017 	else
10018 		return (check == top);
10019 }
10020