xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision e914ace2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2018, Joyent, Inc.
24  * Copyright (c) 2011, 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  */
28 
29 /*
30  * DVA-based Adjustable Replacement Cache
31  *
32  * While much of the theory of operation used here is
33  * based on the self-tuning, low overhead replacement cache
34  * presented by Megiddo and Modha at FAST 2003, there are some
35  * significant differences:
36  *
37  * 1. The Megiddo and Modha model assumes any page is evictable.
38  * Pages in its cache cannot be "locked" into memory.  This makes
39  * the eviction algorithm simple: evict the last page in the list.
40  * This also make the performance characteristics easy to reason
41  * about.  Our cache is not so simple.  At any given moment, some
42  * subset of the blocks in the cache are un-evictable because we
43  * have handed out a reference to them.  Blocks are only evictable
44  * when there are no external references active.  This makes
45  * eviction far more problematic:  we choose to evict the evictable
46  * blocks that are the "lowest" in the list.
47  *
48  * There are times when it is not possible to evict the requested
49  * space.  In these circumstances we are unable to adjust the cache
50  * size.  To prevent the cache growing unbounded at these times we
51  * implement a "cache throttle" that slows the flow of new data
52  * into the cache until we can make space available.
53  *
54  * 2. The Megiddo and Modha model assumes a fixed cache size.
55  * Pages are evicted when the cache is full and there is a cache
56  * miss.  Our model has a variable sized cache.  It grows with
57  * high use, but also tries to react to memory pressure from the
58  * operating system: decreasing its size when system memory is
59  * tight.
60  *
61  * 3. The Megiddo and Modha model assumes a fixed page size. All
62  * elements of the cache are therefore exactly the same size.  So
63  * when adjusting the cache size following a cache miss, its simply
64  * a matter of choosing a single page to evict.  In our model, we
65  * have variable sized cache blocks (rangeing from 512 bytes to
66  * 128K bytes).  We therefore choose a set of blocks to evict to make
67  * space for a cache miss that approximates as closely as possible
68  * the space used by the new block.
69  *
70  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71  * by N. Megiddo & D. Modha, FAST 2003
72  */
73 
74 /*
75  * The locking model:
76  *
77  * A new reference to a cache buffer can be obtained in two
78  * ways: 1) via a hash table lookup using the DVA as a key,
79  * or 2) via one of the ARC lists.  The arc_read() interface
80  * uses method 1, while the internal ARC algorithms for
81  * adjusting the cache use method 2.  We therefore provide two
82  * types of locks: 1) the hash table lock array, and 2) the
83  * ARC list locks.
84  *
85  * Buffers do not have their own mutexes, rather they rely on the
86  * hash table mutexes for the bulk of their protection (i.e. most
87  * fields in the arc_buf_hdr_t are protected by these mutexes).
88  *
89  * buf_hash_find() returns the appropriate mutex (held) when it
90  * locates the requested buffer in the hash table.  It returns
91  * NULL for the mutex if the buffer was not in the table.
92  *
93  * buf_hash_remove() expects the appropriate hash mutex to be
94  * already held before it is invoked.
95  *
96  * Each ARC state also has a mutex which is used to protect the
97  * buffer list associated with the state.  When attempting to
98  * obtain a hash table lock while holding an ARC list lock you
99  * must use: mutex_tryenter() to avoid deadlock.  Also note that
100  * the active state mutex must be held before the ghost state mutex.
101  *
102  * Note that the majority of the performance stats are manipulated
103  * with atomic operations.
104  *
105  * The L2ARC uses the l2ad_mtx on each vdev for the following:
106  *
107  *	- L2ARC buflist creation
108  *	- L2ARC buflist eviction
109  *	- L2ARC write completion, which walks L2ARC buflists
110  *	- ARC header destruction, as it removes from L2ARC buflists
111  *	- ARC header release, as it removes from L2ARC buflists
112  */
113 
114 /*
115  * ARC operation:
116  *
117  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
118  * This structure can point either to a block that is still in the cache or to
119  * one that is only accessible in an L2 ARC device, or it can provide
120  * information about a block that was recently evicted. If a block is
121  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
122  * information to retrieve it from the L2ARC device. This information is
123  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
124  * that is in this state cannot access the data directly.
125  *
126  * Blocks that are actively being referenced or have not been evicted
127  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
128  * the arc_buf_hdr_t that will point to the data block in memory. A block can
129  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
130  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
131  * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
132  *
133  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
134  * ability to store the physical data (b_pabd) associated with the DVA of the
135  * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
136  * it will match its on-disk compression characteristics. This behavior can be
137  * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
138  * compressed ARC functionality is disabled, the b_pabd will point to an
139  * uncompressed version of the on-disk data.
140  *
141  * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
142  * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
143  * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
144  * consumer. The ARC will provide references to this data and will keep it
145  * cached until it is no longer in use. The ARC caches only the L1ARC's physical
146  * data block and will evict any arc_buf_t that is no longer referenced. The
147  * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
148  * "overhead_size" kstat.
149  *
150  * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
151  * compressed form. The typical case is that consumers will want uncompressed
152  * data, and when that happens a new data buffer is allocated where the data is
153  * decompressed for them to use. Currently the only consumer who wants
154  * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
155  * exists on disk. When this happens, the arc_buf_t's data buffer is shared
156  * with the arc_buf_hdr_t.
157  *
158  * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
159  * first one is owned by a compressed send consumer (and therefore references
160  * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
161  * used by any other consumer (and has its own uncompressed copy of the data
162  * buffer).
163  *
164  *   arc_buf_hdr_t
165  *   +-----------+
166  *   | fields    |
167  *   | common to |
168  *   | L1- and   |
169  *   | L2ARC     |
170  *   +-----------+
171  *   | l2arc_buf_hdr_t
172  *   |           |
173  *   +-----------+
174  *   | l1arc_buf_hdr_t
175  *   |           |              arc_buf_t
176  *   | b_buf     +------------>+-----------+      arc_buf_t
177  *   | b_pabd    +-+           |b_next     +---->+-----------+
178  *   +-----------+ |           |-----------|     |b_next     +-->NULL
179  *                 |           |b_comp = T |     +-----------+
180  *                 |           |b_data     +-+   |b_comp = F |
181  *                 |           +-----------+ |   |b_data     +-+
182  *                 +->+------+               |   +-----------+ |
183  *        compressed  |      |               |                 |
184  *           data     |      |<--------------+                 | uncompressed
185  *                    +------+          compressed,            |     data
186  *                                        shared               +-->+------+
187  *                                         data                    |      |
188  *                                                                 |      |
189  *                                                                 +------+
190  *
191  * When a consumer reads a block, the ARC must first look to see if the
192  * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
193  * arc_buf_t and either copies uncompressed data into a new data buffer from an
194  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
195  * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
196  * hdr is compressed and the desired compression characteristics of the
197  * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
198  * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
199  * the last buffer in the hdr's b_buf list, however a shared compressed buf can
200  * be anywhere in the hdr's list.
201  *
202  * The diagram below shows an example of an uncompressed ARC hdr that is
203  * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
204  * the last element in the buf list):
205  *
206  *                arc_buf_hdr_t
207  *                +-----------+
208  *                |           |
209  *                |           |
210  *                |           |
211  *                +-----------+
212  * l2arc_buf_hdr_t|           |
213  *                |           |
214  *                +-----------+
215  * l1arc_buf_hdr_t|           |
216  *                |           |                 arc_buf_t    (shared)
217  *                |    b_buf  +------------>+---------+      arc_buf_t
218  *                |           |             |b_next   +---->+---------+
219  *                |  b_pabd   +-+           |---------|     |b_next   +-->NULL
220  *                +-----------+ |           |         |     +---------+
221  *                              |           |b_data   +-+   |         |
222  *                              |           +---------+ |   |b_data   +-+
223  *                              +->+------+             |   +---------+ |
224  *                                 |      |             |               |
225  *                   uncompressed  |      |             |               |
226  *                        data     +------+             |               |
227  *                                    ^                 +->+------+     |
228  *                                    |       uncompressed |      |     |
229  *                                    |           data     |      |     |
230  *                                    |                    +------+     |
231  *                                    +---------------------------------+
232  *
233  * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
234  * since the physical block is about to be rewritten. The new data contents
235  * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
236  * it may compress the data before writing it to disk. The ARC will be called
237  * with the transformed data and will bcopy the transformed on-disk block into
238  * a newly allocated b_pabd. Writes are always done into buffers which have
239  * either been loaned (and hence are new and don't have other readers) or
240  * buffers which have been released (and hence have their own hdr, if there
241  * were originally other readers of the buf's original hdr). This ensures that
242  * the ARC only needs to update a single buf and its hdr after a write occurs.
243  *
244  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
245  * L2ARC will always write the contents of b_pabd to the L2ARC. This means
246  * that when compressed ARC is enabled that the L2ARC blocks are identical
247  * to the on-disk block in the main data pool. This provides a significant
248  * advantage since the ARC can leverage the bp's checksum when reading from the
249  * L2ARC to determine if the contents are valid. However, if the compressed
250  * ARC is disabled, then the L2ARC's block must be transformed to look
251  * like the physical block in the main data pool before comparing the
252  * checksum and determining its validity.
253  */
254 
255 #include <sys/spa.h>
256 #include <sys/zio.h>
257 #include <sys/spa_impl.h>
258 #include <sys/zio_compress.h>
259 #include <sys/zio_checksum.h>
260 #include <sys/zfs_context.h>
261 #include <sys/arc.h>
262 #include <sys/refcount.h>
263 #include <sys/vdev.h>
264 #include <sys/vdev_impl.h>
265 #include <sys/dsl_pool.h>
266 #include <sys/zio_checksum.h>
267 #include <sys/multilist.h>
268 #include <sys/abd.h>
269 #ifdef _KERNEL
270 #include <sys/vmsystm.h>
271 #include <vm/anon.h>
272 #include <sys/fs/swapnode.h>
273 #include <sys/dnlc.h>
274 #endif
275 #include <sys/callb.h>
276 #include <sys/kstat.h>
277 #include <sys/zthr.h>
278 #include <zfs_fletcher.h>
279 #include <sys/aggsum.h>
280 #include <sys/cityhash.h>
281 
282 #ifndef _KERNEL
283 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
284 boolean_t arc_watch = B_FALSE;
285 int arc_procfd;
286 #endif
287 
288 /*
289  * This thread's job is to keep enough free memory in the system, by
290  * calling arc_kmem_reap_now() plus arc_shrink(), which improves
291  * arc_available_memory().
292  */
293 static zthr_t		*arc_reap_zthr;
294 
295 /*
296  * This thread's job is to keep arc_size under arc_c, by calling
297  * arc_adjust(), which improves arc_is_overflowing().
298  */
299 static zthr_t		*arc_adjust_zthr;
300 
301 static kmutex_t		arc_adjust_lock;
302 static kcondvar_t	arc_adjust_waiters_cv;
303 static boolean_t	arc_adjust_needed = B_FALSE;
304 
305 uint_t arc_reduce_dnlc_percent = 3;
306 
307 /*
308  * The number of headers to evict in arc_evict_state_impl() before
309  * dropping the sublist lock and evicting from another sublist. A lower
310  * value means we're more likely to evict the "correct" header (i.e. the
311  * oldest header in the arc state), but comes with higher overhead
312  * (i.e. more invocations of arc_evict_state_impl()).
313  */
314 int zfs_arc_evict_batch_limit = 10;
315 
316 /* number of seconds before growing cache again */
317 int arc_grow_retry = 60;
318 
319 /*
320  * Minimum time between calls to arc_kmem_reap_soon().  Note that this will
321  * be converted to ticks, so with the default hz=100, a setting of 15 ms
322  * will actually wait 2 ticks, or 20ms.
323  */
324 int arc_kmem_cache_reap_retry_ms = 1000;
325 
326 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
327 int zfs_arc_overflow_shift = 8;
328 
329 /* shift of arc_c for calculating both min and max arc_p */
330 int arc_p_min_shift = 4;
331 
332 /* log2(fraction of arc to reclaim) */
333 int arc_shrink_shift = 7;
334 
335 /*
336  * log2(fraction of ARC which must be free to allow growing).
337  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
338  * when reading a new block into the ARC, we will evict an equal-sized block
339  * from the ARC.
340  *
341  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
342  * we will still not allow it to grow.
343  */
344 int			arc_no_grow_shift = 5;
345 
346 
347 /*
348  * minimum lifespan of a prefetch block in clock ticks
349  * (initialized in arc_init())
350  */
351 static int		arc_min_prefetch_lifespan;
352 
353 /*
354  * If this percent of memory is free, don't throttle.
355  */
356 int arc_lotsfree_percent = 10;
357 
358 static boolean_t arc_initialized;
359 
360 /*
361  * The arc has filled available memory and has now warmed up.
362  */
363 static boolean_t arc_warm;
364 
365 /*
366  * log2 fraction of the zio arena to keep free.
367  */
368 int arc_zio_arena_free_shift = 2;
369 
370 /*
371  * These tunables are for performance analysis.
372  */
373 uint64_t zfs_arc_max;
374 uint64_t zfs_arc_min;
375 uint64_t zfs_arc_meta_limit = 0;
376 uint64_t zfs_arc_meta_min = 0;
377 int zfs_arc_grow_retry = 0;
378 int zfs_arc_shrink_shift = 0;
379 int zfs_arc_p_min_shift = 0;
380 int zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
381 
382 /*
383  * ARC dirty data constraints for arc_tempreserve_space() throttle
384  */
385 uint_t zfs_arc_dirty_limit_percent = 50;	/* total dirty data limit */
386 uint_t zfs_arc_anon_limit_percent = 25;		/* anon block dirty limit */
387 uint_t zfs_arc_pool_dirty_percent = 20;		/* each pool's anon allowance */
388 
389 boolean_t zfs_compressed_arc_enabled = B_TRUE;
390 
391 /*
392  * Note that buffers can be in one of 6 states:
393  *	ARC_anon	- anonymous (discussed below)
394  *	ARC_mru		- recently used, currently cached
395  *	ARC_mru_ghost	- recentely used, no longer in cache
396  *	ARC_mfu		- frequently used, currently cached
397  *	ARC_mfu_ghost	- frequently used, no longer in cache
398  *	ARC_l2c_only	- exists in L2ARC but not other states
399  * When there are no active references to the buffer, they are
400  * are linked onto a list in one of these arc states.  These are
401  * the only buffers that can be evicted or deleted.  Within each
402  * state there are multiple lists, one for meta-data and one for
403  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
404  * etc.) is tracked separately so that it can be managed more
405  * explicitly: favored over data, limited explicitly.
406  *
407  * Anonymous buffers are buffers that are not associated with
408  * a DVA.  These are buffers that hold dirty block copies
409  * before they are written to stable storage.  By definition,
410  * they are "ref'd" and are considered part of arc_mru
411  * that cannot be freed.  Generally, they will aquire a DVA
412  * as they are written and migrate onto the arc_mru list.
413  *
414  * The ARC_l2c_only state is for buffers that are in the second
415  * level ARC but no longer in any of the ARC_m* lists.  The second
416  * level ARC itself may also contain buffers that are in any of
417  * the ARC_m* states - meaning that a buffer can exist in two
418  * places.  The reason for the ARC_l2c_only state is to keep the
419  * buffer header in the hash table, so that reads that hit the
420  * second level ARC benefit from these fast lookups.
421  */
422 
423 typedef struct arc_state {
424 	/*
425 	 * list of evictable buffers
426 	 */
427 	multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
428 	/*
429 	 * total amount of evictable data in this state
430 	 */
431 	zfs_refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
432 	/*
433 	 * total amount of data in this state; this includes: evictable,
434 	 * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
435 	 */
436 	zfs_refcount_t arcs_size;
437 } arc_state_t;
438 
439 /* The 6 states: */
440 static arc_state_t ARC_anon;
441 static arc_state_t ARC_mru;
442 static arc_state_t ARC_mru_ghost;
443 static arc_state_t ARC_mfu;
444 static arc_state_t ARC_mfu_ghost;
445 static arc_state_t ARC_l2c_only;
446 
447 typedef struct arc_stats {
448 	kstat_named_t arcstat_hits;
449 	kstat_named_t arcstat_misses;
450 	kstat_named_t arcstat_demand_data_hits;
451 	kstat_named_t arcstat_demand_data_misses;
452 	kstat_named_t arcstat_demand_metadata_hits;
453 	kstat_named_t arcstat_demand_metadata_misses;
454 	kstat_named_t arcstat_prefetch_data_hits;
455 	kstat_named_t arcstat_prefetch_data_misses;
456 	kstat_named_t arcstat_prefetch_metadata_hits;
457 	kstat_named_t arcstat_prefetch_metadata_misses;
458 	kstat_named_t arcstat_mru_hits;
459 	kstat_named_t arcstat_mru_ghost_hits;
460 	kstat_named_t arcstat_mfu_hits;
461 	kstat_named_t arcstat_mfu_ghost_hits;
462 	kstat_named_t arcstat_deleted;
463 	/*
464 	 * Number of buffers that could not be evicted because the hash lock
465 	 * was held by another thread.  The lock may not necessarily be held
466 	 * by something using the same buffer, since hash locks are shared
467 	 * by multiple buffers.
468 	 */
469 	kstat_named_t arcstat_mutex_miss;
470 	/*
471 	 * Number of buffers skipped because they have I/O in progress, are
472 	 * indrect prefetch buffers that have not lived long enough, or are
473 	 * not from the spa we're trying to evict from.
474 	 */
475 	kstat_named_t arcstat_evict_skip;
476 	/*
477 	 * Number of times arc_evict_state() was unable to evict enough
478 	 * buffers to reach it's target amount.
479 	 */
480 	kstat_named_t arcstat_evict_not_enough;
481 	kstat_named_t arcstat_evict_l2_cached;
482 	kstat_named_t arcstat_evict_l2_eligible;
483 	kstat_named_t arcstat_evict_l2_ineligible;
484 	kstat_named_t arcstat_evict_l2_skip;
485 	kstat_named_t arcstat_hash_elements;
486 	kstat_named_t arcstat_hash_elements_max;
487 	kstat_named_t arcstat_hash_collisions;
488 	kstat_named_t arcstat_hash_chains;
489 	kstat_named_t arcstat_hash_chain_max;
490 	kstat_named_t arcstat_p;
491 	kstat_named_t arcstat_c;
492 	kstat_named_t arcstat_c_min;
493 	kstat_named_t arcstat_c_max;
494 	/* Not updated directly; only synced in arc_kstat_update. */
495 	kstat_named_t arcstat_size;
496 	/*
497 	 * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
498 	 * Note that the compressed bytes may match the uncompressed bytes
499 	 * if the block is either not compressed or compressed arc is disabled.
500 	 */
501 	kstat_named_t arcstat_compressed_size;
502 	/*
503 	 * Uncompressed size of the data stored in b_pabd. If compressed
504 	 * arc is disabled then this value will be identical to the stat
505 	 * above.
506 	 */
507 	kstat_named_t arcstat_uncompressed_size;
508 	/*
509 	 * Number of bytes stored in all the arc_buf_t's. This is classified
510 	 * as "overhead" since this data is typically short-lived and will
511 	 * be evicted from the arc when it becomes unreferenced unless the
512 	 * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
513 	 * values have been set (see comment in dbuf.c for more information).
514 	 */
515 	kstat_named_t arcstat_overhead_size;
516 	/*
517 	 * Number of bytes consumed by internal ARC structures necessary
518 	 * for tracking purposes; these structures are not actually
519 	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
520 	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
521 	 * caches), and arc_buf_t structures (allocated via arc_buf_t
522 	 * cache).
523 	 * Not updated directly; only synced in arc_kstat_update.
524 	 */
525 	kstat_named_t arcstat_hdr_size;
526 	/*
527 	 * Number of bytes consumed by ARC buffers of type equal to
528 	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
529 	 * on disk user data (e.g. plain file contents).
530 	 * Not updated directly; only synced in arc_kstat_update.
531 	 */
532 	kstat_named_t arcstat_data_size;
533 	/*
534 	 * Number of bytes consumed by ARC buffers of type equal to
535 	 * ARC_BUFC_METADATA. This is generally consumed by buffers
536 	 * backing on disk data that is used for internal ZFS
537 	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
538 	 * Not updated directly; only synced in arc_kstat_update.
539 	 */
540 	kstat_named_t arcstat_metadata_size;
541 	/*
542 	 * Number of bytes consumed by various buffers and structures
543 	 * not actually backed with ARC buffers. This includes bonus
544 	 * buffers (allocated directly via zio_buf_* functions),
545 	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
546 	 * cache), and dnode_t structures (allocated via dnode_t cache).
547 	 * Not updated directly; only synced in arc_kstat_update.
548 	 */
549 	kstat_named_t arcstat_other_size;
550 	/*
551 	 * Total number of bytes consumed by ARC buffers residing in the
552 	 * arc_anon state. This includes *all* buffers in the arc_anon
553 	 * state; e.g. data, metadata, evictable, and unevictable buffers
554 	 * are all included in this value.
555 	 * Not updated directly; only synced in arc_kstat_update.
556 	 */
557 	kstat_named_t arcstat_anon_size;
558 	/*
559 	 * Number of bytes consumed by ARC buffers that meet the
560 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
561 	 * residing in the arc_anon state, and are eligible for eviction
562 	 * (e.g. have no outstanding holds on the buffer).
563 	 * Not updated directly; only synced in arc_kstat_update.
564 	 */
565 	kstat_named_t arcstat_anon_evictable_data;
566 	/*
567 	 * Number of bytes consumed by ARC buffers that meet the
568 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
569 	 * residing in the arc_anon state, and are eligible for eviction
570 	 * (e.g. have no outstanding holds on the buffer).
571 	 * Not updated directly; only synced in arc_kstat_update.
572 	 */
573 	kstat_named_t arcstat_anon_evictable_metadata;
574 	/*
575 	 * Total number of bytes consumed by ARC buffers residing in the
576 	 * arc_mru state. This includes *all* buffers in the arc_mru
577 	 * state; e.g. data, metadata, evictable, and unevictable buffers
578 	 * are all included in this value.
579 	 * Not updated directly; only synced in arc_kstat_update.
580 	 */
581 	kstat_named_t arcstat_mru_size;
582 	/*
583 	 * Number of bytes consumed by ARC buffers that meet the
584 	 * following criteria: backing buffers of type ARC_BUFC_DATA,
585 	 * residing in the arc_mru state, and are eligible for eviction
586 	 * (e.g. have no outstanding holds on the buffer).
587 	 * Not updated directly; only synced in arc_kstat_update.
588 	 */
589 	kstat_named_t arcstat_mru_evictable_data;
590 	/*
591 	 * Number of bytes consumed by ARC buffers that meet the
592 	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
593 	 * residing in the arc_mru state, and are eligible for eviction
594 	 * (e.g. have no outstanding holds on the buffer).
595 	 * Not updated directly; only synced in arc_kstat_update.
596 	 */
597 	kstat_named_t arcstat_mru_evictable_metadata;
598 	/*
599 	 * Total number of bytes that *would have been* consumed by ARC
600 	 * buffers in the arc_mru_ghost state. The key thing to note
601 	 * here, is the fact that this size doesn't actually indicate
602 	 * RAM consumption. The ghost lists only consist of headers and
603 	 * don't actually have ARC buffers linked off of these headers.
604 	 * Thus, *if* the headers had associated ARC buffers, these
605 	 * buffers *would have* consumed this number of bytes.
606 	 * Not updated directly; only synced in arc_kstat_update.
607 	 */
608 	kstat_named_t arcstat_mru_ghost_size;
609 	/*
610 	 * Number of bytes that *would have been* consumed by ARC
611 	 * buffers that are eligible for eviction, of type
612 	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
613 	 * Not updated directly; only synced in arc_kstat_update.
614 	 */
615 	kstat_named_t arcstat_mru_ghost_evictable_data;
616 	/*
617 	 * Number of bytes that *would have been* consumed by ARC
618 	 * buffers that are eligible for eviction, of type
619 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
620 	 * Not updated directly; only synced in arc_kstat_update.
621 	 */
622 	kstat_named_t arcstat_mru_ghost_evictable_metadata;
623 	/*
624 	 * Total number of bytes consumed by ARC buffers residing in the
625 	 * arc_mfu state. This includes *all* buffers in the arc_mfu
626 	 * state; e.g. data, metadata, evictable, and unevictable buffers
627 	 * are all included in this value.
628 	 * Not updated directly; only synced in arc_kstat_update.
629 	 */
630 	kstat_named_t arcstat_mfu_size;
631 	/*
632 	 * Number of bytes consumed by ARC buffers that are eligible for
633 	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
634 	 * state.
635 	 * Not updated directly; only synced in arc_kstat_update.
636 	 */
637 	kstat_named_t arcstat_mfu_evictable_data;
638 	/*
639 	 * Number of bytes consumed by ARC buffers that are eligible for
640 	 * eviction, of type ARC_BUFC_METADATA, and reside in the
641 	 * arc_mfu state.
642 	 * Not updated directly; only synced in arc_kstat_update.
643 	 */
644 	kstat_named_t arcstat_mfu_evictable_metadata;
645 	/*
646 	 * Total number of bytes that *would have been* consumed by ARC
647 	 * buffers in the arc_mfu_ghost state. See the comment above
648 	 * arcstat_mru_ghost_size for more details.
649 	 * Not updated directly; only synced in arc_kstat_update.
650 	 */
651 	kstat_named_t arcstat_mfu_ghost_size;
652 	/*
653 	 * Number of bytes that *would have been* consumed by ARC
654 	 * buffers that are eligible for eviction, of type
655 	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
656 	 * Not updated directly; only synced in arc_kstat_update.
657 	 */
658 	kstat_named_t arcstat_mfu_ghost_evictable_data;
659 	/*
660 	 * Number of bytes that *would have been* consumed by ARC
661 	 * buffers that are eligible for eviction, of type
662 	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
663 	 * Not updated directly; only synced in arc_kstat_update.
664 	 */
665 	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
666 	kstat_named_t arcstat_l2_hits;
667 	kstat_named_t arcstat_l2_misses;
668 	kstat_named_t arcstat_l2_feeds;
669 	kstat_named_t arcstat_l2_rw_clash;
670 	kstat_named_t arcstat_l2_read_bytes;
671 	kstat_named_t arcstat_l2_write_bytes;
672 	kstat_named_t arcstat_l2_writes_sent;
673 	kstat_named_t arcstat_l2_writes_done;
674 	kstat_named_t arcstat_l2_writes_error;
675 	kstat_named_t arcstat_l2_writes_lock_retry;
676 	kstat_named_t arcstat_l2_evict_lock_retry;
677 	kstat_named_t arcstat_l2_evict_reading;
678 	kstat_named_t arcstat_l2_evict_l1cached;
679 	kstat_named_t arcstat_l2_free_on_write;
680 	kstat_named_t arcstat_l2_abort_lowmem;
681 	kstat_named_t arcstat_l2_cksum_bad;
682 	kstat_named_t arcstat_l2_io_error;
683 	kstat_named_t arcstat_l2_lsize;
684 	kstat_named_t arcstat_l2_psize;
685 	/* Not updated directly; only synced in arc_kstat_update. */
686 	kstat_named_t arcstat_l2_hdr_size;
687 	kstat_named_t arcstat_memory_throttle_count;
688 	/* Not updated directly; only synced in arc_kstat_update. */
689 	kstat_named_t arcstat_meta_used;
690 	kstat_named_t arcstat_meta_limit;
691 	kstat_named_t arcstat_meta_max;
692 	kstat_named_t arcstat_meta_min;
693 	kstat_named_t arcstat_sync_wait_for_async;
694 	kstat_named_t arcstat_demand_hit_predictive_prefetch;
695 } arc_stats_t;
696 
697 static arc_stats_t arc_stats = {
698 	{ "hits",			KSTAT_DATA_UINT64 },
699 	{ "misses",			KSTAT_DATA_UINT64 },
700 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
701 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
702 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
703 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
704 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
705 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
706 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
707 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
708 	{ "mru_hits",			KSTAT_DATA_UINT64 },
709 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
710 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
711 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
712 	{ "deleted",			KSTAT_DATA_UINT64 },
713 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
714 	{ "evict_skip",			KSTAT_DATA_UINT64 },
715 	{ "evict_not_enough",		KSTAT_DATA_UINT64 },
716 	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
717 	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
718 	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
719 	{ "evict_l2_skip",		KSTAT_DATA_UINT64 },
720 	{ "hash_elements",		KSTAT_DATA_UINT64 },
721 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
722 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
723 	{ "hash_chains",		KSTAT_DATA_UINT64 },
724 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
725 	{ "p",				KSTAT_DATA_UINT64 },
726 	{ "c",				KSTAT_DATA_UINT64 },
727 	{ "c_min",			KSTAT_DATA_UINT64 },
728 	{ "c_max",			KSTAT_DATA_UINT64 },
729 	{ "size",			KSTAT_DATA_UINT64 },
730 	{ "compressed_size",		KSTAT_DATA_UINT64 },
731 	{ "uncompressed_size",		KSTAT_DATA_UINT64 },
732 	{ "overhead_size",		KSTAT_DATA_UINT64 },
733 	{ "hdr_size",			KSTAT_DATA_UINT64 },
734 	{ "data_size",			KSTAT_DATA_UINT64 },
735 	{ "metadata_size",		KSTAT_DATA_UINT64 },
736 	{ "other_size",			KSTAT_DATA_UINT64 },
737 	{ "anon_size",			KSTAT_DATA_UINT64 },
738 	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
739 	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
740 	{ "mru_size",			KSTAT_DATA_UINT64 },
741 	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
742 	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
743 	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
744 	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
745 	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
746 	{ "mfu_size",			KSTAT_DATA_UINT64 },
747 	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
748 	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
749 	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
750 	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
751 	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
752 	{ "l2_hits",			KSTAT_DATA_UINT64 },
753 	{ "l2_misses",			KSTAT_DATA_UINT64 },
754 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
755 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
756 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
757 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
758 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
759 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
760 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
761 	{ "l2_writes_lock_retry",	KSTAT_DATA_UINT64 },
762 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
763 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
764 	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
765 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
766 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
767 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
768 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
769 	{ "l2_size",			KSTAT_DATA_UINT64 },
770 	{ "l2_asize",			KSTAT_DATA_UINT64 },
771 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
772 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
773 	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
774 	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
775 	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
776 	{ "arc_meta_min",		KSTAT_DATA_UINT64 },
777 	{ "sync_wait_for_async",	KSTAT_DATA_UINT64 },
778 	{ "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
779 };
780 
781 #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
782 
783 #define	ARCSTAT_INCR(stat, val) \
784 	atomic_add_64(&arc_stats.stat.value.ui64, (val))
785 
786 #define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
787 #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
788 
789 #define	ARCSTAT_MAX(stat, val) {					\
790 	uint64_t m;							\
791 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
792 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
793 		continue;						\
794 }
795 
796 #define	ARCSTAT_MAXSTAT(stat) \
797 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
798 
799 /*
800  * We define a macro to allow ARC hits/misses to be easily broken down by
801  * two separate conditions, giving a total of four different subtypes for
802  * each of hits and misses (so eight statistics total).
803  */
804 #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
805 	if (cond1) {							\
806 		if (cond2) {						\
807 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
808 		} else {						\
809 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
810 		}							\
811 	} else {							\
812 		if (cond2) {						\
813 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
814 		} else {						\
815 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
816 		}							\
817 	}
818 
819 kstat_t			*arc_ksp;
820 static arc_state_t	*arc_anon;
821 static arc_state_t	*arc_mru;
822 static arc_state_t	*arc_mru_ghost;
823 static arc_state_t	*arc_mfu;
824 static arc_state_t	*arc_mfu_ghost;
825 static arc_state_t	*arc_l2c_only;
826 
827 /*
828  * There are several ARC variables that are critical to export as kstats --
829  * but we don't want to have to grovel around in the kstat whenever we wish to
830  * manipulate them.  For these variables, we therefore define them to be in
831  * terms of the statistic variable.  This assures that we are not introducing
832  * the possibility of inconsistency by having shadow copies of the variables,
833  * while still allowing the code to be readable.
834  */
835 #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
836 #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
837 #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
838 #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
839 #define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
840 #define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
841 #define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
842 
843 /* compressed size of entire arc */
844 #define	arc_compressed_size	ARCSTAT(arcstat_compressed_size)
845 /* uncompressed size of entire arc */
846 #define	arc_uncompressed_size	ARCSTAT(arcstat_uncompressed_size)
847 /* number of bytes in the arc from arc_buf_t's */
848 #define	arc_overhead_size	ARCSTAT(arcstat_overhead_size)
849 
850 /*
851  * There are also some ARC variables that we want to export, but that are
852  * updated so often that having the canonical representation be the statistic
853  * variable causes a performance bottleneck. We want to use aggsum_t's for these
854  * instead, but still be able to export the kstat in the same way as before.
855  * The solution is to always use the aggsum version, except in the kstat update
856  * callback.
857  */
858 aggsum_t arc_size;
859 aggsum_t arc_meta_used;
860 aggsum_t astat_data_size;
861 aggsum_t astat_metadata_size;
862 aggsum_t astat_hdr_size;
863 aggsum_t astat_other_size;
864 aggsum_t astat_l2_hdr_size;
865 
866 static int		arc_no_grow;	/* Don't try to grow cache size */
867 static hrtime_t		arc_growtime;
868 static uint64_t		arc_tempreserve;
869 static uint64_t		arc_loaned_bytes;
870 
871 typedef struct arc_callback arc_callback_t;
872 
873 struct arc_callback {
874 	void			*acb_private;
875 	arc_done_func_t		*acb_done;
876 	arc_buf_t		*acb_buf;
877 	boolean_t		acb_compressed;
878 	zio_t			*acb_zio_dummy;
879 	arc_callback_t		*acb_next;
880 };
881 
882 typedef struct arc_write_callback arc_write_callback_t;
883 
884 struct arc_write_callback {
885 	void		*awcb_private;
886 	arc_done_func_t	*awcb_ready;
887 	arc_done_func_t	*awcb_children_ready;
888 	arc_done_func_t	*awcb_physdone;
889 	arc_done_func_t	*awcb_done;
890 	arc_buf_t	*awcb_buf;
891 };
892 
893 /*
894  * ARC buffers are separated into multiple structs as a memory saving measure:
895  *   - Common fields struct, always defined, and embedded within it:
896  *       - L2-only fields, always allocated but undefined when not in L2ARC
897  *       - L1-only fields, only allocated when in L1ARC
898  *
899  *           Buffer in L1                     Buffer only in L2
900  *    +------------------------+          +------------------------+
901  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
902  *    |                        |          |                        |
903  *    |                        |          |                        |
904  *    |                        |          |                        |
905  *    +------------------------+          +------------------------+
906  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
907  *    | (undefined if L1-only) |          |                        |
908  *    +------------------------+          +------------------------+
909  *    | l1arc_buf_hdr_t        |
910  *    |                        |
911  *    |                        |
912  *    |                        |
913  *    |                        |
914  *    +------------------------+
915  *
916  * Because it's possible for the L2ARC to become extremely large, we can wind
917  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
918  * is minimized by only allocating the fields necessary for an L1-cached buffer
919  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
920  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
921  * words in pointers. arc_hdr_realloc() is used to switch a header between
922  * these two allocation states.
923  */
924 typedef struct l1arc_buf_hdr {
925 	kmutex_t		b_freeze_lock;
926 	zio_cksum_t		*b_freeze_cksum;
927 #ifdef ZFS_DEBUG
928 	/*
929 	 * Used for debugging with kmem_flags - by allocating and freeing
930 	 * b_thawed when the buffer is thawed, we get a record of the stack
931 	 * trace that thawed it.
932 	 */
933 	void			*b_thawed;
934 #endif
935 
936 	arc_buf_t		*b_buf;
937 	uint32_t		b_bufcnt;
938 	/* for waiting on writes to complete */
939 	kcondvar_t		b_cv;
940 	uint8_t			b_byteswap;
941 
942 	/* protected by arc state mutex */
943 	arc_state_t		*b_state;
944 	multilist_node_t	b_arc_node;
945 
946 	/* updated atomically */
947 	clock_t			b_arc_access;
948 
949 	/* self protecting */
950 	zfs_refcount_t		b_refcnt;
951 
952 	arc_callback_t		*b_acb;
953 	abd_t			*b_pabd;
954 } l1arc_buf_hdr_t;
955 
956 typedef struct l2arc_dev l2arc_dev_t;
957 
958 typedef struct l2arc_buf_hdr {
959 	/* protected by arc_buf_hdr mutex */
960 	l2arc_dev_t		*b_dev;		/* L2ARC device */
961 	uint64_t		b_daddr;	/* disk address, offset byte */
962 
963 	list_node_t		b_l2node;
964 } l2arc_buf_hdr_t;
965 
966 struct arc_buf_hdr {
967 	/* protected by hash lock */
968 	dva_t			b_dva;
969 	uint64_t		b_birth;
970 
971 	arc_buf_contents_t	b_type;
972 	arc_buf_hdr_t		*b_hash_next;
973 	arc_flags_t		b_flags;
974 
975 	/*
976 	 * This field stores the size of the data buffer after
977 	 * compression, and is set in the arc's zio completion handlers.
978 	 * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
979 	 *
980 	 * While the block pointers can store up to 32MB in their psize
981 	 * field, we can only store up to 32MB minus 512B. This is due
982 	 * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
983 	 * a field of zeros represents 512B in the bp). We can't use a
984 	 * bias of 1 since we need to reserve a psize of zero, here, to
985 	 * represent holes and embedded blocks.
986 	 *
987 	 * This isn't a problem in practice, since the maximum size of a
988 	 * buffer is limited to 16MB, so we never need to store 32MB in
989 	 * this field. Even in the upstream illumos code base, the
990 	 * maximum size of a buffer is limited to 16MB.
991 	 */
992 	uint16_t		b_psize;
993 
994 	/*
995 	 * This field stores the size of the data buffer before
996 	 * compression, and cannot change once set. It is in units
997 	 * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
998 	 */
999 	uint16_t		b_lsize;	/* immutable */
1000 	uint64_t		b_spa;		/* immutable */
1001 
1002 	/* L2ARC fields. Undefined when not in L2ARC. */
1003 	l2arc_buf_hdr_t		b_l2hdr;
1004 	/* L1ARC fields. Undefined when in l2arc_only state */
1005 	l1arc_buf_hdr_t		b_l1hdr;
1006 };
1007 
1008 #define	GHOST_STATE(state)	\
1009 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
1010 	(state) == arc_l2c_only)
1011 
1012 #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1013 #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1014 #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1015 #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
1016 #define	HDR_COMPRESSION_ENABLED(hdr)	\
1017 	((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1018 
1019 #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
1020 #define	HDR_L2_READING(hdr)	\
1021 	(((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
1022 	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1023 #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1024 #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1025 #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1026 #define	HDR_SHARED_DATA(hdr)	((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1027 
1028 #define	HDR_ISTYPE_METADATA(hdr)	\
1029 	((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1030 #define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
1031 
1032 #define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1033 #define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1034 
1035 /* For storing compression mode in b_flags */
1036 #define	HDR_COMPRESS_OFFSET	(highbit64(ARC_FLAG_COMPRESS_0) - 1)
1037 
1038 #define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET((hdr)->b_flags, \
1039 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1040 #define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1041 	HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1042 
1043 #define	ARC_BUF_LAST(buf)	((buf)->b_next == NULL)
1044 #define	ARC_BUF_SHARED(buf)	((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1045 #define	ARC_BUF_COMPRESSED(buf)	((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1046 
1047 /*
1048  * Other sizes
1049  */
1050 
1051 #define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1052 #define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1053 
1054 /*
1055  * Hash table routines
1056  */
1057 
1058 #define	HT_LOCK_PAD	64
1059 
1060 struct ht_lock {
1061 	kmutex_t	ht_lock;
1062 #ifdef _KERNEL
1063 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1064 #endif
1065 };
1066 
1067 #define	BUF_LOCKS 256
1068 typedef struct buf_hash_table {
1069 	uint64_t ht_mask;
1070 	arc_buf_hdr_t **ht_table;
1071 	struct ht_lock ht_locks[BUF_LOCKS];
1072 } buf_hash_table_t;
1073 
1074 static buf_hash_table_t buf_hash_table;
1075 
1076 #define	BUF_HASH_INDEX(spa, dva, birth) \
1077 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1078 #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1079 #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1080 #define	HDR_LOCK(hdr) \
1081 	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1082 
1083 uint64_t zfs_crc64_table[256];
1084 
1085 /*
1086  * Level 2 ARC
1087  */
1088 
1089 #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
1090 #define	L2ARC_HEADROOM		2			/* num of writes */
1091 /*
1092  * If we discover during ARC scan any buffers to be compressed, we boost
1093  * our headroom for the next scanning cycle by this percentage multiple.
1094  */
1095 #define	L2ARC_HEADROOM_BOOST	200
1096 #define	L2ARC_FEED_SECS		1		/* caching interval secs */
1097 #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
1098 
1099 #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
1100 #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
1101 
1102 /* L2ARC Performance Tunables */
1103 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
1104 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
1105 uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
1106 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1107 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
1108 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
1109 boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
1110 boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
1111 boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
1112 
1113 /*
1114  * L2ARC Internals
1115  */
1116 struct l2arc_dev {
1117 	vdev_t			*l2ad_vdev;	/* vdev */
1118 	spa_t			*l2ad_spa;	/* spa */
1119 	uint64_t		l2ad_hand;	/* next write location */
1120 	uint64_t		l2ad_start;	/* first addr on device */
1121 	uint64_t		l2ad_end;	/* last addr on device */
1122 	boolean_t		l2ad_first;	/* first sweep through */
1123 	boolean_t		l2ad_writing;	/* currently writing */
1124 	kmutex_t		l2ad_mtx;	/* lock for buffer list */
1125 	list_t			l2ad_buflist;	/* buffer list */
1126 	list_node_t		l2ad_node;	/* device list node */
1127 	zfs_refcount_t		l2ad_alloc;	/* allocated bytes */
1128 };
1129 
1130 static list_t L2ARC_dev_list;			/* device list */
1131 static list_t *l2arc_dev_list;			/* device list pointer */
1132 static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1133 static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1134 static list_t L2ARC_free_on_write;		/* free after write buf list */
1135 static list_t *l2arc_free_on_write;		/* free after write list ptr */
1136 static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1137 static uint64_t l2arc_ndev;			/* number of devices */
1138 
1139 typedef struct l2arc_read_callback {
1140 	arc_buf_hdr_t		*l2rcb_hdr;		/* read header */
1141 	blkptr_t		l2rcb_bp;		/* original blkptr */
1142 	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1143 	int			l2rcb_flags;		/* original flags */
1144 	abd_t			*l2rcb_abd;		/* temporary buffer */
1145 } l2arc_read_callback_t;
1146 
1147 typedef struct l2arc_write_callback {
1148 	l2arc_dev_t	*l2wcb_dev;		/* device info */
1149 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1150 } l2arc_write_callback_t;
1151 
1152 typedef struct l2arc_data_free {
1153 	/* protected by l2arc_free_on_write_mtx */
1154 	abd_t		*l2df_abd;
1155 	size_t		l2df_size;
1156 	arc_buf_contents_t l2df_type;
1157 	list_node_t	l2df_list_node;
1158 } l2arc_data_free_t;
1159 
1160 static kmutex_t l2arc_feed_thr_lock;
1161 static kcondvar_t l2arc_feed_thr_cv;
1162 static uint8_t l2arc_thread_exit;
1163 
1164 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1165 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1166 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1167 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1168 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1169 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1170 static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1171 static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
1172 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1173 static boolean_t arc_is_overflowing();
1174 static void arc_buf_watch(arc_buf_t *);
1175 
1176 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1177 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1178 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1179 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1180 
1181 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1182 static void l2arc_read_done(zio_t *);
1183 
1184 
1185 /*
1186  * We use Cityhash for this. It's fast, and has good hash properties without
1187  * requiring any large static buffers.
1188  */
1189 static uint64_t
1190 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1191 {
1192 	return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1193 }
1194 
1195 #define	HDR_EMPTY(hdr)						\
1196 	((hdr)->b_dva.dva_word[0] == 0 &&			\
1197 	(hdr)->b_dva.dva_word[1] == 0)
1198 
1199 #define	HDR_EQUAL(spa, dva, birth, hdr)				\
1200 	((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1201 	((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1202 	((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1203 
1204 static void
1205 buf_discard_identity(arc_buf_hdr_t *hdr)
1206 {
1207 	hdr->b_dva.dva_word[0] = 0;
1208 	hdr->b_dva.dva_word[1] = 0;
1209 	hdr->b_birth = 0;
1210 }
1211 
1212 static arc_buf_hdr_t *
1213 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1214 {
1215 	const dva_t *dva = BP_IDENTITY(bp);
1216 	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1217 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1218 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1219 	arc_buf_hdr_t *hdr;
1220 
1221 	mutex_enter(hash_lock);
1222 	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1223 	    hdr = hdr->b_hash_next) {
1224 		if (HDR_EQUAL(spa, dva, birth, hdr)) {
1225 			*lockp = hash_lock;
1226 			return (hdr);
1227 		}
1228 	}
1229 	mutex_exit(hash_lock);
1230 	*lockp = NULL;
1231 	return (NULL);
1232 }
1233 
1234 /*
1235  * Insert an entry into the hash table.  If there is already an element
1236  * equal to elem in the hash table, then the already existing element
1237  * will be returned and the new element will not be inserted.
1238  * Otherwise returns NULL.
1239  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1240  */
1241 static arc_buf_hdr_t *
1242 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1243 {
1244 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1245 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1246 	arc_buf_hdr_t *fhdr;
1247 	uint32_t i;
1248 
1249 	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1250 	ASSERT(hdr->b_birth != 0);
1251 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
1252 
1253 	if (lockp != NULL) {
1254 		*lockp = hash_lock;
1255 		mutex_enter(hash_lock);
1256 	} else {
1257 		ASSERT(MUTEX_HELD(hash_lock));
1258 	}
1259 
1260 	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1261 	    fhdr = fhdr->b_hash_next, i++) {
1262 		if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1263 			return (fhdr);
1264 	}
1265 
1266 	hdr->b_hash_next = buf_hash_table.ht_table[idx];
1267 	buf_hash_table.ht_table[idx] = hdr;
1268 	arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1269 
1270 	/* collect some hash table performance data */
1271 	if (i > 0) {
1272 		ARCSTAT_BUMP(arcstat_hash_collisions);
1273 		if (i == 1)
1274 			ARCSTAT_BUMP(arcstat_hash_chains);
1275 
1276 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1277 	}
1278 
1279 	ARCSTAT_BUMP(arcstat_hash_elements);
1280 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1281 
1282 	return (NULL);
1283 }
1284 
1285 static void
1286 buf_hash_remove(arc_buf_hdr_t *hdr)
1287 {
1288 	arc_buf_hdr_t *fhdr, **hdrp;
1289 	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1290 
1291 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1292 	ASSERT(HDR_IN_HASH_TABLE(hdr));
1293 
1294 	hdrp = &buf_hash_table.ht_table[idx];
1295 	while ((fhdr = *hdrp) != hdr) {
1296 		ASSERT3P(fhdr, !=, NULL);
1297 		hdrp = &fhdr->b_hash_next;
1298 	}
1299 	*hdrp = hdr->b_hash_next;
1300 	hdr->b_hash_next = NULL;
1301 	arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1302 
1303 	/* collect some hash table performance data */
1304 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1305 
1306 	if (buf_hash_table.ht_table[idx] &&
1307 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1308 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1309 }
1310 
1311 /*
1312  * Global data structures and functions for the buf kmem cache.
1313  */
1314 static kmem_cache_t *hdr_full_cache;
1315 static kmem_cache_t *hdr_l2only_cache;
1316 static kmem_cache_t *buf_cache;
1317 
1318 static void
1319 buf_fini(void)
1320 {
1321 	int i;
1322 
1323 	kmem_free(buf_hash_table.ht_table,
1324 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1325 	for (i = 0; i < BUF_LOCKS; i++)
1326 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1327 	kmem_cache_destroy(hdr_full_cache);
1328 	kmem_cache_destroy(hdr_l2only_cache);
1329 	kmem_cache_destroy(buf_cache);
1330 }
1331 
1332 /*
1333  * Constructor callback - called when the cache is empty
1334  * and a new buf is requested.
1335  */
1336 /* ARGSUSED */
1337 static int
1338 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1339 {
1340 	arc_buf_hdr_t *hdr = vbuf;
1341 
1342 	bzero(hdr, HDR_FULL_SIZE);
1343 	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1344 	zfs_refcount_create(&hdr->b_l1hdr.b_refcnt);
1345 	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1346 	multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1347 	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1348 
1349 	return (0);
1350 }
1351 
1352 /* ARGSUSED */
1353 static int
1354 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1355 {
1356 	arc_buf_hdr_t *hdr = vbuf;
1357 
1358 	bzero(hdr, HDR_L2ONLY_SIZE);
1359 	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1360 
1361 	return (0);
1362 }
1363 
1364 /* ARGSUSED */
1365 static int
1366 buf_cons(void *vbuf, void *unused, int kmflag)
1367 {
1368 	arc_buf_t *buf = vbuf;
1369 
1370 	bzero(buf, sizeof (arc_buf_t));
1371 	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1372 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1373 
1374 	return (0);
1375 }
1376 
1377 /*
1378  * Destructor callback - called when a cached buf is
1379  * no longer required.
1380  */
1381 /* ARGSUSED */
1382 static void
1383 hdr_full_dest(void *vbuf, void *unused)
1384 {
1385 	arc_buf_hdr_t *hdr = vbuf;
1386 
1387 	ASSERT(HDR_EMPTY(hdr));
1388 	cv_destroy(&hdr->b_l1hdr.b_cv);
1389 	zfs_refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1390 	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1391 	ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1392 	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1393 }
1394 
1395 /* ARGSUSED */
1396 static void
1397 hdr_l2only_dest(void *vbuf, void *unused)
1398 {
1399 	arc_buf_hdr_t *hdr = vbuf;
1400 
1401 	ASSERT(HDR_EMPTY(hdr));
1402 	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1403 }
1404 
1405 /* ARGSUSED */
1406 static void
1407 buf_dest(void *vbuf, void *unused)
1408 {
1409 	arc_buf_t *buf = vbuf;
1410 
1411 	mutex_destroy(&buf->b_evict_lock);
1412 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1413 }
1414 
1415 /*
1416  * Reclaim callback -- invoked when memory is low.
1417  */
1418 /* ARGSUSED */
1419 static void
1420 hdr_recl(void *unused)
1421 {
1422 	dprintf("hdr_recl called\n");
1423 	/*
1424 	 * umem calls the reclaim func when we destroy the buf cache,
1425 	 * which is after we do arc_fini().
1426 	 */
1427 	if (arc_initialized)
1428 		zthr_wakeup(arc_reap_zthr);
1429 }
1430 
1431 static void
1432 buf_init(void)
1433 {
1434 	uint64_t *ct;
1435 	uint64_t hsize = 1ULL << 12;
1436 	int i, j;
1437 
1438 	/*
1439 	 * The hash table is big enough to fill all of physical memory
1440 	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1441 	 * By default, the table will take up
1442 	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1443 	 */
1444 	while (hsize * zfs_arc_average_blocksize < physmem * PAGESIZE)
1445 		hsize <<= 1;
1446 retry:
1447 	buf_hash_table.ht_mask = hsize - 1;
1448 	buf_hash_table.ht_table =
1449 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1450 	if (buf_hash_table.ht_table == NULL) {
1451 		ASSERT(hsize > (1ULL << 8));
1452 		hsize >>= 1;
1453 		goto retry;
1454 	}
1455 
1456 	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1457 	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1458 	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1459 	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1460 	    NULL, NULL, 0);
1461 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1462 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1463 
1464 	for (i = 0; i < 256; i++)
1465 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1466 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1467 
1468 	for (i = 0; i < BUF_LOCKS; i++) {
1469 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1470 		    NULL, MUTEX_DEFAULT, NULL);
1471 	}
1472 }
1473 
1474 /*
1475  * This is the size that the buf occupies in memory. If the buf is compressed,
1476  * it will correspond to the compressed size. You should use this method of
1477  * getting the buf size unless you explicitly need the logical size.
1478  */
1479 int32_t
1480 arc_buf_size(arc_buf_t *buf)
1481 {
1482 	return (ARC_BUF_COMPRESSED(buf) ?
1483 	    HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1484 }
1485 
1486 int32_t
1487 arc_buf_lsize(arc_buf_t *buf)
1488 {
1489 	return (HDR_GET_LSIZE(buf->b_hdr));
1490 }
1491 
1492 enum zio_compress
1493 arc_get_compression(arc_buf_t *buf)
1494 {
1495 	return (ARC_BUF_COMPRESSED(buf) ?
1496 	    HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1497 }
1498 
1499 #define	ARC_MINTIME	(hz>>4) /* 62 ms */
1500 
1501 static inline boolean_t
1502 arc_buf_is_shared(arc_buf_t *buf)
1503 {
1504 	boolean_t shared = (buf->b_data != NULL &&
1505 	    buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1506 	    abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1507 	    buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1508 	IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1509 	IMPLY(shared, ARC_BUF_SHARED(buf));
1510 	IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1511 
1512 	/*
1513 	 * It would be nice to assert arc_can_share() too, but the "hdr isn't
1514 	 * already being shared" requirement prevents us from doing that.
1515 	 */
1516 
1517 	return (shared);
1518 }
1519 
1520 /*
1521  * Free the checksum associated with this header. If there is no checksum, this
1522  * is a no-op.
1523  */
1524 static inline void
1525 arc_cksum_free(arc_buf_hdr_t *hdr)
1526 {
1527 	ASSERT(HDR_HAS_L1HDR(hdr));
1528 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1529 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1530 		kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1531 		hdr->b_l1hdr.b_freeze_cksum = NULL;
1532 	}
1533 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1534 }
1535 
1536 /*
1537  * Return true iff at least one of the bufs on hdr is not compressed.
1538  */
1539 static boolean_t
1540 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1541 {
1542 	for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1543 		if (!ARC_BUF_COMPRESSED(b)) {
1544 			return (B_TRUE);
1545 		}
1546 	}
1547 	return (B_FALSE);
1548 }
1549 
1550 /*
1551  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1552  * matches the checksum that is stored in the hdr. If there is no checksum,
1553  * or if the buf is compressed, this is a no-op.
1554  */
1555 static void
1556 arc_cksum_verify(arc_buf_t *buf)
1557 {
1558 	arc_buf_hdr_t *hdr = buf->b_hdr;
1559 	zio_cksum_t zc;
1560 
1561 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1562 		return;
1563 
1564 	if (ARC_BUF_COMPRESSED(buf)) {
1565 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1566 		    arc_hdr_has_uncompressed_buf(hdr));
1567 		return;
1568 	}
1569 
1570 	ASSERT(HDR_HAS_L1HDR(hdr));
1571 
1572 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1573 	if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1574 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1575 		return;
1576 	}
1577 
1578 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1579 	if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1580 		panic("buffer modified while frozen!");
1581 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1582 }
1583 
1584 static boolean_t
1585 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1586 {
1587 	enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1588 	boolean_t valid_cksum;
1589 
1590 	ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1591 	VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1592 
1593 	/*
1594 	 * We rely on the blkptr's checksum to determine if the block
1595 	 * is valid or not. When compressed arc is enabled, the l2arc
1596 	 * writes the block to the l2arc just as it appears in the pool.
1597 	 * This allows us to use the blkptr's checksum to validate the
1598 	 * data that we just read off of the l2arc without having to store
1599 	 * a separate checksum in the arc_buf_hdr_t. However, if compressed
1600 	 * arc is disabled, then the data written to the l2arc is always
1601 	 * uncompressed and won't match the block as it exists in the main
1602 	 * pool. When this is the case, we must first compress it if it is
1603 	 * compressed on the main pool before we can validate the checksum.
1604 	 */
1605 	if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1606 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1607 		uint64_t lsize = HDR_GET_LSIZE(hdr);
1608 		uint64_t csize;
1609 
1610 		abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
1611 		csize = zio_compress_data(compress, zio->io_abd,
1612 		    abd_to_buf(cdata), lsize);
1613 
1614 		ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1615 		if (csize < HDR_GET_PSIZE(hdr)) {
1616 			/*
1617 			 * Compressed blocks are always a multiple of the
1618 			 * smallest ashift in the pool. Ideally, we would
1619 			 * like to round up the csize to the next
1620 			 * spa_min_ashift but that value may have changed
1621 			 * since the block was last written. Instead,
1622 			 * we rely on the fact that the hdr's psize
1623 			 * was set to the psize of the block when it was
1624 			 * last written. We set the csize to that value
1625 			 * and zero out any part that should not contain
1626 			 * data.
1627 			 */
1628 			abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
1629 			csize = HDR_GET_PSIZE(hdr);
1630 		}
1631 		zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
1632 	}
1633 
1634 	/*
1635 	 * Block pointers always store the checksum for the logical data.
1636 	 * If the block pointer has the gang bit set, then the checksum
1637 	 * it represents is for the reconstituted data and not for an
1638 	 * individual gang member. The zio pipeline, however, must be able to
1639 	 * determine the checksum of each of the gang constituents so it
1640 	 * treats the checksum comparison differently than what we need
1641 	 * for l2arc blocks. This prevents us from using the
1642 	 * zio_checksum_error() interface directly. Instead we must call the
1643 	 * zio_checksum_error_impl() so that we can ensure the checksum is
1644 	 * generated using the correct checksum algorithm and accounts for the
1645 	 * logical I/O size and not just a gang fragment.
1646 	 */
1647 	valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
1648 	    BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
1649 	    zio->io_offset, NULL) == 0);
1650 	zio_pop_transforms(zio);
1651 	return (valid_cksum);
1652 }
1653 
1654 /*
1655  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
1656  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
1657  * isn't modified later on. If buf is compressed or there is already a checksum
1658  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
1659  */
1660 static void
1661 arc_cksum_compute(arc_buf_t *buf)
1662 {
1663 	arc_buf_hdr_t *hdr = buf->b_hdr;
1664 
1665 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1666 		return;
1667 
1668 	ASSERT(HDR_HAS_L1HDR(hdr));
1669 
1670 	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1671 	if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1672 		ASSERT(arc_hdr_has_uncompressed_buf(hdr));
1673 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1674 		return;
1675 	} else if (ARC_BUF_COMPRESSED(buf)) {
1676 		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1677 		return;
1678 	}
1679 
1680 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1681 	hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1682 	    KM_SLEEP);
1683 	fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
1684 	    hdr->b_l1hdr.b_freeze_cksum);
1685 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1686 	arc_buf_watch(buf);
1687 }
1688 
1689 #ifndef _KERNEL
1690 typedef struct procctl {
1691 	long cmd;
1692 	prwatch_t prwatch;
1693 } procctl_t;
1694 #endif
1695 
1696 /* ARGSUSED */
1697 static void
1698 arc_buf_unwatch(arc_buf_t *buf)
1699 {
1700 #ifndef _KERNEL
1701 	if (arc_watch) {
1702 		int result;
1703 		procctl_t ctl;
1704 		ctl.cmd = PCWATCH;
1705 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1706 		ctl.prwatch.pr_size = 0;
1707 		ctl.prwatch.pr_wflags = 0;
1708 		result = write(arc_procfd, &ctl, sizeof (ctl));
1709 		ASSERT3U(result, ==, sizeof (ctl));
1710 	}
1711 #endif
1712 }
1713 
1714 /* ARGSUSED */
1715 static void
1716 arc_buf_watch(arc_buf_t *buf)
1717 {
1718 #ifndef _KERNEL
1719 	if (arc_watch) {
1720 		int result;
1721 		procctl_t ctl;
1722 		ctl.cmd = PCWATCH;
1723 		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1724 		ctl.prwatch.pr_size = arc_buf_size(buf);
1725 		ctl.prwatch.pr_wflags = WA_WRITE;
1726 		result = write(arc_procfd, &ctl, sizeof (ctl));
1727 		ASSERT3U(result, ==, sizeof (ctl));
1728 	}
1729 #endif
1730 }
1731 
1732 static arc_buf_contents_t
1733 arc_buf_type(arc_buf_hdr_t *hdr)
1734 {
1735 	arc_buf_contents_t type;
1736 	if (HDR_ISTYPE_METADATA(hdr)) {
1737 		type = ARC_BUFC_METADATA;
1738 	} else {
1739 		type = ARC_BUFC_DATA;
1740 	}
1741 	VERIFY3U(hdr->b_type, ==, type);
1742 	return (type);
1743 }
1744 
1745 boolean_t
1746 arc_is_metadata(arc_buf_t *buf)
1747 {
1748 	return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
1749 }
1750 
1751 static uint32_t
1752 arc_bufc_to_flags(arc_buf_contents_t type)
1753 {
1754 	switch (type) {
1755 	case ARC_BUFC_DATA:
1756 		/* metadata field is 0 if buffer contains normal data */
1757 		return (0);
1758 	case ARC_BUFC_METADATA:
1759 		return (ARC_FLAG_BUFC_METADATA);
1760 	default:
1761 		break;
1762 	}
1763 	panic("undefined ARC buffer type!");
1764 	return ((uint32_t)-1);
1765 }
1766 
1767 void
1768 arc_buf_thaw(arc_buf_t *buf)
1769 {
1770 	arc_buf_hdr_t *hdr = buf->b_hdr;
1771 
1772 	ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
1773 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1774 
1775 	arc_cksum_verify(buf);
1776 
1777 	/*
1778 	 * Compressed buffers do not manipulate the b_freeze_cksum or
1779 	 * allocate b_thawed.
1780 	 */
1781 	if (ARC_BUF_COMPRESSED(buf)) {
1782 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1783 		    arc_hdr_has_uncompressed_buf(hdr));
1784 		return;
1785 	}
1786 
1787 	ASSERT(HDR_HAS_L1HDR(hdr));
1788 	arc_cksum_free(hdr);
1789 
1790 	mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1791 #ifdef ZFS_DEBUG
1792 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1793 		if (hdr->b_l1hdr.b_thawed != NULL)
1794 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
1795 		hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1796 	}
1797 #endif
1798 
1799 	mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1800 
1801 	arc_buf_unwatch(buf);
1802 }
1803 
1804 void
1805 arc_buf_freeze(arc_buf_t *buf)
1806 {
1807 	arc_buf_hdr_t *hdr = buf->b_hdr;
1808 	kmutex_t *hash_lock;
1809 
1810 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1811 		return;
1812 
1813 	if (ARC_BUF_COMPRESSED(buf)) {
1814 		ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1815 		    arc_hdr_has_uncompressed_buf(hdr));
1816 		return;
1817 	}
1818 
1819 	hash_lock = HDR_LOCK(hdr);
1820 	mutex_enter(hash_lock);
1821 
1822 	ASSERT(HDR_HAS_L1HDR(hdr));
1823 	ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
1824 	    hdr->b_l1hdr.b_state == arc_anon);
1825 	arc_cksum_compute(buf);
1826 	mutex_exit(hash_lock);
1827 }
1828 
1829 /*
1830  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
1831  * the following functions should be used to ensure that the flags are
1832  * updated in a thread-safe way. When manipulating the flags either
1833  * the hash_lock must be held or the hdr must be undiscoverable. This
1834  * ensures that we're not racing with any other threads when updating
1835  * the flags.
1836  */
1837 static inline void
1838 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1839 {
1840 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1841 	hdr->b_flags |= flags;
1842 }
1843 
1844 static inline void
1845 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
1846 {
1847 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1848 	hdr->b_flags &= ~flags;
1849 }
1850 
1851 /*
1852  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
1853  * done in a special way since we have to clear and set bits
1854  * at the same time. Consumers that wish to set the compression bits
1855  * must use this function to ensure that the flags are updated in
1856  * thread-safe manner.
1857  */
1858 static void
1859 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
1860 {
1861 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
1862 
1863 	/*
1864 	 * Holes and embedded blocks will always have a psize = 0 so
1865 	 * we ignore the compression of the blkptr and set the
1866 	 * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
1867 	 * Holes and embedded blocks remain anonymous so we don't
1868 	 * want to uncompress them. Mark them as uncompressed.
1869 	 */
1870 	if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
1871 		arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1872 		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
1873 		ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
1874 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1875 	} else {
1876 		arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
1877 		HDR_SET_COMPRESS(hdr, cmp);
1878 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
1879 		ASSERT(HDR_COMPRESSION_ENABLED(hdr));
1880 	}
1881 }
1882 
1883 /*
1884  * Looks for another buf on the same hdr which has the data decompressed, copies
1885  * from it, and returns true. If no such buf exists, returns false.
1886  */
1887 static boolean_t
1888 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
1889 {
1890 	arc_buf_hdr_t *hdr = buf->b_hdr;
1891 	boolean_t copied = B_FALSE;
1892 
1893 	ASSERT(HDR_HAS_L1HDR(hdr));
1894 	ASSERT3P(buf->b_data, !=, NULL);
1895 	ASSERT(!ARC_BUF_COMPRESSED(buf));
1896 
1897 	for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
1898 	    from = from->b_next) {
1899 		/* can't use our own data buffer */
1900 		if (from == buf) {
1901 			continue;
1902 		}
1903 
1904 		if (!ARC_BUF_COMPRESSED(from)) {
1905 			bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
1906 			copied = B_TRUE;
1907 			break;
1908 		}
1909 	}
1910 
1911 	/*
1912 	 * There were no decompressed bufs, so there should not be a
1913 	 * checksum on the hdr either.
1914 	 */
1915 	EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
1916 
1917 	return (copied);
1918 }
1919 
1920 /*
1921  * Given a buf that has a data buffer attached to it, this function will
1922  * efficiently fill the buf with data of the specified compression setting from
1923  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
1924  * are already sharing a data buf, no copy is performed.
1925  *
1926  * If the buf is marked as compressed but uncompressed data was requested, this
1927  * will allocate a new data buffer for the buf, remove that flag, and fill the
1928  * buf with uncompressed data. You can't request a compressed buf on a hdr with
1929  * uncompressed data, and (since we haven't added support for it yet) if you
1930  * want compressed data your buf must already be marked as compressed and have
1931  * the correct-sized data buffer.
1932  */
1933 static int
1934 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
1935 {
1936 	arc_buf_hdr_t *hdr = buf->b_hdr;
1937 	boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
1938 	dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
1939 
1940 	ASSERT3P(buf->b_data, !=, NULL);
1941 	IMPLY(compressed, hdr_compressed);
1942 	IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
1943 
1944 	if (hdr_compressed == compressed) {
1945 		if (!arc_buf_is_shared(buf)) {
1946 			abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
1947 			    arc_buf_size(buf));
1948 		}
1949 	} else {
1950 		ASSERT(hdr_compressed);
1951 		ASSERT(!compressed);
1952 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
1953 
1954 		/*
1955 		 * If the buf is sharing its data with the hdr, unlink it and
1956 		 * allocate a new data buffer for the buf.
1957 		 */
1958 		if (arc_buf_is_shared(buf)) {
1959 			ASSERT(ARC_BUF_COMPRESSED(buf));
1960 
1961 			/* We need to give the buf it's own b_data */
1962 			buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
1963 			buf->b_data =
1964 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
1965 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
1966 
1967 			/* Previously overhead was 0; just add new overhead */
1968 			ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
1969 		} else if (ARC_BUF_COMPRESSED(buf)) {
1970 			/* We need to reallocate the buf's b_data */
1971 			arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
1972 			    buf);
1973 			buf->b_data =
1974 			    arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
1975 
1976 			/* We increased the size of b_data; update overhead */
1977 			ARCSTAT_INCR(arcstat_overhead_size,
1978 			    HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
1979 		}
1980 
1981 		/*
1982 		 * Regardless of the buf's previous compression settings, it
1983 		 * should not be compressed at the end of this function.
1984 		 */
1985 		buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
1986 
1987 		/*
1988 		 * Try copying the data from another buf which already has a
1989 		 * decompressed version. If that's not possible, it's time to
1990 		 * bite the bullet and decompress the data from the hdr.
1991 		 */
1992 		if (arc_buf_try_copy_decompressed_data(buf)) {
1993 			/* Skip byteswapping and checksumming (already done) */
1994 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
1995 			return (0);
1996 		} else {
1997 			int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
1998 			    hdr->b_l1hdr.b_pabd, buf->b_data,
1999 			    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2000 
2001 			/*
2002 			 * Absent hardware errors or software bugs, this should
2003 			 * be impossible, but log it anyway so we can debug it.
2004 			 */
2005 			if (error != 0) {
2006 				zfs_dbgmsg(
2007 				    "hdr %p, compress %d, psize %d, lsize %d",
2008 				    hdr, HDR_GET_COMPRESS(hdr),
2009 				    HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2010 				return (SET_ERROR(EIO));
2011 			}
2012 		}
2013 	}
2014 
2015 	/* Byteswap the buf's data if necessary */
2016 	if (bswap != DMU_BSWAP_NUMFUNCS) {
2017 		ASSERT(!HDR_SHARED_DATA(hdr));
2018 		ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2019 		dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2020 	}
2021 
2022 	/* Compute the hdr's checksum if necessary */
2023 	arc_cksum_compute(buf);
2024 
2025 	return (0);
2026 }
2027 
2028 int
2029 arc_decompress(arc_buf_t *buf)
2030 {
2031 	return (arc_buf_fill(buf, B_FALSE));
2032 }
2033 
2034 /*
2035  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2036  */
2037 static uint64_t
2038 arc_hdr_size(arc_buf_hdr_t *hdr)
2039 {
2040 	uint64_t size;
2041 
2042 	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2043 	    HDR_GET_PSIZE(hdr) > 0) {
2044 		size = HDR_GET_PSIZE(hdr);
2045 	} else {
2046 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2047 		size = HDR_GET_LSIZE(hdr);
2048 	}
2049 	return (size);
2050 }
2051 
2052 /*
2053  * Increment the amount of evictable space in the arc_state_t's refcount.
2054  * We account for the space used by the hdr and the arc buf individually
2055  * so that we can add and remove them from the refcount individually.
2056  */
2057 static void
2058 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2059 {
2060 	arc_buf_contents_t type = arc_buf_type(hdr);
2061 
2062 	ASSERT(HDR_HAS_L1HDR(hdr));
2063 
2064 	if (GHOST_STATE(state)) {
2065 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2066 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2067 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2068 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2069 		    HDR_GET_LSIZE(hdr), hdr);
2070 		return;
2071 	}
2072 
2073 	ASSERT(!GHOST_STATE(state));
2074 	if (hdr->b_l1hdr.b_pabd != NULL) {
2075 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2076 		    arc_hdr_size(hdr), hdr);
2077 	}
2078 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2079 	    buf = buf->b_next) {
2080 		if (arc_buf_is_shared(buf))
2081 			continue;
2082 		(void) zfs_refcount_add_many(&state->arcs_esize[type],
2083 		    arc_buf_size(buf), buf);
2084 	}
2085 }
2086 
2087 /*
2088  * Decrement the amount of evictable space in the arc_state_t's refcount.
2089  * We account for the space used by the hdr and the arc buf individually
2090  * so that we can add and remove them from the refcount individually.
2091  */
2092 static void
2093 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2094 {
2095 	arc_buf_contents_t type = arc_buf_type(hdr);
2096 
2097 	ASSERT(HDR_HAS_L1HDR(hdr));
2098 
2099 	if (GHOST_STATE(state)) {
2100 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2101 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2102 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2103 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2104 		    HDR_GET_LSIZE(hdr), hdr);
2105 		return;
2106 	}
2107 
2108 	ASSERT(!GHOST_STATE(state));
2109 	if (hdr->b_l1hdr.b_pabd != NULL) {
2110 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2111 		    arc_hdr_size(hdr), hdr);
2112 	}
2113 	for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2114 	    buf = buf->b_next) {
2115 		if (arc_buf_is_shared(buf))
2116 			continue;
2117 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2118 		    arc_buf_size(buf), buf);
2119 	}
2120 }
2121 
2122 /*
2123  * Add a reference to this hdr indicating that someone is actively
2124  * referencing that memory. When the refcount transitions from 0 to 1,
2125  * we remove it from the respective arc_state_t list to indicate that
2126  * it is not evictable.
2127  */
2128 static void
2129 add_reference(arc_buf_hdr_t *hdr, void *tag)
2130 {
2131 	ASSERT(HDR_HAS_L1HDR(hdr));
2132 	if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2133 		ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2134 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2135 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2136 	}
2137 
2138 	arc_state_t *state = hdr->b_l1hdr.b_state;
2139 
2140 	if ((zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2141 	    (state != arc_anon)) {
2142 		/* We don't use the L2-only state list. */
2143 		if (state != arc_l2c_only) {
2144 			multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2145 			    hdr);
2146 			arc_evictable_space_decrement(hdr, state);
2147 		}
2148 		/* remove the prefetch flag if we get a reference */
2149 		arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2150 	}
2151 }
2152 
2153 /*
2154  * Remove a reference from this hdr. When the reference transitions from
2155  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2156  * list making it eligible for eviction.
2157  */
2158 static int
2159 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2160 {
2161 	int cnt;
2162 	arc_state_t *state = hdr->b_l1hdr.b_state;
2163 
2164 	ASSERT(HDR_HAS_L1HDR(hdr));
2165 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2166 	ASSERT(!GHOST_STATE(state));
2167 
2168 	/*
2169 	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
2170 	 * check to prevent usage of the arc_l2c_only list.
2171 	 */
2172 	if (((cnt = zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2173 	    (state != arc_anon)) {
2174 		multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2175 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2176 		arc_evictable_space_increment(hdr, state);
2177 	}
2178 	return (cnt);
2179 }
2180 
2181 /*
2182  * Move the supplied buffer to the indicated state. The hash lock
2183  * for the buffer must be held by the caller.
2184  */
2185 static void
2186 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2187     kmutex_t *hash_lock)
2188 {
2189 	arc_state_t *old_state;
2190 	int64_t refcnt;
2191 	uint32_t bufcnt;
2192 	boolean_t update_old, update_new;
2193 	arc_buf_contents_t buftype = arc_buf_type(hdr);
2194 
2195 	/*
2196 	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2197 	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
2198 	 * L1 hdr doesn't always exist when we change state to arc_anon before
2199 	 * destroying a header, in which case reallocating to add the L1 hdr is
2200 	 * pointless.
2201 	 */
2202 	if (HDR_HAS_L1HDR(hdr)) {
2203 		old_state = hdr->b_l1hdr.b_state;
2204 		refcnt = zfs_refcount_count(&hdr->b_l1hdr.b_refcnt);
2205 		bufcnt = hdr->b_l1hdr.b_bufcnt;
2206 		update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
2207 	} else {
2208 		old_state = arc_l2c_only;
2209 		refcnt = 0;
2210 		bufcnt = 0;
2211 		update_old = B_FALSE;
2212 	}
2213 	update_new = update_old;
2214 
2215 	ASSERT(MUTEX_HELD(hash_lock));
2216 	ASSERT3P(new_state, !=, old_state);
2217 	ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2218 	ASSERT(old_state != arc_anon || bufcnt <= 1);
2219 
2220 	/*
2221 	 * If this buffer is evictable, transfer it from the
2222 	 * old state list to the new state list.
2223 	 */
2224 	if (refcnt == 0) {
2225 		if (old_state != arc_anon && old_state != arc_l2c_only) {
2226 			ASSERT(HDR_HAS_L1HDR(hdr));
2227 			multilist_remove(old_state->arcs_list[buftype], hdr);
2228 
2229 			if (GHOST_STATE(old_state)) {
2230 				ASSERT0(bufcnt);
2231 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2232 				update_old = B_TRUE;
2233 			}
2234 			arc_evictable_space_decrement(hdr, old_state);
2235 		}
2236 		if (new_state != arc_anon && new_state != arc_l2c_only) {
2237 
2238 			/*
2239 			 * An L1 header always exists here, since if we're
2240 			 * moving to some L1-cached state (i.e. not l2c_only or
2241 			 * anonymous), we realloc the header to add an L1hdr
2242 			 * beforehand.
2243 			 */
2244 			ASSERT(HDR_HAS_L1HDR(hdr));
2245 			multilist_insert(new_state->arcs_list[buftype], hdr);
2246 
2247 			if (GHOST_STATE(new_state)) {
2248 				ASSERT0(bufcnt);
2249 				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2250 				update_new = B_TRUE;
2251 			}
2252 			arc_evictable_space_increment(hdr, new_state);
2253 		}
2254 	}
2255 
2256 	ASSERT(!HDR_EMPTY(hdr));
2257 	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2258 		buf_hash_remove(hdr);
2259 
2260 	/* adjust state sizes (ignore arc_l2c_only) */
2261 
2262 	if (update_new && new_state != arc_l2c_only) {
2263 		ASSERT(HDR_HAS_L1HDR(hdr));
2264 		if (GHOST_STATE(new_state)) {
2265 			ASSERT0(bufcnt);
2266 
2267 			/*
2268 			 * When moving a header to a ghost state, we first
2269 			 * remove all arc buffers. Thus, we'll have a
2270 			 * bufcnt of zero, and no arc buffer to use for
2271 			 * the reference. As a result, we use the arc
2272 			 * header pointer for the reference.
2273 			 */
2274 			(void) zfs_refcount_add_many(&new_state->arcs_size,
2275 			    HDR_GET_LSIZE(hdr), hdr);
2276 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2277 		} else {
2278 			uint32_t buffers = 0;
2279 
2280 			/*
2281 			 * Each individual buffer holds a unique reference,
2282 			 * thus we must remove each of these references one
2283 			 * at a time.
2284 			 */
2285 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2286 			    buf = buf->b_next) {
2287 				ASSERT3U(bufcnt, !=, 0);
2288 				buffers++;
2289 
2290 				/*
2291 				 * When the arc_buf_t is sharing the data
2292 				 * block with the hdr, the owner of the
2293 				 * reference belongs to the hdr. Only
2294 				 * add to the refcount if the arc_buf_t is
2295 				 * not shared.
2296 				 */
2297 				if (arc_buf_is_shared(buf))
2298 					continue;
2299 
2300 				(void) zfs_refcount_add_many(
2301 				    &new_state->arcs_size,
2302 				    arc_buf_size(buf), buf);
2303 			}
2304 			ASSERT3U(bufcnt, ==, buffers);
2305 
2306 			if (hdr->b_l1hdr.b_pabd != NULL) {
2307 				(void) zfs_refcount_add_many(
2308 				    &new_state->arcs_size,
2309 				    arc_hdr_size(hdr), hdr);
2310 			} else {
2311 				ASSERT(GHOST_STATE(old_state));
2312 			}
2313 		}
2314 	}
2315 
2316 	if (update_old && old_state != arc_l2c_only) {
2317 		ASSERT(HDR_HAS_L1HDR(hdr));
2318 		if (GHOST_STATE(old_state)) {
2319 			ASSERT0(bufcnt);
2320 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2321 
2322 			/*
2323 			 * When moving a header off of a ghost state,
2324 			 * the header will not contain any arc buffers.
2325 			 * We use the arc header pointer for the reference
2326 			 * which is exactly what we did when we put the
2327 			 * header on the ghost state.
2328 			 */
2329 
2330 			(void) zfs_refcount_remove_many(&old_state->arcs_size,
2331 			    HDR_GET_LSIZE(hdr), hdr);
2332 		} else {
2333 			uint32_t buffers = 0;
2334 
2335 			/*
2336 			 * Each individual buffer holds a unique reference,
2337 			 * thus we must remove each of these references one
2338 			 * at a time.
2339 			 */
2340 			for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2341 			    buf = buf->b_next) {
2342 				ASSERT3U(bufcnt, !=, 0);
2343 				buffers++;
2344 
2345 				/*
2346 				 * When the arc_buf_t is sharing the data
2347 				 * block with the hdr, the owner of the
2348 				 * reference belongs to the hdr. Only
2349 				 * add to the refcount if the arc_buf_t is
2350 				 * not shared.
2351 				 */
2352 				if (arc_buf_is_shared(buf))
2353 					continue;
2354 
2355 				(void) zfs_refcount_remove_many(
2356 				    &old_state->arcs_size, arc_buf_size(buf),
2357 				    buf);
2358 			}
2359 			ASSERT3U(bufcnt, ==, buffers);
2360 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2361 			(void) zfs_refcount_remove_many(
2362 			    &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2363 		}
2364 	}
2365 
2366 	if (HDR_HAS_L1HDR(hdr))
2367 		hdr->b_l1hdr.b_state = new_state;
2368 
2369 	/*
2370 	 * L2 headers should never be on the L2 state list since they don't
2371 	 * have L1 headers allocated.
2372 	 */
2373 	ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2374 	    multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2375 }
2376 
2377 void
2378 arc_space_consume(uint64_t space, arc_space_type_t type)
2379 {
2380 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2381 
2382 	switch (type) {
2383 	case ARC_SPACE_DATA:
2384 		aggsum_add(&astat_data_size, space);
2385 		break;
2386 	case ARC_SPACE_META:
2387 		aggsum_add(&astat_metadata_size, space);
2388 		break;
2389 	case ARC_SPACE_OTHER:
2390 		aggsum_add(&astat_other_size, space);
2391 		break;
2392 	case ARC_SPACE_HDRS:
2393 		aggsum_add(&astat_hdr_size, space);
2394 		break;
2395 	case ARC_SPACE_L2HDRS:
2396 		aggsum_add(&astat_l2_hdr_size, space);
2397 		break;
2398 	}
2399 
2400 	if (type != ARC_SPACE_DATA)
2401 		aggsum_add(&arc_meta_used, space);
2402 
2403 	aggsum_add(&arc_size, space);
2404 }
2405 
2406 void
2407 arc_space_return(uint64_t space, arc_space_type_t type)
2408 {
2409 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2410 
2411 	switch (type) {
2412 	case ARC_SPACE_DATA:
2413 		aggsum_add(&astat_data_size, -space);
2414 		break;
2415 	case ARC_SPACE_META:
2416 		aggsum_add(&astat_metadata_size, -space);
2417 		break;
2418 	case ARC_SPACE_OTHER:
2419 		aggsum_add(&astat_other_size, -space);
2420 		break;
2421 	case ARC_SPACE_HDRS:
2422 		aggsum_add(&astat_hdr_size, -space);
2423 		break;
2424 	case ARC_SPACE_L2HDRS:
2425 		aggsum_add(&astat_l2_hdr_size, -space);
2426 		break;
2427 	}
2428 
2429 	if (type != ARC_SPACE_DATA) {
2430 		ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
2431 		/*
2432 		 * We use the upper bound here rather than the precise value
2433 		 * because the arc_meta_max value doesn't need to be
2434 		 * precise. It's only consumed by humans via arcstats.
2435 		 */
2436 		if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
2437 			arc_meta_max = aggsum_upper_bound(&arc_meta_used);
2438 		aggsum_add(&arc_meta_used, -space);
2439 	}
2440 
2441 	ASSERT(aggsum_compare(&arc_size, space) >= 0);
2442 	aggsum_add(&arc_size, -space);
2443 }
2444 
2445 /*
2446  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2447  * with the hdr's b_pabd.
2448  */
2449 static boolean_t
2450 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2451 {
2452 	/*
2453 	 * The criteria for sharing a hdr's data are:
2454 	 * 1. the hdr's compression matches the buf's compression
2455 	 * 2. the hdr doesn't need to be byteswapped
2456 	 * 3. the hdr isn't already being shared
2457 	 * 4. the buf is either compressed or it is the last buf in the hdr list
2458 	 *
2459 	 * Criterion #4 maintains the invariant that shared uncompressed
2460 	 * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2461 	 * might ask, "if a compressed buf is allocated first, won't that be the
2462 	 * last thing in the list?", but in that case it's impossible to create
2463 	 * a shared uncompressed buf anyway (because the hdr must be compressed
2464 	 * to have the compressed buf). You might also think that #3 is
2465 	 * sufficient to make this guarantee, however it's possible
2466 	 * (specifically in the rare L2ARC write race mentioned in
2467 	 * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2468 	 * is sharable, but wasn't at the time of its allocation. Rather than
2469 	 * allow a new shared uncompressed buf to be created and then shuffle
2470 	 * the list around to make it the last element, this simply disallows
2471 	 * sharing if the new buf isn't the first to be added.
2472 	 */
2473 	ASSERT3P(buf->b_hdr, ==, hdr);
2474 	boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2475 	boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2476 	return (buf_compressed == hdr_compressed &&
2477 	    hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2478 	    !HDR_SHARED_DATA(hdr) &&
2479 	    (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2480 }
2481 
2482 /*
2483  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2484  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2485  * copy was made successfully, or an error code otherwise.
2486  */
2487 static int
2488 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2489     boolean_t fill, arc_buf_t **ret)
2490 {
2491 	arc_buf_t *buf;
2492 
2493 	ASSERT(HDR_HAS_L1HDR(hdr));
2494 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2495 	VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2496 	    hdr->b_type == ARC_BUFC_METADATA);
2497 	ASSERT3P(ret, !=, NULL);
2498 	ASSERT3P(*ret, ==, NULL);
2499 
2500 	buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2501 	buf->b_hdr = hdr;
2502 	buf->b_data = NULL;
2503 	buf->b_next = hdr->b_l1hdr.b_buf;
2504 	buf->b_flags = 0;
2505 
2506 	add_reference(hdr, tag);
2507 
2508 	/*
2509 	 * We're about to change the hdr's b_flags. We must either
2510 	 * hold the hash_lock or be undiscoverable.
2511 	 */
2512 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2513 
2514 	/*
2515 	 * Only honor requests for compressed bufs if the hdr is actually
2516 	 * compressed.
2517 	 */
2518 	if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2519 		buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2520 
2521 	/*
2522 	 * If the hdr's data can be shared then we share the data buffer and
2523 	 * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2524 	 * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2525 	 * buffer to store the buf's data.
2526 	 *
2527 	 * There are two additional restrictions here because we're sharing
2528 	 * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2529 	 * actively involved in an L2ARC write, because if this buf is used by
2530 	 * an arc_write() then the hdr's data buffer will be released when the
2531 	 * write completes, even though the L2ARC write might still be using it.
2532 	 * Second, the hdr's ABD must be linear so that the buf's user doesn't
2533 	 * need to be ABD-aware.
2534 	 */
2535 	boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2536 	    abd_is_linear(hdr->b_l1hdr.b_pabd);
2537 
2538 	/* Set up b_data and sharing */
2539 	if (can_share) {
2540 		buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2541 		buf->b_flags |= ARC_BUF_FLAG_SHARED;
2542 		arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2543 	} else {
2544 		buf->b_data =
2545 		    arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2546 		ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2547 	}
2548 	VERIFY3P(buf->b_data, !=, NULL);
2549 
2550 	hdr->b_l1hdr.b_buf = buf;
2551 	hdr->b_l1hdr.b_bufcnt += 1;
2552 
2553 	/*
2554 	 * If the user wants the data from the hdr, we need to either copy or
2555 	 * decompress the data.
2556 	 */
2557 	if (fill) {
2558 		return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
2559 	}
2560 
2561 	return (0);
2562 }
2563 
2564 static char *arc_onloan_tag = "onloan";
2565 
2566 static inline void
2567 arc_loaned_bytes_update(int64_t delta)
2568 {
2569 	atomic_add_64(&arc_loaned_bytes, delta);
2570 
2571 	/* assert that it did not wrap around */
2572 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
2573 }
2574 
2575 /*
2576  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2577  * flight data by arc_tempreserve_space() until they are "returned". Loaned
2578  * buffers must be returned to the arc before they can be used by the DMU or
2579  * freed.
2580  */
2581 arc_buf_t *
2582 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
2583 {
2584 	arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
2585 	    is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
2586 
2587 	arc_loaned_bytes_update(arc_buf_size(buf));
2588 
2589 	return (buf);
2590 }
2591 
2592 arc_buf_t *
2593 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
2594     enum zio_compress compression_type)
2595 {
2596 	arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
2597 	    psize, lsize, compression_type);
2598 
2599 	arc_loaned_bytes_update(arc_buf_size(buf));
2600 
2601 	return (buf);
2602 }
2603 
2604 
2605 /*
2606  * Return a loaned arc buffer to the arc.
2607  */
2608 void
2609 arc_return_buf(arc_buf_t *buf, void *tag)
2610 {
2611 	arc_buf_hdr_t *hdr = buf->b_hdr;
2612 
2613 	ASSERT3P(buf->b_data, !=, NULL);
2614 	ASSERT(HDR_HAS_L1HDR(hdr));
2615 	(void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2616 	(void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2617 
2618 	arc_loaned_bytes_update(-arc_buf_size(buf));
2619 }
2620 
2621 /* Detach an arc_buf from a dbuf (tag) */
2622 void
2623 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2624 {
2625 	arc_buf_hdr_t *hdr = buf->b_hdr;
2626 
2627 	ASSERT3P(buf->b_data, !=, NULL);
2628 	ASSERT(HDR_HAS_L1HDR(hdr));
2629 	(void) zfs_refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2630 	(void) zfs_refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2631 
2632 	arc_loaned_bytes_update(arc_buf_size(buf));
2633 }
2634 
2635 static void
2636 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
2637 {
2638 	l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
2639 
2640 	df->l2df_abd = abd;
2641 	df->l2df_size = size;
2642 	df->l2df_type = type;
2643 	mutex_enter(&l2arc_free_on_write_mtx);
2644 	list_insert_head(l2arc_free_on_write, df);
2645 	mutex_exit(&l2arc_free_on_write_mtx);
2646 }
2647 
2648 static void
2649 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
2650 {
2651 	arc_state_t *state = hdr->b_l1hdr.b_state;
2652 	arc_buf_contents_t type = arc_buf_type(hdr);
2653 	uint64_t size = arc_hdr_size(hdr);
2654 
2655 	/* protected by hash lock, if in the hash table */
2656 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
2657 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2658 		ASSERT(state != arc_anon && state != arc_l2c_only);
2659 
2660 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
2661 		    size, hdr);
2662 	}
2663 	(void) zfs_refcount_remove_many(&state->arcs_size, size, hdr);
2664 	if (type == ARC_BUFC_METADATA) {
2665 		arc_space_return(size, ARC_SPACE_META);
2666 	} else {
2667 		ASSERT(type == ARC_BUFC_DATA);
2668 		arc_space_return(size, ARC_SPACE_DATA);
2669 	}
2670 
2671 	l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
2672 }
2673 
2674 /*
2675  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
2676  * data buffer, we transfer the refcount ownership to the hdr and update
2677  * the appropriate kstats.
2678  */
2679 static void
2680 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2681 {
2682 	arc_state_t *state = hdr->b_l1hdr.b_state;
2683 
2684 	ASSERT(arc_can_share(hdr, buf));
2685 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2686 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2687 
2688 	/*
2689 	 * Start sharing the data buffer. We transfer the
2690 	 * refcount ownership to the hdr since it always owns
2691 	 * the refcount whenever an arc_buf_t is shared.
2692 	 */
2693 	zfs_refcount_transfer_ownership(&state->arcs_size, buf, hdr);
2694 	hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
2695 	abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
2696 	    HDR_ISTYPE_METADATA(hdr));
2697 	arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2698 	buf->b_flags |= ARC_BUF_FLAG_SHARED;
2699 
2700 	/*
2701 	 * Since we've transferred ownership to the hdr we need
2702 	 * to increment its compressed and uncompressed kstats and
2703 	 * decrement the overhead size.
2704 	 */
2705 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2706 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2707 	ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
2708 }
2709 
2710 static void
2711 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2712 {
2713 	arc_state_t *state = hdr->b_l1hdr.b_state;
2714 
2715 	ASSERT(arc_buf_is_shared(buf));
2716 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2717 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2718 
2719 	/*
2720 	 * We are no longer sharing this buffer so we need
2721 	 * to transfer its ownership to the rightful owner.
2722 	 */
2723 	zfs_refcount_transfer_ownership(&state->arcs_size, hdr, buf);
2724 	arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2725 	abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
2726 	abd_put(hdr->b_l1hdr.b_pabd);
2727 	hdr->b_l1hdr.b_pabd = NULL;
2728 	buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2729 
2730 	/*
2731 	 * Since the buffer is no longer shared between
2732 	 * the arc buf and the hdr, count it as overhead.
2733 	 */
2734 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2735 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2736 	ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2737 }
2738 
2739 /*
2740  * Remove an arc_buf_t from the hdr's buf list and return the last
2741  * arc_buf_t on the list. If no buffers remain on the list then return
2742  * NULL.
2743  */
2744 static arc_buf_t *
2745 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2746 {
2747 	ASSERT(HDR_HAS_L1HDR(hdr));
2748 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2749 
2750 	arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
2751 	arc_buf_t *lastbuf = NULL;
2752 
2753 	/*
2754 	 * Remove the buf from the hdr list and locate the last
2755 	 * remaining buffer on the list.
2756 	 */
2757 	while (*bufp != NULL) {
2758 		if (*bufp == buf)
2759 			*bufp = buf->b_next;
2760 
2761 		/*
2762 		 * If we've removed a buffer in the middle of
2763 		 * the list then update the lastbuf and update
2764 		 * bufp.
2765 		 */
2766 		if (*bufp != NULL) {
2767 			lastbuf = *bufp;
2768 			bufp = &(*bufp)->b_next;
2769 		}
2770 	}
2771 	buf->b_next = NULL;
2772 	ASSERT3P(lastbuf, !=, buf);
2773 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
2774 	IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
2775 	IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
2776 
2777 	return (lastbuf);
2778 }
2779 
2780 /*
2781  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
2782  * list and free it.
2783  */
2784 static void
2785 arc_buf_destroy_impl(arc_buf_t *buf)
2786 {
2787 	arc_buf_hdr_t *hdr = buf->b_hdr;
2788 
2789 	/*
2790 	 * Free up the data associated with the buf but only if we're not
2791 	 * sharing this with the hdr. If we are sharing it with the hdr, the
2792 	 * hdr is responsible for doing the free.
2793 	 */
2794 	if (buf->b_data != NULL) {
2795 		/*
2796 		 * We're about to change the hdr's b_flags. We must either
2797 		 * hold the hash_lock or be undiscoverable.
2798 		 */
2799 		ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2800 
2801 		arc_cksum_verify(buf);
2802 		arc_buf_unwatch(buf);
2803 
2804 		if (arc_buf_is_shared(buf)) {
2805 			arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2806 		} else {
2807 			uint64_t size = arc_buf_size(buf);
2808 			arc_free_data_buf(hdr, buf->b_data, size, buf);
2809 			ARCSTAT_INCR(arcstat_overhead_size, -size);
2810 		}
2811 		buf->b_data = NULL;
2812 
2813 		ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
2814 		hdr->b_l1hdr.b_bufcnt -= 1;
2815 	}
2816 
2817 	arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
2818 
2819 	if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
2820 		/*
2821 		 * If the current arc_buf_t is sharing its data buffer with the
2822 		 * hdr, then reassign the hdr's b_pabd to share it with the new
2823 		 * buffer at the end of the list. The shared buffer is always
2824 		 * the last one on the hdr's buffer list.
2825 		 *
2826 		 * There is an equivalent case for compressed bufs, but since
2827 		 * they aren't guaranteed to be the last buf in the list and
2828 		 * that is an exceedingly rare case, we just allow that space be
2829 		 * wasted temporarily.
2830 		 */
2831 		if (lastbuf != NULL) {
2832 			/* Only one buf can be shared at once */
2833 			VERIFY(!arc_buf_is_shared(lastbuf));
2834 			/* hdr is uncompressed so can't have compressed buf */
2835 			VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
2836 
2837 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2838 			arc_hdr_free_pabd(hdr);
2839 
2840 			/*
2841 			 * We must setup a new shared block between the
2842 			 * last buffer and the hdr. The data would have
2843 			 * been allocated by the arc buf so we need to transfer
2844 			 * ownership to the hdr since it's now being shared.
2845 			 */
2846 			arc_share_buf(hdr, lastbuf);
2847 		}
2848 	} else if (HDR_SHARED_DATA(hdr)) {
2849 		/*
2850 		 * Uncompressed shared buffers are always at the end
2851 		 * of the list. Compressed buffers don't have the
2852 		 * same requirements. This makes it hard to
2853 		 * simply assert that the lastbuf is shared so
2854 		 * we rely on the hdr's compression flags to determine
2855 		 * if we have a compressed, shared buffer.
2856 		 */
2857 		ASSERT3P(lastbuf, !=, NULL);
2858 		ASSERT(arc_buf_is_shared(lastbuf) ||
2859 		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2860 	}
2861 
2862 	/*
2863 	 * Free the checksum if we're removing the last uncompressed buf from
2864 	 * this hdr.
2865 	 */
2866 	if (!arc_hdr_has_uncompressed_buf(hdr)) {
2867 		arc_cksum_free(hdr);
2868 	}
2869 
2870 	/* clean up the buf */
2871 	buf->b_hdr = NULL;
2872 	kmem_cache_free(buf_cache, buf);
2873 }
2874 
2875 static void
2876 arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
2877 {
2878 	ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2879 	ASSERT(HDR_HAS_L1HDR(hdr));
2880 	ASSERT(!HDR_SHARED_DATA(hdr));
2881 
2882 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2883 	hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
2884 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2885 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2886 
2887 	ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
2888 	ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
2889 }
2890 
2891 static void
2892 arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
2893 {
2894 	ASSERT(HDR_HAS_L1HDR(hdr));
2895 	ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2896 
2897 	/*
2898 	 * If the hdr is currently being written to the l2arc then
2899 	 * we defer freeing the data by adding it to the l2arc_free_on_write
2900 	 * list. The l2arc will free the data once it's finished
2901 	 * writing it to the l2arc device.
2902 	 */
2903 	if (HDR_L2_WRITING(hdr)) {
2904 		arc_hdr_free_on_write(hdr);
2905 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2906 	} else {
2907 		arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
2908 		    arc_hdr_size(hdr), hdr);
2909 	}
2910 	hdr->b_l1hdr.b_pabd = NULL;
2911 	hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
2912 
2913 	ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
2914 	ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
2915 }
2916 
2917 static arc_buf_hdr_t *
2918 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
2919     enum zio_compress compression_type, arc_buf_contents_t type)
2920 {
2921 	arc_buf_hdr_t *hdr;
2922 
2923 	VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
2924 
2925 	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
2926 	ASSERT(HDR_EMPTY(hdr));
2927 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2928 	ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
2929 	HDR_SET_PSIZE(hdr, psize);
2930 	HDR_SET_LSIZE(hdr, lsize);
2931 	hdr->b_spa = spa;
2932 	hdr->b_type = type;
2933 	hdr->b_flags = 0;
2934 	arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
2935 	arc_hdr_set_compress(hdr, compression_type);
2936 
2937 	hdr->b_l1hdr.b_state = arc_anon;
2938 	hdr->b_l1hdr.b_arc_access = 0;
2939 	hdr->b_l1hdr.b_bufcnt = 0;
2940 	hdr->b_l1hdr.b_buf = NULL;
2941 
2942 	/*
2943 	 * Allocate the hdr's buffer. This will contain either
2944 	 * the compressed or uncompressed data depending on the block
2945 	 * it references and compressed arc enablement.
2946 	 */
2947 	arc_hdr_alloc_pabd(hdr);
2948 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2949 
2950 	return (hdr);
2951 }
2952 
2953 /*
2954  * Transition between the two allocation states for the arc_buf_hdr struct.
2955  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
2956  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
2957  * version is used when a cache buffer is only in the L2ARC in order to reduce
2958  * memory usage.
2959  */
2960 static arc_buf_hdr_t *
2961 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
2962 {
2963 	ASSERT(HDR_HAS_L2HDR(hdr));
2964 
2965 	arc_buf_hdr_t *nhdr;
2966 	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2967 
2968 	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
2969 	    (old == hdr_l2only_cache && new == hdr_full_cache));
2970 
2971 	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
2972 
2973 	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
2974 	buf_hash_remove(hdr);
2975 
2976 	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
2977 
2978 	if (new == hdr_full_cache) {
2979 		arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
2980 		/*
2981 		 * arc_access and arc_change_state need to be aware that a
2982 		 * header has just come out of L2ARC, so we set its state to
2983 		 * l2c_only even though it's about to change.
2984 		 */
2985 		nhdr->b_l1hdr.b_state = arc_l2c_only;
2986 
2987 		/* Verify previous threads set to NULL before freeing */
2988 		ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
2989 	} else {
2990 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2991 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
2992 		ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
2993 
2994 		/*
2995 		 * If we've reached here, We must have been called from
2996 		 * arc_evict_hdr(), as such we should have already been
2997 		 * removed from any ghost list we were previously on
2998 		 * (which protects us from racing with arc_evict_state),
2999 		 * thus no locking is needed during this check.
3000 		 */
3001 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3002 
3003 		/*
3004 		 * A buffer must not be moved into the arc_l2c_only
3005 		 * state if it's not finished being written out to the
3006 		 * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3007 		 * might try to be accessed, even though it was removed.
3008 		 */
3009 		VERIFY(!HDR_L2_WRITING(hdr));
3010 		VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3011 
3012 #ifdef ZFS_DEBUG
3013 		if (hdr->b_l1hdr.b_thawed != NULL) {
3014 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3015 			hdr->b_l1hdr.b_thawed = NULL;
3016 		}
3017 #endif
3018 
3019 		arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3020 	}
3021 	/*
3022 	 * The header has been reallocated so we need to re-insert it into any
3023 	 * lists it was on.
3024 	 */
3025 	(void) buf_hash_insert(nhdr, NULL);
3026 
3027 	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3028 
3029 	mutex_enter(&dev->l2ad_mtx);
3030 
3031 	/*
3032 	 * We must place the realloc'ed header back into the list at
3033 	 * the same spot. Otherwise, if it's placed earlier in the list,
3034 	 * l2arc_write_buffers() could find it during the function's
3035 	 * write phase, and try to write it out to the l2arc.
3036 	 */
3037 	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3038 	list_remove(&dev->l2ad_buflist, hdr);
3039 
3040 	mutex_exit(&dev->l2ad_mtx);
3041 
3042 	/*
3043 	 * Since we're using the pointer address as the tag when
3044 	 * incrementing and decrementing the l2ad_alloc refcount, we
3045 	 * must remove the old pointer (that we're about to destroy) and
3046 	 * add the new pointer to the refcount. Otherwise we'd remove
3047 	 * the wrong pointer address when calling arc_hdr_destroy() later.
3048 	 */
3049 
3050 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr),
3051 	    hdr);
3052 	(void) zfs_refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr),
3053 	    nhdr);
3054 
3055 	buf_discard_identity(hdr);
3056 	kmem_cache_free(old, hdr);
3057 
3058 	return (nhdr);
3059 }
3060 
3061 /*
3062  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3063  * The buf is returned thawed since we expect the consumer to modify it.
3064  */
3065 arc_buf_t *
3066 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3067 {
3068 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3069 	    ZIO_COMPRESS_OFF, type);
3070 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3071 
3072 	arc_buf_t *buf = NULL;
3073 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3074 	arc_buf_thaw(buf);
3075 
3076 	return (buf);
3077 }
3078 
3079 /*
3080  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3081  * for bufs containing metadata.
3082  */
3083 arc_buf_t *
3084 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3085     enum zio_compress compression_type)
3086 {
3087 	ASSERT3U(lsize, >, 0);
3088 	ASSERT3U(lsize, >=, psize);
3089 	ASSERT(compression_type > ZIO_COMPRESS_OFF);
3090 	ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3091 
3092 	arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3093 	    compression_type, ARC_BUFC_DATA);
3094 	ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3095 
3096 	arc_buf_t *buf = NULL;
3097 	VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3098 	arc_buf_thaw(buf);
3099 	ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3100 
3101 	if (!arc_buf_is_shared(buf)) {
3102 		/*
3103 		 * To ensure that the hdr has the correct data in it if we call
3104 		 * arc_decompress() on this buf before it's been written to
3105 		 * disk, it's easiest if we just set up sharing between the
3106 		 * buf and the hdr.
3107 		 */
3108 		ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3109 		arc_hdr_free_pabd(hdr);
3110 		arc_share_buf(hdr, buf);
3111 	}
3112 
3113 	return (buf);
3114 }
3115 
3116 static void
3117 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3118 {
3119 	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3120 	l2arc_dev_t *dev = l2hdr->b_dev;
3121 	uint64_t psize = arc_hdr_size(hdr);
3122 
3123 	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3124 	ASSERT(HDR_HAS_L2HDR(hdr));
3125 
3126 	list_remove(&dev->l2ad_buflist, hdr);
3127 
3128 	ARCSTAT_INCR(arcstat_l2_psize, -psize);
3129 	ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3130 
3131 	vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3132 
3133 	(void) zfs_refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3134 	arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3135 }
3136 
3137 static void
3138 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3139 {
3140 	if (HDR_HAS_L1HDR(hdr)) {
3141 		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3142 		    hdr->b_l1hdr.b_bufcnt > 0);
3143 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3144 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3145 	}
3146 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3147 	ASSERT(!HDR_IN_HASH_TABLE(hdr));
3148 
3149 	if (!HDR_EMPTY(hdr))
3150 		buf_discard_identity(hdr);
3151 
3152 	if (HDR_HAS_L2HDR(hdr)) {
3153 		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3154 		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3155 
3156 		if (!buflist_held)
3157 			mutex_enter(&dev->l2ad_mtx);
3158 
3159 		/*
3160 		 * Even though we checked this conditional above, we
3161 		 * need to check this again now that we have the
3162 		 * l2ad_mtx. This is because we could be racing with
3163 		 * another thread calling l2arc_evict() which might have
3164 		 * destroyed this header's L2 portion as we were waiting
3165 		 * to acquire the l2ad_mtx. If that happens, we don't
3166 		 * want to re-destroy the header's L2 portion.
3167 		 */
3168 		if (HDR_HAS_L2HDR(hdr))
3169 			arc_hdr_l2hdr_destroy(hdr);
3170 
3171 		if (!buflist_held)
3172 			mutex_exit(&dev->l2ad_mtx);
3173 	}
3174 
3175 	if (HDR_HAS_L1HDR(hdr)) {
3176 		arc_cksum_free(hdr);
3177 
3178 		while (hdr->b_l1hdr.b_buf != NULL)
3179 			arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3180 
3181 #ifdef ZFS_DEBUG
3182 		if (hdr->b_l1hdr.b_thawed != NULL) {
3183 			kmem_free(hdr->b_l1hdr.b_thawed, 1);
3184 			hdr->b_l1hdr.b_thawed = NULL;
3185 		}
3186 #endif
3187 
3188 		if (hdr->b_l1hdr.b_pabd != NULL) {
3189 			arc_hdr_free_pabd(hdr);
3190 		}
3191 	}
3192 
3193 	ASSERT3P(hdr->b_hash_next, ==, NULL);
3194 	if (HDR_HAS_L1HDR(hdr)) {
3195 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3196 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3197 		kmem_cache_free(hdr_full_cache, hdr);
3198 	} else {
3199 		kmem_cache_free(hdr_l2only_cache, hdr);
3200 	}
3201 }
3202 
3203 void
3204 arc_buf_destroy(arc_buf_t *buf, void* tag)
3205 {
3206 	arc_buf_hdr_t *hdr = buf->b_hdr;
3207 	kmutex_t *hash_lock = HDR_LOCK(hdr);
3208 
3209 	if (hdr->b_l1hdr.b_state == arc_anon) {
3210 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3211 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3212 		VERIFY0(remove_reference(hdr, NULL, tag));
3213 		arc_hdr_destroy(hdr);
3214 		return;
3215 	}
3216 
3217 	mutex_enter(hash_lock);
3218 	ASSERT3P(hdr, ==, buf->b_hdr);
3219 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3220 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3221 	ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3222 	ASSERT3P(buf->b_data, !=, NULL);
3223 
3224 	(void) remove_reference(hdr, hash_lock, tag);
3225 	arc_buf_destroy_impl(buf);
3226 	mutex_exit(hash_lock);
3227 }
3228 
3229 /*
3230  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3231  * state of the header is dependent on it's state prior to entering this
3232  * function. The following transitions are possible:
3233  *
3234  *    - arc_mru -> arc_mru_ghost
3235  *    - arc_mfu -> arc_mfu_ghost
3236  *    - arc_mru_ghost -> arc_l2c_only
3237  *    - arc_mru_ghost -> deleted
3238  *    - arc_mfu_ghost -> arc_l2c_only
3239  *    - arc_mfu_ghost -> deleted
3240  */
3241 static int64_t
3242 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3243 {
3244 	arc_state_t *evicted_state, *state;
3245 	int64_t bytes_evicted = 0;
3246 
3247 	ASSERT(MUTEX_HELD(hash_lock));
3248 	ASSERT(HDR_HAS_L1HDR(hdr));
3249 
3250 	state = hdr->b_l1hdr.b_state;
3251 	if (GHOST_STATE(state)) {
3252 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3253 		ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3254 
3255 		/*
3256 		 * l2arc_write_buffers() relies on a header's L1 portion
3257 		 * (i.e. its b_pabd field) during it's write phase.
3258 		 * Thus, we cannot push a header onto the arc_l2c_only
3259 		 * state (removing it's L1 piece) until the header is
3260 		 * done being written to the l2arc.
3261 		 */
3262 		if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3263 			ARCSTAT_BUMP(arcstat_evict_l2_skip);
3264 			return (bytes_evicted);
3265 		}
3266 
3267 		ARCSTAT_BUMP(arcstat_deleted);
3268 		bytes_evicted += HDR_GET_LSIZE(hdr);
3269 
3270 		DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3271 
3272 		ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3273 		if (HDR_HAS_L2HDR(hdr)) {
3274 			/*
3275 			 * This buffer is cached on the 2nd Level ARC;
3276 			 * don't destroy the header.
3277 			 */
3278 			arc_change_state(arc_l2c_only, hdr, hash_lock);
3279 			/*
3280 			 * dropping from L1+L2 cached to L2-only,
3281 			 * realloc to remove the L1 header.
3282 			 */
3283 			hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3284 			    hdr_l2only_cache);
3285 		} else {
3286 			arc_change_state(arc_anon, hdr, hash_lock);
3287 			arc_hdr_destroy(hdr);
3288 		}
3289 		return (bytes_evicted);
3290 	}
3291 
3292 	ASSERT(state == arc_mru || state == arc_mfu);
3293 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3294 
3295 	/* prefetch buffers have a minimum lifespan */
3296 	if (HDR_IO_IN_PROGRESS(hdr) ||
3297 	    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3298 	    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
3299 	    arc_min_prefetch_lifespan)) {
3300 		ARCSTAT_BUMP(arcstat_evict_skip);
3301 		return (bytes_evicted);
3302 	}
3303 
3304 	ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
3305 	while (hdr->b_l1hdr.b_buf) {
3306 		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3307 		if (!mutex_tryenter(&buf->b_evict_lock)) {
3308 			ARCSTAT_BUMP(arcstat_mutex_miss);
3309 			break;
3310 		}
3311 		if (buf->b_data != NULL)
3312 			bytes_evicted += HDR_GET_LSIZE(hdr);
3313 		mutex_exit(&buf->b_evict_lock);
3314 		arc_buf_destroy_impl(buf);
3315 	}
3316 
3317 	if (HDR_HAS_L2HDR(hdr)) {
3318 		ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3319 	} else {
3320 		if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3321 			ARCSTAT_INCR(arcstat_evict_l2_eligible,
3322 			    HDR_GET_LSIZE(hdr));
3323 		} else {
3324 			ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3325 			    HDR_GET_LSIZE(hdr));
3326 		}
3327 	}
3328 
3329 	if (hdr->b_l1hdr.b_bufcnt == 0) {
3330 		arc_cksum_free(hdr);
3331 
3332 		bytes_evicted += arc_hdr_size(hdr);
3333 
3334 		/*
3335 		 * If this hdr is being evicted and has a compressed
3336 		 * buffer then we discard it here before we change states.
3337 		 * This ensures that the accounting is updated correctly
3338 		 * in arc_free_data_impl().
3339 		 */
3340 		arc_hdr_free_pabd(hdr);
3341 
3342 		arc_change_state(evicted_state, hdr, hash_lock);
3343 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3344 		arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3345 		DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3346 	}
3347 
3348 	return (bytes_evicted);
3349 }
3350 
3351 static uint64_t
3352 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3353     uint64_t spa, int64_t bytes)
3354 {
3355 	multilist_sublist_t *mls;
3356 	uint64_t bytes_evicted = 0;
3357 	arc_buf_hdr_t *hdr;
3358 	kmutex_t *hash_lock;
3359 	int evict_count = 0;
3360 
3361 	ASSERT3P(marker, !=, NULL);
3362 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3363 
3364 	mls = multilist_sublist_lock(ml, idx);
3365 
3366 	for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3367 	    hdr = multilist_sublist_prev(mls, marker)) {
3368 		if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3369 		    (evict_count >= zfs_arc_evict_batch_limit))
3370 			break;
3371 
3372 		/*
3373 		 * To keep our iteration location, move the marker
3374 		 * forward. Since we're not holding hdr's hash lock, we
3375 		 * must be very careful and not remove 'hdr' from the
3376 		 * sublist. Otherwise, other consumers might mistake the
3377 		 * 'hdr' as not being on a sublist when they call the
3378 		 * multilist_link_active() function (they all rely on
3379 		 * the hash lock protecting concurrent insertions and
3380 		 * removals). multilist_sublist_move_forward() was
3381 		 * specifically implemented to ensure this is the case
3382 		 * (only 'marker' will be removed and re-inserted).
3383 		 */
3384 		multilist_sublist_move_forward(mls, marker);
3385 
3386 		/*
3387 		 * The only case where the b_spa field should ever be
3388 		 * zero, is the marker headers inserted by
3389 		 * arc_evict_state(). It's possible for multiple threads
3390 		 * to be calling arc_evict_state() concurrently (e.g.
3391 		 * dsl_pool_close() and zio_inject_fault()), so we must
3392 		 * skip any markers we see from these other threads.
3393 		 */
3394 		if (hdr->b_spa == 0)
3395 			continue;
3396 
3397 		/* we're only interested in evicting buffers of a certain spa */
3398 		if (spa != 0 && hdr->b_spa != spa) {
3399 			ARCSTAT_BUMP(arcstat_evict_skip);
3400 			continue;
3401 		}
3402 
3403 		hash_lock = HDR_LOCK(hdr);
3404 
3405 		/*
3406 		 * We aren't calling this function from any code path
3407 		 * that would already be holding a hash lock, so we're
3408 		 * asserting on this assumption to be defensive in case
3409 		 * this ever changes. Without this check, it would be
3410 		 * possible to incorrectly increment arcstat_mutex_miss
3411 		 * below (e.g. if the code changed such that we called
3412 		 * this function with a hash lock held).
3413 		 */
3414 		ASSERT(!MUTEX_HELD(hash_lock));
3415 
3416 		if (mutex_tryenter(hash_lock)) {
3417 			uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3418 			mutex_exit(hash_lock);
3419 
3420 			bytes_evicted += evicted;
3421 
3422 			/*
3423 			 * If evicted is zero, arc_evict_hdr() must have
3424 			 * decided to skip this header, don't increment
3425 			 * evict_count in this case.
3426 			 */
3427 			if (evicted != 0)
3428 				evict_count++;
3429 
3430 			/*
3431 			 * If arc_size isn't overflowing, signal any
3432 			 * threads that might happen to be waiting.
3433 			 *
3434 			 * For each header evicted, we wake up a single
3435 			 * thread. If we used cv_broadcast, we could
3436 			 * wake up "too many" threads causing arc_size
3437 			 * to significantly overflow arc_c; since
3438 			 * arc_get_data_impl() doesn't check for overflow
3439 			 * when it's woken up (it doesn't because it's
3440 			 * possible for the ARC to be overflowing while
3441 			 * full of un-evictable buffers, and the
3442 			 * function should proceed in this case).
3443 			 *
3444 			 * If threads are left sleeping, due to not
3445 			 * using cv_broadcast here, they will be woken
3446 			 * up via cv_broadcast in arc_adjust_cb() just
3447 			 * before arc_adjust_zthr sleeps.
3448 			 */
3449 			mutex_enter(&arc_adjust_lock);
3450 			if (!arc_is_overflowing())
3451 				cv_signal(&arc_adjust_waiters_cv);
3452 			mutex_exit(&arc_adjust_lock);
3453 		} else {
3454 			ARCSTAT_BUMP(arcstat_mutex_miss);
3455 		}
3456 	}
3457 
3458 	multilist_sublist_unlock(mls);
3459 
3460 	return (bytes_evicted);
3461 }
3462 
3463 /*
3464  * Evict buffers from the given arc state, until we've removed the
3465  * specified number of bytes. Move the removed buffers to the
3466  * appropriate evict state.
3467  *
3468  * This function makes a "best effort". It skips over any buffers
3469  * it can't get a hash_lock on, and so, may not catch all candidates.
3470  * It may also return without evicting as much space as requested.
3471  *
3472  * If bytes is specified using the special value ARC_EVICT_ALL, this
3473  * will evict all available (i.e. unlocked and evictable) buffers from
3474  * the given arc state; which is used by arc_flush().
3475  */
3476 static uint64_t
3477 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3478     arc_buf_contents_t type)
3479 {
3480 	uint64_t total_evicted = 0;
3481 	multilist_t *ml = state->arcs_list[type];
3482 	int num_sublists;
3483 	arc_buf_hdr_t **markers;
3484 
3485 	IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3486 
3487 	num_sublists = multilist_get_num_sublists(ml);
3488 
3489 	/*
3490 	 * If we've tried to evict from each sublist, made some
3491 	 * progress, but still have not hit the target number of bytes
3492 	 * to evict, we want to keep trying. The markers allow us to
3493 	 * pick up where we left off for each individual sublist, rather
3494 	 * than starting from the tail each time.
3495 	 */
3496 	markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3497 	for (int i = 0; i < num_sublists; i++) {
3498 		markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3499 
3500 		/*
3501 		 * A b_spa of 0 is used to indicate that this header is
3502 		 * a marker. This fact is used in arc_adjust_type() and
3503 		 * arc_evict_state_impl().
3504 		 */
3505 		markers[i]->b_spa = 0;
3506 
3507 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3508 		multilist_sublist_insert_tail(mls, markers[i]);
3509 		multilist_sublist_unlock(mls);
3510 	}
3511 
3512 	/*
3513 	 * While we haven't hit our target number of bytes to evict, or
3514 	 * we're evicting all available buffers.
3515 	 */
3516 	while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3517 		/*
3518 		 * Start eviction using a randomly selected sublist,
3519 		 * this is to try and evenly balance eviction across all
3520 		 * sublists. Always starting at the same sublist
3521 		 * (e.g. index 0) would cause evictions to favor certain
3522 		 * sublists over others.
3523 		 */
3524 		int sublist_idx = multilist_get_random_index(ml);
3525 		uint64_t scan_evicted = 0;
3526 
3527 		for (int i = 0; i < num_sublists; i++) {
3528 			uint64_t bytes_remaining;
3529 			uint64_t bytes_evicted;
3530 
3531 			if (bytes == ARC_EVICT_ALL)
3532 				bytes_remaining = ARC_EVICT_ALL;
3533 			else if (total_evicted < bytes)
3534 				bytes_remaining = bytes - total_evicted;
3535 			else
3536 				break;
3537 
3538 			bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3539 			    markers[sublist_idx], spa, bytes_remaining);
3540 
3541 			scan_evicted += bytes_evicted;
3542 			total_evicted += bytes_evicted;
3543 
3544 			/* we've reached the end, wrap to the beginning */
3545 			if (++sublist_idx >= num_sublists)
3546 				sublist_idx = 0;
3547 		}
3548 
3549 		/*
3550 		 * If we didn't evict anything during this scan, we have
3551 		 * no reason to believe we'll evict more during another
3552 		 * scan, so break the loop.
3553 		 */
3554 		if (scan_evicted == 0) {
3555 			/* This isn't possible, let's make that obvious */
3556 			ASSERT3S(bytes, !=, 0);
3557 
3558 			/*
3559 			 * When bytes is ARC_EVICT_ALL, the only way to
3560 			 * break the loop is when scan_evicted is zero.
3561 			 * In that case, we actually have evicted enough,
3562 			 * so we don't want to increment the kstat.
3563 			 */
3564 			if (bytes != ARC_EVICT_ALL) {
3565 				ASSERT3S(total_evicted, <, bytes);
3566 				ARCSTAT_BUMP(arcstat_evict_not_enough);
3567 			}
3568 
3569 			break;
3570 		}
3571 	}
3572 
3573 	for (int i = 0; i < num_sublists; i++) {
3574 		multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3575 		multilist_sublist_remove(mls, markers[i]);
3576 		multilist_sublist_unlock(mls);
3577 
3578 		kmem_cache_free(hdr_full_cache, markers[i]);
3579 	}
3580 	kmem_free(markers, sizeof (*markers) * num_sublists);
3581 
3582 	return (total_evicted);
3583 }
3584 
3585 /*
3586  * Flush all "evictable" data of the given type from the arc state
3587  * specified. This will not evict any "active" buffers (i.e. referenced).
3588  *
3589  * When 'retry' is set to B_FALSE, the function will make a single pass
3590  * over the state and evict any buffers that it can. Since it doesn't
3591  * continually retry the eviction, it might end up leaving some buffers
3592  * in the ARC due to lock misses.
3593  *
3594  * When 'retry' is set to B_TRUE, the function will continually retry the
3595  * eviction until *all* evictable buffers have been removed from the
3596  * state. As a result, if concurrent insertions into the state are
3597  * allowed (e.g. if the ARC isn't shutting down), this function might
3598  * wind up in an infinite loop, continually trying to evict buffers.
3599  */
3600 static uint64_t
3601 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
3602     boolean_t retry)
3603 {
3604 	uint64_t evicted = 0;
3605 
3606 	while (zfs_refcount_count(&state->arcs_esize[type]) != 0) {
3607 		evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
3608 
3609 		if (!retry)
3610 			break;
3611 	}
3612 
3613 	return (evicted);
3614 }
3615 
3616 /*
3617  * Evict the specified number of bytes from the state specified,
3618  * restricting eviction to the spa and type given. This function
3619  * prevents us from trying to evict more from a state's list than
3620  * is "evictable", and to skip evicting altogether when passed a
3621  * negative value for "bytes". In contrast, arc_evict_state() will
3622  * evict everything it can, when passed a negative value for "bytes".
3623  */
3624 static uint64_t
3625 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
3626     arc_buf_contents_t type)
3627 {
3628 	int64_t delta;
3629 
3630 	if (bytes > 0 && zfs_refcount_count(&state->arcs_esize[type]) > 0) {
3631 		delta = MIN(zfs_refcount_count(&state->arcs_esize[type]),
3632 		    bytes);
3633 		return (arc_evict_state(state, spa, delta, type));
3634 	}
3635 
3636 	return (0);
3637 }
3638 
3639 /*
3640  * Evict metadata buffers from the cache, such that arc_meta_used is
3641  * capped by the arc_meta_limit tunable.
3642  */
3643 static uint64_t
3644 arc_adjust_meta(uint64_t meta_used)
3645 {
3646 	uint64_t total_evicted = 0;
3647 	int64_t target;
3648 
3649 	/*
3650 	 * If we're over the meta limit, we want to evict enough
3651 	 * metadata to get back under the meta limit. We don't want to
3652 	 * evict so much that we drop the MRU below arc_p, though. If
3653 	 * we're over the meta limit more than we're over arc_p, we
3654 	 * evict some from the MRU here, and some from the MFU below.
3655 	 */
3656 	target = MIN((int64_t)(meta_used - arc_meta_limit),
3657 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
3658 	    zfs_refcount_count(&arc_mru->arcs_size) - arc_p));
3659 
3660 	total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3661 
3662 	/*
3663 	 * Similar to the above, we want to evict enough bytes to get us
3664 	 * below the meta limit, but not so much as to drop us below the
3665 	 * space allotted to the MFU (which is defined as arc_c - arc_p).
3666 	 */
3667 	target = MIN((int64_t)(meta_used - arc_meta_limit),
3668 	    (int64_t)(zfs_refcount_count(&arc_mfu->arcs_size) -
3669 	    (arc_c - arc_p)));
3670 
3671 	total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3672 
3673 	return (total_evicted);
3674 }
3675 
3676 /*
3677  * Return the type of the oldest buffer in the given arc state
3678  *
3679  * This function will select a random sublist of type ARC_BUFC_DATA and
3680  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
3681  * is compared, and the type which contains the "older" buffer will be
3682  * returned.
3683  */
3684 static arc_buf_contents_t
3685 arc_adjust_type(arc_state_t *state)
3686 {
3687 	multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
3688 	multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
3689 	int data_idx = multilist_get_random_index(data_ml);
3690 	int meta_idx = multilist_get_random_index(meta_ml);
3691 	multilist_sublist_t *data_mls;
3692 	multilist_sublist_t *meta_mls;
3693 	arc_buf_contents_t type;
3694 	arc_buf_hdr_t *data_hdr;
3695 	arc_buf_hdr_t *meta_hdr;
3696 
3697 	/*
3698 	 * We keep the sublist lock until we're finished, to prevent
3699 	 * the headers from being destroyed via arc_evict_state().
3700 	 */
3701 	data_mls = multilist_sublist_lock(data_ml, data_idx);
3702 	meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
3703 
3704 	/*
3705 	 * These two loops are to ensure we skip any markers that
3706 	 * might be at the tail of the lists due to arc_evict_state().
3707 	 */
3708 
3709 	for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
3710 	    data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
3711 		if (data_hdr->b_spa != 0)
3712 			break;
3713 	}
3714 
3715 	for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
3716 	    meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
3717 		if (meta_hdr->b_spa != 0)
3718 			break;
3719 	}
3720 
3721 	if (data_hdr == NULL && meta_hdr == NULL) {
3722 		type = ARC_BUFC_DATA;
3723 	} else if (data_hdr == NULL) {
3724 		ASSERT3P(meta_hdr, !=, NULL);
3725 		type = ARC_BUFC_METADATA;
3726 	} else if (meta_hdr == NULL) {
3727 		ASSERT3P(data_hdr, !=, NULL);
3728 		type = ARC_BUFC_DATA;
3729 	} else {
3730 		ASSERT3P(data_hdr, !=, NULL);
3731 		ASSERT3P(meta_hdr, !=, NULL);
3732 
3733 		/* The headers can't be on the sublist without an L1 header */
3734 		ASSERT(HDR_HAS_L1HDR(data_hdr));
3735 		ASSERT(HDR_HAS_L1HDR(meta_hdr));
3736 
3737 		if (data_hdr->b_l1hdr.b_arc_access <
3738 		    meta_hdr->b_l1hdr.b_arc_access) {
3739 			type = ARC_BUFC_DATA;
3740 		} else {
3741 			type = ARC_BUFC_METADATA;
3742 		}
3743 	}
3744 
3745 	multilist_sublist_unlock(meta_mls);
3746 	multilist_sublist_unlock(data_mls);
3747 
3748 	return (type);
3749 }
3750 
3751 /*
3752  * Evict buffers from the cache, such that arc_size is capped by arc_c.
3753  */
3754 static uint64_t
3755 arc_adjust(void)
3756 {
3757 	uint64_t total_evicted = 0;
3758 	uint64_t bytes;
3759 	int64_t target;
3760 	uint64_t asize = aggsum_value(&arc_size);
3761 	uint64_t ameta = aggsum_value(&arc_meta_used);
3762 
3763 	/*
3764 	 * If we're over arc_meta_limit, we want to correct that before
3765 	 * potentially evicting data buffers below.
3766 	 */
3767 	total_evicted += arc_adjust_meta(ameta);
3768 
3769 	/*
3770 	 * Adjust MRU size
3771 	 *
3772 	 * If we're over the target cache size, we want to evict enough
3773 	 * from the list to get back to our target size. We don't want
3774 	 * to evict too much from the MRU, such that it drops below
3775 	 * arc_p. So, if we're over our target cache size more than
3776 	 * the MRU is over arc_p, we'll evict enough to get back to
3777 	 * arc_p here, and then evict more from the MFU below.
3778 	 */
3779 	target = MIN((int64_t)(asize - arc_c),
3780 	    (int64_t)(zfs_refcount_count(&arc_anon->arcs_size) +
3781 	    zfs_refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
3782 
3783 	/*
3784 	 * If we're below arc_meta_min, always prefer to evict data.
3785 	 * Otherwise, try to satisfy the requested number of bytes to
3786 	 * evict from the type which contains older buffers; in an
3787 	 * effort to keep newer buffers in the cache regardless of their
3788 	 * type. If we cannot satisfy the number of bytes from this
3789 	 * type, spill over into the next type.
3790 	 */
3791 	if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
3792 	    ameta > arc_meta_min) {
3793 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3794 		total_evicted += bytes;
3795 
3796 		/*
3797 		 * If we couldn't evict our target number of bytes from
3798 		 * metadata, we try to get the rest from data.
3799 		 */
3800 		target -= bytes;
3801 
3802 		total_evicted +=
3803 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3804 	} else {
3805 		bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
3806 		total_evicted += bytes;
3807 
3808 		/*
3809 		 * If we couldn't evict our target number of bytes from
3810 		 * data, we try to get the rest from metadata.
3811 		 */
3812 		target -= bytes;
3813 
3814 		total_evicted +=
3815 		    arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
3816 	}
3817 
3818 	/*
3819 	 * Adjust MFU size
3820 	 *
3821 	 * Now that we've tried to evict enough from the MRU to get its
3822 	 * size back to arc_p, if we're still above the target cache
3823 	 * size, we evict the rest from the MFU.
3824 	 */
3825 	target = asize - arc_c;
3826 
3827 	if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
3828 	    ameta > arc_meta_min) {
3829 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3830 		total_evicted += bytes;
3831 
3832 		/*
3833 		 * If we couldn't evict our target number of bytes from
3834 		 * metadata, we try to get the rest from data.
3835 		 */
3836 		target -= bytes;
3837 
3838 		total_evicted +=
3839 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3840 	} else {
3841 		bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
3842 		total_evicted += bytes;
3843 
3844 		/*
3845 		 * If we couldn't evict our target number of bytes from
3846 		 * data, we try to get the rest from data.
3847 		 */
3848 		target -= bytes;
3849 
3850 		total_evicted +=
3851 		    arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
3852 	}
3853 
3854 	/*
3855 	 * Adjust ghost lists
3856 	 *
3857 	 * In addition to the above, the ARC also defines target values
3858 	 * for the ghost lists. The sum of the mru list and mru ghost
3859 	 * list should never exceed the target size of the cache, and
3860 	 * the sum of the mru list, mfu list, mru ghost list, and mfu
3861 	 * ghost list should never exceed twice the target size of the
3862 	 * cache. The following logic enforces these limits on the ghost
3863 	 * caches, and evicts from them as needed.
3864 	 */
3865 	target = zfs_refcount_count(&arc_mru->arcs_size) +
3866 	    zfs_refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
3867 
3868 	bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
3869 	total_evicted += bytes;
3870 
3871 	target -= bytes;
3872 
3873 	total_evicted +=
3874 	    arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
3875 
3876 	/*
3877 	 * We assume the sum of the mru list and mfu list is less than
3878 	 * or equal to arc_c (we enforced this above), which means we
3879 	 * can use the simpler of the two equations below:
3880 	 *
3881 	 *	mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
3882 	 *		    mru ghost + mfu ghost <= arc_c
3883 	 */
3884 	target = zfs_refcount_count(&arc_mru_ghost->arcs_size) +
3885 	    zfs_refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
3886 
3887 	bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
3888 	total_evicted += bytes;
3889 
3890 	target -= bytes;
3891 
3892 	total_evicted +=
3893 	    arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
3894 
3895 	return (total_evicted);
3896 }
3897 
3898 void
3899 arc_flush(spa_t *spa, boolean_t retry)
3900 {
3901 	uint64_t guid = 0;
3902 
3903 	/*
3904 	 * If retry is B_TRUE, a spa must not be specified since we have
3905 	 * no good way to determine if all of a spa's buffers have been
3906 	 * evicted from an arc state.
3907 	 */
3908 	ASSERT(!retry || spa == 0);
3909 
3910 	if (spa != NULL)
3911 		guid = spa_load_guid(spa);
3912 
3913 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
3914 	(void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
3915 
3916 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
3917 	(void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
3918 
3919 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
3920 	(void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
3921 
3922 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
3923 	(void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
3924 }
3925 
3926 static void
3927 arc_reduce_target_size(int64_t to_free)
3928 {
3929 	uint64_t asize = aggsum_value(&arc_size);
3930 	if (arc_c > arc_c_min) {
3931 
3932 		if (arc_c > arc_c_min + to_free)
3933 			atomic_add_64(&arc_c, -to_free);
3934 		else
3935 			arc_c = arc_c_min;
3936 
3937 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3938 		if (asize < arc_c)
3939 			arc_c = MAX(asize, arc_c_min);
3940 		if (arc_p > arc_c)
3941 			arc_p = (arc_c >> 1);
3942 		ASSERT(arc_c >= arc_c_min);
3943 		ASSERT((int64_t)arc_p >= 0);
3944 	}
3945 
3946 	if (asize > arc_c) {
3947 		/* See comment in arc_adjust_cb_check() on why lock+flag */
3948 		mutex_enter(&arc_adjust_lock);
3949 		arc_adjust_needed = B_TRUE;
3950 		mutex_exit(&arc_adjust_lock);
3951 		zthr_wakeup(arc_adjust_zthr);
3952 	}
3953 }
3954 
3955 typedef enum free_memory_reason_t {
3956 	FMR_UNKNOWN,
3957 	FMR_NEEDFREE,
3958 	FMR_LOTSFREE,
3959 	FMR_SWAPFS_MINFREE,
3960 	FMR_PAGES_PP_MAXIMUM,
3961 	FMR_HEAP_ARENA,
3962 	FMR_ZIO_ARENA,
3963 } free_memory_reason_t;
3964 
3965 int64_t last_free_memory;
3966 free_memory_reason_t last_free_reason;
3967 
3968 /*
3969  * Additional reserve of pages for pp_reserve.
3970  */
3971 int64_t arc_pages_pp_reserve = 64;
3972 
3973 /*
3974  * Additional reserve of pages for swapfs.
3975  */
3976 int64_t arc_swapfs_reserve = 64;
3977 
3978 /*
3979  * Return the amount of memory that can be consumed before reclaim will be
3980  * needed.  Positive if there is sufficient free memory, negative indicates
3981  * the amount of memory that needs to be freed up.
3982  */
3983 static int64_t
3984 arc_available_memory(void)
3985 {
3986 	int64_t lowest = INT64_MAX;
3987 	int64_t n;
3988 	free_memory_reason_t r = FMR_UNKNOWN;
3989 
3990 #ifdef _KERNEL
3991 	if (needfree > 0) {
3992 		n = PAGESIZE * (-needfree);
3993 		if (n < lowest) {
3994 			lowest = n;
3995 			r = FMR_NEEDFREE;
3996 		}
3997 	}
3998 
3999 	/*
4000 	 * check that we're out of range of the pageout scanner.  It starts to
4001 	 * schedule paging if freemem is less than lotsfree and needfree.
4002 	 * lotsfree is the high-water mark for pageout, and needfree is the
4003 	 * number of needed free pages.  We add extra pages here to make sure
4004 	 * the scanner doesn't start up while we're freeing memory.
4005 	 */
4006 	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4007 	if (n < lowest) {
4008 		lowest = n;
4009 		r = FMR_LOTSFREE;
4010 	}
4011 
4012 	/*
4013 	 * check to make sure that swapfs has enough space so that anon
4014 	 * reservations can still succeed. anon_resvmem() checks that the
4015 	 * availrmem is greater than swapfs_minfree, and the number of reserved
4016 	 * swap pages.  We also add a bit of extra here just to prevent
4017 	 * circumstances from getting really dire.
4018 	 */
4019 	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4020 	    desfree - arc_swapfs_reserve);
4021 	if (n < lowest) {
4022 		lowest = n;
4023 		r = FMR_SWAPFS_MINFREE;
4024 	}
4025 
4026 
4027 	/*
4028 	 * Check that we have enough availrmem that memory locking (e.g., via
4029 	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4030 	 * stores the number of pages that cannot be locked; when availrmem
4031 	 * drops below pages_pp_maximum, page locking mechanisms such as
4032 	 * page_pp_lock() will fail.)
4033 	 */
4034 	n = PAGESIZE * (availrmem - pages_pp_maximum -
4035 	    arc_pages_pp_reserve);
4036 	if (n < lowest) {
4037 		lowest = n;
4038 		r = FMR_PAGES_PP_MAXIMUM;
4039 	}
4040 
4041 #if defined(__i386)
4042 	/*
4043 	 * If we're on an i386 platform, it's possible that we'll exhaust the
4044 	 * kernel heap space before we ever run out of available physical
4045 	 * memory.  Most checks of the size of the heap_area compare against
4046 	 * tune.t_minarmem, which is the minimum available real memory that we
4047 	 * can have in the system.  However, this is generally fixed at 25 pages
4048 	 * which is so low that it's useless.  In this comparison, we seek to
4049 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
4050 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4051 	 * free)
4052 	 */
4053 	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
4054 	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
4055 	if (n < lowest) {
4056 		lowest = n;
4057 		r = FMR_HEAP_ARENA;
4058 	}
4059 #endif
4060 
4061 	/*
4062 	 * If zio data pages are being allocated out of a separate heap segment,
4063 	 * then enforce that the size of available vmem for this arena remains
4064 	 * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4065 	 *
4066 	 * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4067 	 * memory (in the zio_arena) free, which can avoid memory
4068 	 * fragmentation issues.
4069 	 */
4070 	if (zio_arena != NULL) {
4071 		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4072 		    (vmem_size(zio_arena, VMEM_ALLOC) >>
4073 		    arc_zio_arena_free_shift);
4074 		if (n < lowest) {
4075 			lowest = n;
4076 			r = FMR_ZIO_ARENA;
4077 		}
4078 	}
4079 #else
4080 	/* Every 100 calls, free a small amount */
4081 	if (spa_get_random(100) == 0)
4082 		lowest = -1024;
4083 #endif
4084 
4085 	last_free_memory = lowest;
4086 	last_free_reason = r;
4087 
4088 	return (lowest);
4089 }
4090 
4091 
4092 /*
4093  * Determine if the system is under memory pressure and is asking
4094  * to reclaim memory. A return value of B_TRUE indicates that the system
4095  * is under memory pressure and that the arc should adjust accordingly.
4096  */
4097 static boolean_t
4098 arc_reclaim_needed(void)
4099 {
4100 	return (arc_available_memory() < 0);
4101 }
4102 
4103 static void
4104 arc_kmem_reap_soon(void)
4105 {
4106 	size_t			i;
4107 	kmem_cache_t		*prev_cache = NULL;
4108 	kmem_cache_t		*prev_data_cache = NULL;
4109 	extern kmem_cache_t	*zio_buf_cache[];
4110 	extern kmem_cache_t	*zio_data_buf_cache[];
4111 	extern kmem_cache_t	*range_seg_cache;
4112 	extern kmem_cache_t	*abd_chunk_cache;
4113 
4114 #ifdef _KERNEL
4115 	if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4116 		/*
4117 		 * We are exceeding our meta-data cache limit.
4118 		 * Purge some DNLC entries to release holds on meta-data.
4119 		 */
4120 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4121 	}
4122 #if defined(__i386)
4123 	/*
4124 	 * Reclaim unused memory from all kmem caches.
4125 	 */
4126 	kmem_reap();
4127 #endif
4128 #endif
4129 
4130 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4131 		if (zio_buf_cache[i] != prev_cache) {
4132 			prev_cache = zio_buf_cache[i];
4133 			kmem_cache_reap_soon(zio_buf_cache[i]);
4134 		}
4135 		if (zio_data_buf_cache[i] != prev_data_cache) {
4136 			prev_data_cache = zio_data_buf_cache[i];
4137 			kmem_cache_reap_soon(zio_data_buf_cache[i]);
4138 		}
4139 	}
4140 	kmem_cache_reap_soon(abd_chunk_cache);
4141 	kmem_cache_reap_soon(buf_cache);
4142 	kmem_cache_reap_soon(hdr_full_cache);
4143 	kmem_cache_reap_soon(hdr_l2only_cache);
4144 	kmem_cache_reap_soon(range_seg_cache);
4145 
4146 	if (zio_arena != NULL) {
4147 		/*
4148 		 * Ask the vmem arena to reclaim unused memory from its
4149 		 * quantum caches.
4150 		 */
4151 		vmem_qcache_reap(zio_arena);
4152 	}
4153 }
4154 
4155 /* ARGSUSED */
4156 static boolean_t
4157 arc_adjust_cb_check(void *arg, zthr_t *zthr)
4158 {
4159 	/*
4160 	 * This is necessary in order for the mdb ::arc dcmd to
4161 	 * show up to date information. Since the ::arc command
4162 	 * does not call the kstat's update function, without
4163 	 * this call, the command may show stale stats for the
4164 	 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4165 	 * with this change, the data might be up to 1 second
4166 	 * out of date(the arc_adjust_zthr has a maximum sleep
4167 	 * time of 1 second); but that should suffice.  The
4168 	 * arc_state_t structures can be queried directly if more
4169 	 * accurate information is needed.
4170 	 */
4171 	if (arc_ksp != NULL)
4172 		arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4173 
4174 	/*
4175 	 * We have to rely on arc_get_data_impl() to tell us when to adjust,
4176 	 * rather than checking if we are overflowing here, so that we are
4177 	 * sure to not leave arc_get_data_impl() waiting on
4178 	 * arc_adjust_waiters_cv.  If we have become "not overflowing" since
4179 	 * arc_get_data_impl() checked, we need to wake it up.  We could
4180 	 * broadcast the CV here, but arc_get_data_impl() may have not yet
4181 	 * gone to sleep.  We would need to use a mutex to ensure that this
4182 	 * function doesn't broadcast until arc_get_data_impl() has gone to
4183 	 * sleep (e.g. the arc_adjust_lock).  However, the lock ordering of
4184 	 * such a lock would necessarily be incorrect with respect to the
4185 	 * zthr_lock, which is held before this function is called, and is
4186 	 * held by arc_get_data_impl() when it calls zthr_wakeup().
4187 	 */
4188 	return (arc_adjust_needed);
4189 }
4190 
4191 /*
4192  * Keep arc_size under arc_c by running arc_adjust which evicts data
4193  * from the ARC.
4194  */
4195 /* ARGSUSED */
4196 static int
4197 arc_adjust_cb(void *arg, zthr_t *zthr)
4198 {
4199 	uint64_t evicted = 0;
4200 
4201 	/* Evict from cache */
4202 	evicted = arc_adjust();
4203 
4204 	/*
4205 	 * If evicted is zero, we couldn't evict anything
4206 	 * via arc_adjust(). This could be due to hash lock
4207 	 * collisions, but more likely due to the majority of
4208 	 * arc buffers being unevictable. Therefore, even if
4209 	 * arc_size is above arc_c, another pass is unlikely to
4210 	 * be helpful and could potentially cause us to enter an
4211 	 * infinite loop.  Additionally, zthr_iscancelled() is
4212 	 * checked here so that if the arc is shutting down, the
4213 	 * broadcast will wake any remaining arc adjust waiters.
4214 	 */
4215 	mutex_enter(&arc_adjust_lock);
4216 	arc_adjust_needed = !zthr_iscancelled(arc_adjust_zthr) &&
4217 	    evicted > 0 && aggsum_compare(&arc_size, arc_c) > 0;
4218 	if (!arc_adjust_needed) {
4219 		/*
4220 		 * We're either no longer overflowing, or we
4221 		 * can't evict anything more, so we should wake
4222 		 * up any waiters.
4223 		 */
4224 		cv_broadcast(&arc_adjust_waiters_cv);
4225 	}
4226 	mutex_exit(&arc_adjust_lock);
4227 
4228 	return (0);
4229 }
4230 
4231 /* ARGSUSED */
4232 static boolean_t
4233 arc_reap_cb_check(void *arg, zthr_t *zthr)
4234 {
4235 	int64_t free_memory = arc_available_memory();
4236 
4237 	/*
4238 	 * If a kmem reap is already active, don't schedule more.  We must
4239 	 * check for this because kmem_cache_reap_soon() won't actually
4240 	 * block on the cache being reaped (this is to prevent callers from
4241 	 * becoming implicitly blocked by a system-wide kmem reap -- which,
4242 	 * on a system with many, many full magazines, can take minutes).
4243 	 */
4244 	if (!kmem_cache_reap_active() &&
4245 	    free_memory < 0) {
4246 		arc_no_grow = B_TRUE;
4247 		arc_warm = B_TRUE;
4248 		/*
4249 		 * Wait at least zfs_grow_retry (default 60) seconds
4250 		 * before considering growing.
4251 		 */
4252 		arc_growtime = gethrtime() + SEC2NSEC(arc_grow_retry);
4253 		return (B_TRUE);
4254 	} else if (free_memory < arc_c >> arc_no_grow_shift) {
4255 		arc_no_grow = B_TRUE;
4256 	} else if (gethrtime() >= arc_growtime) {
4257 		arc_no_grow = B_FALSE;
4258 	}
4259 
4260 	return (B_FALSE);
4261 }
4262 
4263 /*
4264  * Keep enough free memory in the system by reaping the ARC's kmem
4265  * caches.  To cause more slabs to be reapable, we may reduce the
4266  * target size of the cache (arc_c), causing the arc_adjust_cb()
4267  * to free more buffers.
4268  */
4269 /* ARGSUSED */
4270 static int
4271 arc_reap_cb(void *arg, zthr_t *zthr)
4272 {
4273 	int64_t free_memory;
4274 
4275 	/*
4276 	 * Kick off asynchronous kmem_reap()'s of all our caches.
4277 	 */
4278 	arc_kmem_reap_soon();
4279 
4280 	/*
4281 	 * Wait at least arc_kmem_cache_reap_retry_ms between
4282 	 * arc_kmem_reap_soon() calls. Without this check it is possible to
4283 	 * end up in a situation where we spend lots of time reaping
4284 	 * caches, while we're near arc_c_min.  Waiting here also gives the
4285 	 * subsequent free memory check a chance of finding that the
4286 	 * asynchronous reap has already freed enough memory, and we don't
4287 	 * need to call arc_reduce_target_size().
4288 	 */
4289 	delay((hz * arc_kmem_cache_reap_retry_ms + 999) / 1000);
4290 
4291 	/*
4292 	 * Reduce the target size as needed to maintain the amount of free
4293 	 * memory in the system at a fraction of the arc_size (1/128th by
4294 	 * default).  If oversubscribed (free_memory < 0) then reduce the
4295 	 * target arc_size by the deficit amount plus the fractional
4296 	 * amount.  If free memory is positive but less then the fractional
4297 	 * amount, reduce by what is needed to hit the fractional amount.
4298 	 */
4299 	free_memory = arc_available_memory();
4300 
4301 	int64_t to_free =
4302 	    (arc_c >> arc_shrink_shift) - free_memory;
4303 	if (to_free > 0) {
4304 #ifdef _KERNEL
4305 		to_free = MAX(to_free, ptob(needfree));
4306 #endif
4307 		arc_reduce_target_size(to_free);
4308 	}
4309 
4310 	return (0);
4311 }
4312 
4313 /*
4314  * Adapt arc info given the number of bytes we are trying to add and
4315  * the state that we are comming from.  This function is only called
4316  * when we are adding new content to the cache.
4317  */
4318 static void
4319 arc_adapt(int bytes, arc_state_t *state)
4320 {
4321 	int mult;
4322 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
4323 	int64_t mrug_size = zfs_refcount_count(&arc_mru_ghost->arcs_size);
4324 	int64_t mfug_size = zfs_refcount_count(&arc_mfu_ghost->arcs_size);
4325 
4326 	if (state == arc_l2c_only)
4327 		return;
4328 
4329 	ASSERT(bytes > 0);
4330 	/*
4331 	 * Adapt the target size of the MRU list:
4332 	 *	- if we just hit in the MRU ghost list, then increase
4333 	 *	  the target size of the MRU list.
4334 	 *	- if we just hit in the MFU ghost list, then increase
4335 	 *	  the target size of the MFU list by decreasing the
4336 	 *	  target size of the MRU list.
4337 	 */
4338 	if (state == arc_mru_ghost) {
4339 		mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
4340 		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
4341 
4342 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
4343 	} else if (state == arc_mfu_ghost) {
4344 		uint64_t delta;
4345 
4346 		mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
4347 		mult = MIN(mult, 10);
4348 
4349 		delta = MIN(bytes * mult, arc_p);
4350 		arc_p = MAX(arc_p_min, arc_p - delta);
4351 	}
4352 	ASSERT((int64_t)arc_p >= 0);
4353 
4354 	/*
4355 	 * Wake reap thread if we do not have any available memory
4356 	 */
4357 	if (arc_reclaim_needed()) {
4358 		zthr_wakeup(arc_reap_zthr);
4359 		return;
4360 	}
4361 
4362 
4363 	if (arc_no_grow)
4364 		return;
4365 
4366 	if (arc_c >= arc_c_max)
4367 		return;
4368 
4369 	/*
4370 	 * If we're within (2 * maxblocksize) bytes of the target
4371 	 * cache size, increment the target cache size
4372 	 */
4373 	if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
4374 	    0) {
4375 		atomic_add_64(&arc_c, (int64_t)bytes);
4376 		if (arc_c > arc_c_max)
4377 			arc_c = arc_c_max;
4378 		else if (state == arc_anon)
4379 			atomic_add_64(&arc_p, (int64_t)bytes);
4380 		if (arc_p > arc_c)
4381 			arc_p = arc_c;
4382 	}
4383 	ASSERT((int64_t)arc_p >= 0);
4384 }
4385 
4386 /*
4387  * Check if arc_size has grown past our upper threshold, determined by
4388  * zfs_arc_overflow_shift.
4389  */
4390 static boolean_t
4391 arc_is_overflowing(void)
4392 {
4393 	/* Always allow at least one block of overflow */
4394 	uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
4395 	    arc_c >> zfs_arc_overflow_shift);
4396 
4397 	/*
4398 	 * We just compare the lower bound here for performance reasons. Our
4399 	 * primary goals are to make sure that the arc never grows without
4400 	 * bound, and that it can reach its maximum size. This check
4401 	 * accomplishes both goals. The maximum amount we could run over by is
4402 	 * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
4403 	 * in the ARC. In practice, that's in the tens of MB, which is low
4404 	 * enough to be safe.
4405 	 */
4406 	return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
4407 }
4408 
4409 static abd_t *
4410 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4411 {
4412 	arc_buf_contents_t type = arc_buf_type(hdr);
4413 
4414 	arc_get_data_impl(hdr, size, tag);
4415 	if (type == ARC_BUFC_METADATA) {
4416 		return (abd_alloc(size, B_TRUE));
4417 	} else {
4418 		ASSERT(type == ARC_BUFC_DATA);
4419 		return (abd_alloc(size, B_FALSE));
4420 	}
4421 }
4422 
4423 static void *
4424 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4425 {
4426 	arc_buf_contents_t type = arc_buf_type(hdr);
4427 
4428 	arc_get_data_impl(hdr, size, tag);
4429 	if (type == ARC_BUFC_METADATA) {
4430 		return (zio_buf_alloc(size));
4431 	} else {
4432 		ASSERT(type == ARC_BUFC_DATA);
4433 		return (zio_data_buf_alloc(size));
4434 	}
4435 }
4436 
4437 /*
4438  * Allocate a block and return it to the caller. If we are hitting the
4439  * hard limit for the cache size, we must sleep, waiting for the eviction
4440  * thread to catch up. If we're past the target size but below the hard
4441  * limit, we'll only signal the reclaim thread and continue on.
4442  */
4443 static void
4444 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4445 {
4446 	arc_state_t *state = hdr->b_l1hdr.b_state;
4447 	arc_buf_contents_t type = arc_buf_type(hdr);
4448 
4449 	arc_adapt(size, state);
4450 
4451 	/*
4452 	 * If arc_size is currently overflowing, and has grown past our
4453 	 * upper limit, we must be adding data faster than the evict
4454 	 * thread can evict. Thus, to ensure we don't compound the
4455 	 * problem by adding more data and forcing arc_size to grow even
4456 	 * further past it's target size, we halt and wait for the
4457 	 * eviction thread to catch up.
4458 	 *
4459 	 * It's also possible that the reclaim thread is unable to evict
4460 	 * enough buffers to get arc_size below the overflow limit (e.g.
4461 	 * due to buffers being un-evictable, or hash lock collisions).
4462 	 * In this case, we want to proceed regardless if we're
4463 	 * overflowing; thus we don't use a while loop here.
4464 	 */
4465 	if (arc_is_overflowing()) {
4466 		mutex_enter(&arc_adjust_lock);
4467 
4468 		/*
4469 		 * Now that we've acquired the lock, we may no longer be
4470 		 * over the overflow limit, lets check.
4471 		 *
4472 		 * We're ignoring the case of spurious wake ups. If that
4473 		 * were to happen, it'd let this thread consume an ARC
4474 		 * buffer before it should have (i.e. before we're under
4475 		 * the overflow limit and were signalled by the reclaim
4476 		 * thread). As long as that is a rare occurrence, it
4477 		 * shouldn't cause any harm.
4478 		 */
4479 		if (arc_is_overflowing()) {
4480 			arc_adjust_needed = B_TRUE;
4481 			zthr_wakeup(arc_adjust_zthr);
4482 			(void) cv_wait(&arc_adjust_waiters_cv,
4483 			    &arc_adjust_lock);
4484 		}
4485 		mutex_exit(&arc_adjust_lock);
4486 	}
4487 
4488 	VERIFY3U(hdr->b_type, ==, type);
4489 	if (type == ARC_BUFC_METADATA) {
4490 		arc_space_consume(size, ARC_SPACE_META);
4491 	} else {
4492 		arc_space_consume(size, ARC_SPACE_DATA);
4493 	}
4494 
4495 	/*
4496 	 * Update the state size.  Note that ghost states have a
4497 	 * "ghost size" and so don't need to be updated.
4498 	 */
4499 	if (!GHOST_STATE(state)) {
4500 
4501 		(void) zfs_refcount_add_many(&state->arcs_size, size, tag);
4502 
4503 		/*
4504 		 * If this is reached via arc_read, the link is
4505 		 * protected by the hash lock. If reached via
4506 		 * arc_buf_alloc, the header should not be accessed by
4507 		 * any other thread. And, if reached via arc_read_done,
4508 		 * the hash lock will protect it if it's found in the
4509 		 * hash table; otherwise no other thread should be
4510 		 * trying to [add|remove]_reference it.
4511 		 */
4512 		if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4513 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4514 			(void) zfs_refcount_add_many(&state->arcs_esize[type],
4515 			    size, tag);
4516 		}
4517 
4518 		/*
4519 		 * If we are growing the cache, and we are adding anonymous
4520 		 * data, and we have outgrown arc_p, update arc_p
4521 		 */
4522 		if (aggsum_compare(&arc_size, arc_c) < 0 &&
4523 		    hdr->b_l1hdr.b_state == arc_anon &&
4524 		    (zfs_refcount_count(&arc_anon->arcs_size) +
4525 		    zfs_refcount_count(&arc_mru->arcs_size) > arc_p))
4526 			arc_p = MIN(arc_c, arc_p + size);
4527 	}
4528 }
4529 
4530 static void
4531 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
4532 {
4533 	arc_free_data_impl(hdr, size, tag);
4534 	abd_free(abd);
4535 }
4536 
4537 static void
4538 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
4539 {
4540 	arc_buf_contents_t type = arc_buf_type(hdr);
4541 
4542 	arc_free_data_impl(hdr, size, tag);
4543 	if (type == ARC_BUFC_METADATA) {
4544 		zio_buf_free(buf, size);
4545 	} else {
4546 		ASSERT(type == ARC_BUFC_DATA);
4547 		zio_data_buf_free(buf, size);
4548 	}
4549 }
4550 
4551 /*
4552  * Free the arc data buffer.
4553  */
4554 static void
4555 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
4556 {
4557 	arc_state_t *state = hdr->b_l1hdr.b_state;
4558 	arc_buf_contents_t type = arc_buf_type(hdr);
4559 
4560 	/* protected by hash lock, if in the hash table */
4561 	if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
4562 		ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4563 		ASSERT(state != arc_anon && state != arc_l2c_only);
4564 
4565 		(void) zfs_refcount_remove_many(&state->arcs_esize[type],
4566 		    size, tag);
4567 	}
4568 	(void) zfs_refcount_remove_many(&state->arcs_size, size, tag);
4569 
4570 	VERIFY3U(hdr->b_type, ==, type);
4571 	if (type == ARC_BUFC_METADATA) {
4572 		arc_space_return(size, ARC_SPACE_META);
4573 	} else {
4574 		ASSERT(type == ARC_BUFC_DATA);
4575 		arc_space_return(size, ARC_SPACE_DATA);
4576 	}
4577 }
4578 
4579 /*
4580  * This routine is called whenever a buffer is accessed.
4581  * NOTE: the hash lock is dropped in this function.
4582  */
4583 static void
4584 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
4585 {
4586 	clock_t now;
4587 
4588 	ASSERT(MUTEX_HELD(hash_lock));
4589 	ASSERT(HDR_HAS_L1HDR(hdr));
4590 
4591 	if (hdr->b_l1hdr.b_state == arc_anon) {
4592 		/*
4593 		 * This buffer is not in the cache, and does not
4594 		 * appear in our "ghost" list.  Add the new buffer
4595 		 * to the MRU state.
4596 		 */
4597 
4598 		ASSERT0(hdr->b_l1hdr.b_arc_access);
4599 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4600 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4601 		arc_change_state(arc_mru, hdr, hash_lock);
4602 
4603 	} else if (hdr->b_l1hdr.b_state == arc_mru) {
4604 		now = ddi_get_lbolt();
4605 
4606 		/*
4607 		 * If this buffer is here because of a prefetch, then either:
4608 		 * - clear the flag if this is a "referencing" read
4609 		 *   (any subsequent access will bump this into the MFU state).
4610 		 * or
4611 		 * - move the buffer to the head of the list if this is
4612 		 *   another prefetch (to make it less likely to be evicted).
4613 		 */
4614 		if (HDR_PREFETCH(hdr)) {
4615 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4616 				/* link protected by hash lock */
4617 				ASSERT(multilist_link_active(
4618 				    &hdr->b_l1hdr.b_arc_node));
4619 			} else {
4620 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4621 				ARCSTAT_BUMP(arcstat_mru_hits);
4622 			}
4623 			hdr->b_l1hdr.b_arc_access = now;
4624 			return;
4625 		}
4626 
4627 		/*
4628 		 * This buffer has been "accessed" only once so far,
4629 		 * but it is still in the cache. Move it to the MFU
4630 		 * state.
4631 		 */
4632 		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
4633 			/*
4634 			 * More than 125ms have passed since we
4635 			 * instantiated this buffer.  Move it to the
4636 			 * most frequently used state.
4637 			 */
4638 			hdr->b_l1hdr.b_arc_access = now;
4639 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4640 			arc_change_state(arc_mfu, hdr, hash_lock);
4641 		}
4642 		ARCSTAT_BUMP(arcstat_mru_hits);
4643 	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
4644 		arc_state_t	*new_state;
4645 		/*
4646 		 * This buffer has been "accessed" recently, but
4647 		 * was evicted from the cache.  Move it to the
4648 		 * MFU state.
4649 		 */
4650 
4651 		if (HDR_PREFETCH(hdr)) {
4652 			new_state = arc_mru;
4653 			if (zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
4654 				arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
4655 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
4656 		} else {
4657 			new_state = arc_mfu;
4658 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4659 		}
4660 
4661 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4662 		arc_change_state(new_state, hdr, hash_lock);
4663 
4664 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
4665 	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
4666 		/*
4667 		 * This buffer has been accessed more than once and is
4668 		 * still in the cache.  Keep it in the MFU state.
4669 		 *
4670 		 * NOTE: an add_reference() that occurred when we did
4671 		 * the arc_read() will have kicked this off the list.
4672 		 * If it was a prefetch, we will explicitly move it to
4673 		 * the head of the list now.
4674 		 */
4675 		if ((HDR_PREFETCH(hdr)) != 0) {
4676 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4677 			/* link protected by hash_lock */
4678 			ASSERT(multilist_link_active(&hdr->b_l1hdr.b_arc_node));
4679 		}
4680 		ARCSTAT_BUMP(arcstat_mfu_hits);
4681 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4682 	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
4683 		arc_state_t	*new_state = arc_mfu;
4684 		/*
4685 		 * This buffer has been accessed more than once but has
4686 		 * been evicted from the cache.  Move it back to the
4687 		 * MFU state.
4688 		 */
4689 
4690 		if (HDR_PREFETCH(hdr)) {
4691 			/*
4692 			 * This is a prefetch access...
4693 			 * move this block back to the MRU state.
4694 			 */
4695 			ASSERT0(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt));
4696 			new_state = arc_mru;
4697 		}
4698 
4699 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4700 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4701 		arc_change_state(new_state, hdr, hash_lock);
4702 
4703 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
4704 	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
4705 		/*
4706 		 * This buffer is on the 2nd Level ARC.
4707 		 */
4708 
4709 		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
4710 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
4711 		arc_change_state(arc_mfu, hdr, hash_lock);
4712 	} else {
4713 		ASSERT(!"invalid arc state");
4714 	}
4715 }
4716 
4717 /* a generic arc_done_func_t which you can use */
4718 /* ARGSUSED */
4719 void
4720 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
4721 {
4722 	if (zio == NULL || zio->io_error == 0)
4723 		bcopy(buf->b_data, arg, arc_buf_size(buf));
4724 	arc_buf_destroy(buf, arg);
4725 }
4726 
4727 /* a generic arc_done_func_t */
4728 void
4729 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
4730 {
4731 	arc_buf_t **bufp = arg;
4732 	if (buf == NULL) {
4733 		ASSERT(zio == NULL || zio->io_error != 0);
4734 		*bufp = NULL;
4735 	} else {
4736 		ASSERT(zio == NULL || zio->io_error == 0);
4737 		*bufp = buf;
4738 		ASSERT(buf->b_data != NULL);
4739 	}
4740 }
4741 
4742 static void
4743 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
4744 {
4745 	if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
4746 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
4747 		ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
4748 	} else {
4749 		if (HDR_COMPRESSION_ENABLED(hdr)) {
4750 			ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
4751 			    BP_GET_COMPRESS(bp));
4752 		}
4753 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
4754 		ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
4755 	}
4756 }
4757 
4758 static void
4759 arc_read_done(zio_t *zio)
4760 {
4761 	arc_buf_hdr_t	*hdr = zio->io_private;
4762 	kmutex_t	*hash_lock = NULL;
4763 	arc_callback_t	*callback_list;
4764 	arc_callback_t	*acb;
4765 	boolean_t	freeable = B_FALSE;
4766 	boolean_t	no_zio_error = (zio->io_error == 0);
4767 
4768 	/*
4769 	 * The hdr was inserted into hash-table and removed from lists
4770 	 * prior to starting I/O.  We should find this header, since
4771 	 * it's in the hash table, and it should be legit since it's
4772 	 * not possible to evict it during the I/O.  The only possible
4773 	 * reason for it not to be found is if we were freed during the
4774 	 * read.
4775 	 */
4776 	if (HDR_IN_HASH_TABLE(hdr)) {
4777 		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
4778 		ASSERT3U(hdr->b_dva.dva_word[0], ==,
4779 		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
4780 		ASSERT3U(hdr->b_dva.dva_word[1], ==,
4781 		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
4782 
4783 		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
4784 		    &hash_lock);
4785 
4786 		ASSERT((found == hdr &&
4787 		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
4788 		    (found == hdr && HDR_L2_READING(hdr)));
4789 		ASSERT3P(hash_lock, !=, NULL);
4790 	}
4791 
4792 	if (no_zio_error) {
4793 		/* byteswap if necessary */
4794 		if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
4795 			if (BP_GET_LEVEL(zio->io_bp) > 0) {
4796 				hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
4797 			} else {
4798 				hdr->b_l1hdr.b_byteswap =
4799 				    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
4800 			}
4801 		} else {
4802 			hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
4803 		}
4804 	}
4805 
4806 	arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
4807 	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
4808 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
4809 
4810 	callback_list = hdr->b_l1hdr.b_acb;
4811 	ASSERT3P(callback_list, !=, NULL);
4812 
4813 	if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
4814 		/*
4815 		 * Only call arc_access on anonymous buffers.  This is because
4816 		 * if we've issued an I/O for an evicted buffer, we've already
4817 		 * called arc_access (to prevent any simultaneous readers from
4818 		 * getting confused).
4819 		 */
4820 		arc_access(hdr, hash_lock);
4821 	}
4822 
4823 	/*
4824 	 * If a read request has a callback (i.e. acb_done is not NULL), then we
4825 	 * make a buf containing the data according to the parameters which were
4826 	 * passed in. The implementation of arc_buf_alloc_impl() ensures that we
4827 	 * aren't needlessly decompressing the data multiple times.
4828 	 */
4829 	int callback_cnt = 0;
4830 	for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
4831 		if (!acb->acb_done)
4832 			continue;
4833 
4834 		/* This is a demand read since prefetches don't use callbacks */
4835 		callback_cnt++;
4836 
4837 		if (no_zio_error) {
4838 			int error = arc_buf_alloc_impl(hdr, acb->acb_private,
4839 			    acb->acb_compressed, zio->io_error == 0,
4840 			    &acb->acb_buf);
4841 			if (error != 0) {
4842 				/*
4843 				 * Decompression failed.  Set io_error
4844 				 * so that when we call acb_done (below),
4845 				 * we will indicate that the read failed.
4846 				 * Note that in the unusual case where one
4847 				 * callback is compressed and another
4848 				 * uncompressed, we will mark all of them
4849 				 * as failed, even though the uncompressed
4850 				 * one can't actually fail.  In this case,
4851 				 * the hdr will not be anonymous, because
4852 				 * if there are multiple callbacks, it's
4853 				 * because multiple threads found the same
4854 				 * arc buf in the hash table.
4855 				 */
4856 				zio->io_error = error;
4857 			}
4858 		}
4859 	}
4860 	/*
4861 	 * If there are multiple callbacks, we must have the hash lock,
4862 	 * because the only way for multiple threads to find this hdr is
4863 	 * in the hash table.  This ensures that if there are multiple
4864 	 * callbacks, the hdr is not anonymous.  If it were anonymous,
4865 	 * we couldn't use arc_buf_destroy() in the error case below.
4866 	 */
4867 	ASSERT(callback_cnt < 2 || hash_lock != NULL);
4868 
4869 	hdr->b_l1hdr.b_acb = NULL;
4870 	arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
4871 	if (callback_cnt == 0) {
4872 		ASSERT(HDR_PREFETCH(hdr));
4873 		ASSERT0(hdr->b_l1hdr.b_bufcnt);
4874 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
4875 	}
4876 
4877 	ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
4878 	    callback_list != NULL);
4879 
4880 	if (no_zio_error) {
4881 		arc_hdr_verify(hdr, zio->io_bp);
4882 	} else {
4883 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
4884 		if (hdr->b_l1hdr.b_state != arc_anon)
4885 			arc_change_state(arc_anon, hdr, hash_lock);
4886 		if (HDR_IN_HASH_TABLE(hdr))
4887 			buf_hash_remove(hdr);
4888 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4889 	}
4890 
4891 	/*
4892 	 * Broadcast before we drop the hash_lock to avoid the possibility
4893 	 * that the hdr (and hence the cv) might be freed before we get to
4894 	 * the cv_broadcast().
4895 	 */
4896 	cv_broadcast(&hdr->b_l1hdr.b_cv);
4897 
4898 	if (hash_lock != NULL) {
4899 		mutex_exit(hash_lock);
4900 	} else {
4901 		/*
4902 		 * This block was freed while we waited for the read to
4903 		 * complete.  It has been removed from the hash table and
4904 		 * moved to the anonymous state (so that it won't show up
4905 		 * in the cache).
4906 		 */
4907 		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
4908 		freeable = zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
4909 	}
4910 
4911 	/* execute each callback and free its structure */
4912 	while ((acb = callback_list) != NULL) {
4913 		if (acb->acb_done != NULL) {
4914 			if (zio->io_error != 0 && acb->acb_buf != NULL) {
4915 				/*
4916 				 * If arc_buf_alloc_impl() fails during
4917 				 * decompression, the buf will still be
4918 				 * allocated, and needs to be freed here.
4919 				 */
4920 				arc_buf_destroy(acb->acb_buf, acb->acb_private);
4921 				acb->acb_buf = NULL;
4922 			}
4923 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
4924 		}
4925 
4926 		if (acb->acb_zio_dummy != NULL) {
4927 			acb->acb_zio_dummy->io_error = zio->io_error;
4928 			zio_nowait(acb->acb_zio_dummy);
4929 		}
4930 
4931 		callback_list = acb->acb_next;
4932 		kmem_free(acb, sizeof (arc_callback_t));
4933 	}
4934 
4935 	if (freeable)
4936 		arc_hdr_destroy(hdr);
4937 }
4938 
4939 /*
4940  * "Read" the block at the specified DVA (in bp) via the
4941  * cache.  If the block is found in the cache, invoke the provided
4942  * callback immediately and return.  Note that the `zio' parameter
4943  * in the callback will be NULL in this case, since no IO was
4944  * required.  If the block is not in the cache pass the read request
4945  * on to the spa with a substitute callback function, so that the
4946  * requested block will be added to the cache.
4947  *
4948  * If a read request arrives for a block that has a read in-progress,
4949  * either wait for the in-progress read to complete (and return the
4950  * results); or, if this is a read with a "done" func, add a record
4951  * to the read to invoke the "done" func when the read completes,
4952  * and return; or just return.
4953  *
4954  * arc_read_done() will invoke all the requested "done" functions
4955  * for readers of this block.
4956  */
4957 int
4958 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
4959     void *private, zio_priority_t priority, int zio_flags,
4960     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
4961 {
4962 	arc_buf_hdr_t *hdr = NULL;
4963 	kmutex_t *hash_lock = NULL;
4964 	zio_t *rzio;
4965 	uint64_t guid = spa_load_guid(spa);
4966 	boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
4967 
4968 	ASSERT(!BP_IS_EMBEDDED(bp) ||
4969 	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
4970 
4971 top:
4972 	if (!BP_IS_EMBEDDED(bp)) {
4973 		/*
4974 		 * Embedded BP's have no DVA and require no I/O to "read".
4975 		 * Create an anonymous arc buf to back it.
4976 		 */
4977 		hdr = buf_hash_find(guid, bp, &hash_lock);
4978 	}
4979 
4980 	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
4981 		arc_buf_t *buf = NULL;
4982 		*arc_flags |= ARC_FLAG_CACHED;
4983 
4984 		if (HDR_IO_IN_PROGRESS(hdr)) {
4985 
4986 			if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
4987 			    priority == ZIO_PRIORITY_SYNC_READ) {
4988 				/*
4989 				 * This sync read must wait for an
4990 				 * in-progress async read (e.g. a predictive
4991 				 * prefetch).  Async reads are queued
4992 				 * separately at the vdev_queue layer, so
4993 				 * this is a form of priority inversion.
4994 				 * Ideally, we would "inherit" the demand
4995 				 * i/o's priority by moving the i/o from
4996 				 * the async queue to the synchronous queue,
4997 				 * but there is currently no mechanism to do
4998 				 * so.  Track this so that we can evaluate
4999 				 * the magnitude of this potential performance
5000 				 * problem.
5001 				 *
5002 				 * Note that if the prefetch i/o is already
5003 				 * active (has been issued to the device),
5004 				 * the prefetch improved performance, because
5005 				 * we issued it sooner than we would have
5006 				 * without the prefetch.
5007 				 */
5008 				DTRACE_PROBE1(arc__sync__wait__for__async,
5009 				    arc_buf_hdr_t *, hdr);
5010 				ARCSTAT_BUMP(arcstat_sync_wait_for_async);
5011 			}
5012 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5013 				arc_hdr_clear_flags(hdr,
5014 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5015 			}
5016 
5017 			if (*arc_flags & ARC_FLAG_WAIT) {
5018 				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5019 				mutex_exit(hash_lock);
5020 				goto top;
5021 			}
5022 			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5023 
5024 			if (done) {
5025 				arc_callback_t *acb = NULL;
5026 
5027 				acb = kmem_zalloc(sizeof (arc_callback_t),
5028 				    KM_SLEEP);
5029 				acb->acb_done = done;
5030 				acb->acb_private = private;
5031 				acb->acb_compressed = compressed_read;
5032 				if (pio != NULL)
5033 					acb->acb_zio_dummy = zio_null(pio,
5034 					    spa, NULL, NULL, NULL, zio_flags);
5035 
5036 				ASSERT3P(acb->acb_done, !=, NULL);
5037 				acb->acb_next = hdr->b_l1hdr.b_acb;
5038 				hdr->b_l1hdr.b_acb = acb;
5039 				mutex_exit(hash_lock);
5040 				return (0);
5041 			}
5042 			mutex_exit(hash_lock);
5043 			return (0);
5044 		}
5045 
5046 		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5047 		    hdr->b_l1hdr.b_state == arc_mfu);
5048 
5049 		if (done) {
5050 			if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5051 				/*
5052 				 * This is a demand read which does not have to
5053 				 * wait for i/o because we did a predictive
5054 				 * prefetch i/o for it, which has completed.
5055 				 */
5056 				DTRACE_PROBE1(
5057 				    arc__demand__hit__predictive__prefetch,
5058 				    arc_buf_hdr_t *, hdr);
5059 				ARCSTAT_BUMP(
5060 				    arcstat_demand_hit_predictive_prefetch);
5061 				arc_hdr_clear_flags(hdr,
5062 				    ARC_FLAG_PREDICTIVE_PREFETCH);
5063 			}
5064 			ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5065 
5066 			/* Get a buf with the desired data in it. */
5067 			VERIFY0(arc_buf_alloc_impl(hdr, private,
5068 			    compressed_read, B_TRUE, &buf));
5069 		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
5070 		    zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5071 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5072 		}
5073 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5074 		arc_access(hdr, hash_lock);
5075 		if (*arc_flags & ARC_FLAG_L2CACHE)
5076 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5077 		mutex_exit(hash_lock);
5078 		ARCSTAT_BUMP(arcstat_hits);
5079 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5080 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5081 		    data, metadata, hits);
5082 
5083 		if (done)
5084 			done(NULL, buf, private);
5085 	} else {
5086 		uint64_t lsize = BP_GET_LSIZE(bp);
5087 		uint64_t psize = BP_GET_PSIZE(bp);
5088 		arc_callback_t *acb;
5089 		vdev_t *vd = NULL;
5090 		uint64_t addr = 0;
5091 		boolean_t devw = B_FALSE;
5092 		uint64_t size;
5093 
5094 		if (hdr == NULL) {
5095 			/* this block is not in the cache */
5096 			arc_buf_hdr_t *exists = NULL;
5097 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5098 			hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5099 			    BP_GET_COMPRESS(bp), type);
5100 
5101 			if (!BP_IS_EMBEDDED(bp)) {
5102 				hdr->b_dva = *BP_IDENTITY(bp);
5103 				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5104 				exists = buf_hash_insert(hdr, &hash_lock);
5105 			}
5106 			if (exists != NULL) {
5107 				/* somebody beat us to the hash insert */
5108 				mutex_exit(hash_lock);
5109 				buf_discard_identity(hdr);
5110 				arc_hdr_destroy(hdr);
5111 				goto top; /* restart the IO request */
5112 			}
5113 		} else {
5114 			/*
5115 			 * This block is in the ghost cache. If it was L2-only
5116 			 * (and thus didn't have an L1 hdr), we realloc the
5117 			 * header to add an L1 hdr.
5118 			 */
5119 			if (!HDR_HAS_L1HDR(hdr)) {
5120 				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5121 				    hdr_full_cache);
5122 			}
5123 			ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5124 			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5125 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5126 			ASSERT(zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5127 			ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5128 			ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5129 
5130 			/*
5131 			 * This is a delicate dance that we play here.
5132 			 * This hdr is in the ghost list so we access it
5133 			 * to move it out of the ghost list before we
5134 			 * initiate the read. If it's a prefetch then
5135 			 * it won't have a callback so we'll remove the
5136 			 * reference that arc_buf_alloc_impl() created. We
5137 			 * do this after we've called arc_access() to
5138 			 * avoid hitting an assert in remove_reference().
5139 			 */
5140 			arc_access(hdr, hash_lock);
5141 			arc_hdr_alloc_pabd(hdr);
5142 		}
5143 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5144 		size = arc_hdr_size(hdr);
5145 
5146 		/*
5147 		 * If compression is enabled on the hdr, then will do
5148 		 * RAW I/O and will store the compressed data in the hdr's
5149 		 * data block. Otherwise, the hdr's data block will contain
5150 		 * the uncompressed data.
5151 		 */
5152 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5153 			zio_flags |= ZIO_FLAG_RAW;
5154 		}
5155 
5156 		if (*arc_flags & ARC_FLAG_PREFETCH)
5157 			arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5158 		if (*arc_flags & ARC_FLAG_L2CACHE)
5159 			arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5160 		if (BP_GET_LEVEL(bp) > 0)
5161 			arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5162 		if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5163 			arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5164 		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5165 
5166 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5167 		acb->acb_done = done;
5168 		acb->acb_private = private;
5169 		acb->acb_compressed = compressed_read;
5170 
5171 		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5172 		hdr->b_l1hdr.b_acb = acb;
5173 		arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5174 
5175 		if (HDR_HAS_L2HDR(hdr) &&
5176 		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5177 			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5178 			addr = hdr->b_l2hdr.b_daddr;
5179 			/*
5180 			 * Lock out L2ARC device removal.
5181 			 */
5182 			if (vdev_is_dead(vd) ||
5183 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5184 				vd = NULL;
5185 		}
5186 
5187 		if (priority == ZIO_PRIORITY_ASYNC_READ)
5188 			arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5189 		else
5190 			arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5191 
5192 		if (hash_lock != NULL)
5193 			mutex_exit(hash_lock);
5194 
5195 		/*
5196 		 * At this point, we have a level 1 cache miss.  Try again in
5197 		 * L2ARC if possible.
5198 		 */
5199 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5200 
5201 		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5202 		    uint64_t, lsize, zbookmark_phys_t *, zb);
5203 		ARCSTAT_BUMP(arcstat_misses);
5204 		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5205 		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5206 		    data, metadata, misses);
5207 
5208 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5209 			/*
5210 			 * Read from the L2ARC if the following are true:
5211 			 * 1. The L2ARC vdev was previously cached.
5212 			 * 2. This buffer still has L2ARC metadata.
5213 			 * 3. This buffer isn't currently writing to the L2ARC.
5214 			 * 4. The L2ARC entry wasn't evicted, which may
5215 			 *    also have invalidated the vdev.
5216 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
5217 			 */
5218 			if (HDR_HAS_L2HDR(hdr) &&
5219 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5220 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5221 				l2arc_read_callback_t *cb;
5222 				abd_t *abd;
5223 				uint64_t asize;
5224 
5225 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5226 				ARCSTAT_BUMP(arcstat_l2_hits);
5227 
5228 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5229 				    KM_SLEEP);
5230 				cb->l2rcb_hdr = hdr;
5231 				cb->l2rcb_bp = *bp;
5232 				cb->l2rcb_zb = *zb;
5233 				cb->l2rcb_flags = zio_flags;
5234 
5235 				asize = vdev_psize_to_asize(vd, size);
5236 				if (asize != size) {
5237 					abd = abd_alloc_for_io(asize,
5238 					    HDR_ISTYPE_METADATA(hdr));
5239 					cb->l2rcb_abd = abd;
5240 				} else {
5241 					abd = hdr->b_l1hdr.b_pabd;
5242 				}
5243 
5244 				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
5245 				    addr + asize <= vd->vdev_psize -
5246 				    VDEV_LABEL_END_SIZE);
5247 
5248 				/*
5249 				 * l2arc read.  The SCL_L2ARC lock will be
5250 				 * released by l2arc_read_done().
5251 				 * Issue a null zio if the underlying buffer
5252 				 * was squashed to zero size by compression.
5253 				 */
5254 				ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
5255 				    ZIO_COMPRESS_EMPTY);
5256 				rzio = zio_read_phys(pio, vd, addr,
5257 				    asize, abd,
5258 				    ZIO_CHECKSUM_OFF,
5259 				    l2arc_read_done, cb, priority,
5260 				    zio_flags | ZIO_FLAG_DONT_CACHE |
5261 				    ZIO_FLAG_CANFAIL |
5262 				    ZIO_FLAG_DONT_PROPAGATE |
5263 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
5264 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
5265 				    zio_t *, rzio);
5266 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
5267 
5268 				if (*arc_flags & ARC_FLAG_NOWAIT) {
5269 					zio_nowait(rzio);
5270 					return (0);
5271 				}
5272 
5273 				ASSERT(*arc_flags & ARC_FLAG_WAIT);
5274 				if (zio_wait(rzio) == 0)
5275 					return (0);
5276 
5277 				/* l2arc read error; goto zio_read() */
5278 			} else {
5279 				DTRACE_PROBE1(l2arc__miss,
5280 				    arc_buf_hdr_t *, hdr);
5281 				ARCSTAT_BUMP(arcstat_l2_misses);
5282 				if (HDR_L2_WRITING(hdr))
5283 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
5284 				spa_config_exit(spa, SCL_L2ARC, vd);
5285 			}
5286 		} else {
5287 			if (vd != NULL)
5288 				spa_config_exit(spa, SCL_L2ARC, vd);
5289 			if (l2arc_ndev != 0) {
5290 				DTRACE_PROBE1(l2arc__miss,
5291 				    arc_buf_hdr_t *, hdr);
5292 				ARCSTAT_BUMP(arcstat_l2_misses);
5293 			}
5294 		}
5295 
5296 		rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
5297 		    arc_read_done, hdr, priority, zio_flags, zb);
5298 
5299 		if (*arc_flags & ARC_FLAG_WAIT)
5300 			return (zio_wait(rzio));
5301 
5302 		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5303 		zio_nowait(rzio);
5304 	}
5305 	return (0);
5306 }
5307 
5308 /*
5309  * Notify the arc that a block was freed, and thus will never be used again.
5310  */
5311 void
5312 arc_freed(spa_t *spa, const blkptr_t *bp)
5313 {
5314 	arc_buf_hdr_t *hdr;
5315 	kmutex_t *hash_lock;
5316 	uint64_t guid = spa_load_guid(spa);
5317 
5318 	ASSERT(!BP_IS_EMBEDDED(bp));
5319 
5320 	hdr = buf_hash_find(guid, bp, &hash_lock);
5321 	if (hdr == NULL)
5322 		return;
5323 
5324 	/*
5325 	 * We might be trying to free a block that is still doing I/O
5326 	 * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
5327 	 * dmu_sync-ed block). If this block is being prefetched, then it
5328 	 * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
5329 	 * until the I/O completes. A block may also have a reference if it is
5330 	 * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
5331 	 * have written the new block to its final resting place on disk but
5332 	 * without the dedup flag set. This would have left the hdr in the MRU
5333 	 * state and discoverable. When the txg finally syncs it detects that
5334 	 * the block was overridden in open context and issues an override I/O.
5335 	 * Since this is a dedup block, the override I/O will determine if the
5336 	 * block is already in the DDT. If so, then it will replace the io_bp
5337 	 * with the bp from the DDT and allow the I/O to finish. When the I/O
5338 	 * reaches the done callback, dbuf_write_override_done, it will
5339 	 * check to see if the io_bp and io_bp_override are identical.
5340 	 * If they are not, then it indicates that the bp was replaced with
5341 	 * the bp in the DDT and the override bp is freed. This allows
5342 	 * us to arrive here with a reference on a block that is being
5343 	 * freed. So if we have an I/O in progress, or a reference to
5344 	 * this hdr, then we don't destroy the hdr.
5345 	 */
5346 	if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
5347 	    zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
5348 		arc_change_state(arc_anon, hdr, hash_lock);
5349 		arc_hdr_destroy(hdr);
5350 		mutex_exit(hash_lock);
5351 	} else {
5352 		mutex_exit(hash_lock);
5353 	}
5354 
5355 }
5356 
5357 /*
5358  * Release this buffer from the cache, making it an anonymous buffer.  This
5359  * must be done after a read and prior to modifying the buffer contents.
5360  * If the buffer has more than one reference, we must make
5361  * a new hdr for the buffer.
5362  */
5363 void
5364 arc_release(arc_buf_t *buf, void *tag)
5365 {
5366 	arc_buf_hdr_t *hdr = buf->b_hdr;
5367 
5368 	/*
5369 	 * It would be nice to assert that if it's DMU metadata (level >
5370 	 * 0 || it's the dnode file), then it must be syncing context.
5371 	 * But we don't know that information at this level.
5372 	 */
5373 
5374 	mutex_enter(&buf->b_evict_lock);
5375 
5376 	ASSERT(HDR_HAS_L1HDR(hdr));
5377 
5378 	/*
5379 	 * We don't grab the hash lock prior to this check, because if
5380 	 * the buffer's header is in the arc_anon state, it won't be
5381 	 * linked into the hash table.
5382 	 */
5383 	if (hdr->b_l1hdr.b_state == arc_anon) {
5384 		mutex_exit(&buf->b_evict_lock);
5385 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5386 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
5387 		ASSERT(!HDR_HAS_L2HDR(hdr));
5388 		ASSERT(HDR_EMPTY(hdr));
5389 
5390 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5391 		ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
5392 		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
5393 
5394 		hdr->b_l1hdr.b_arc_access = 0;
5395 
5396 		/*
5397 		 * If the buf is being overridden then it may already
5398 		 * have a hdr that is not empty.
5399 		 */
5400 		buf_discard_identity(hdr);
5401 		arc_buf_thaw(buf);
5402 
5403 		return;
5404 	}
5405 
5406 	kmutex_t *hash_lock = HDR_LOCK(hdr);
5407 	mutex_enter(hash_lock);
5408 
5409 	/*
5410 	 * This assignment is only valid as long as the hash_lock is
5411 	 * held, we must be careful not to reference state or the
5412 	 * b_state field after dropping the lock.
5413 	 */
5414 	arc_state_t *state = hdr->b_l1hdr.b_state;
5415 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5416 	ASSERT3P(state, !=, arc_anon);
5417 
5418 	/* this buffer is not on any list */
5419 	ASSERT3S(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
5420 
5421 	if (HDR_HAS_L2HDR(hdr)) {
5422 		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5423 
5424 		/*
5425 		 * We have to recheck this conditional again now that
5426 		 * we're holding the l2ad_mtx to prevent a race with
5427 		 * another thread which might be concurrently calling
5428 		 * l2arc_evict(). In that case, l2arc_evict() might have
5429 		 * destroyed the header's L2 portion as we were waiting
5430 		 * to acquire the l2ad_mtx.
5431 		 */
5432 		if (HDR_HAS_L2HDR(hdr))
5433 			arc_hdr_l2hdr_destroy(hdr);
5434 
5435 		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
5436 	}
5437 
5438 	/*
5439 	 * Do we have more than one buf?
5440 	 */
5441 	if (hdr->b_l1hdr.b_bufcnt > 1) {
5442 		arc_buf_hdr_t *nhdr;
5443 		uint64_t spa = hdr->b_spa;
5444 		uint64_t psize = HDR_GET_PSIZE(hdr);
5445 		uint64_t lsize = HDR_GET_LSIZE(hdr);
5446 		enum zio_compress compress = HDR_GET_COMPRESS(hdr);
5447 		arc_buf_contents_t type = arc_buf_type(hdr);
5448 		VERIFY3U(hdr->b_type, ==, type);
5449 
5450 		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
5451 		(void) remove_reference(hdr, hash_lock, tag);
5452 
5453 		if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
5454 			ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
5455 			ASSERT(ARC_BUF_LAST(buf));
5456 		}
5457 
5458 		/*
5459 		 * Pull the data off of this hdr and attach it to
5460 		 * a new anonymous hdr. Also find the last buffer
5461 		 * in the hdr's buffer list.
5462 		 */
5463 		arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
5464 		ASSERT3P(lastbuf, !=, NULL);
5465 
5466 		/*
5467 		 * If the current arc_buf_t and the hdr are sharing their data
5468 		 * buffer, then we must stop sharing that block.
5469 		 */
5470 		if (arc_buf_is_shared(buf)) {
5471 			VERIFY(!arc_buf_is_shared(lastbuf));
5472 
5473 			/*
5474 			 * First, sever the block sharing relationship between
5475 			 * buf and the arc_buf_hdr_t.
5476 			 */
5477 			arc_unshare_buf(hdr, buf);
5478 
5479 			/*
5480 			 * Now we need to recreate the hdr's b_pabd. Since we
5481 			 * have lastbuf handy, we try to share with it, but if
5482 			 * we can't then we allocate a new b_pabd and copy the
5483 			 * data from buf into it.
5484 			 */
5485 			if (arc_can_share(hdr, lastbuf)) {
5486 				arc_share_buf(hdr, lastbuf);
5487 			} else {
5488 				arc_hdr_alloc_pabd(hdr);
5489 				abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
5490 				    buf->b_data, psize);
5491 			}
5492 			VERIFY3P(lastbuf->b_data, !=, NULL);
5493 		} else if (HDR_SHARED_DATA(hdr)) {
5494 			/*
5495 			 * Uncompressed shared buffers are always at the end
5496 			 * of the list. Compressed buffers don't have the
5497 			 * same requirements. This makes it hard to
5498 			 * simply assert that the lastbuf is shared so
5499 			 * we rely on the hdr's compression flags to determine
5500 			 * if we have a compressed, shared buffer.
5501 			 */
5502 			ASSERT(arc_buf_is_shared(lastbuf) ||
5503 			    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
5504 			ASSERT(!ARC_BUF_SHARED(buf));
5505 		}
5506 		ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5507 		ASSERT3P(state, !=, arc_l2c_only);
5508 
5509 		(void) zfs_refcount_remove_many(&state->arcs_size,
5510 		    arc_buf_size(buf), buf);
5511 
5512 		if (zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
5513 			ASSERT3P(state, !=, arc_l2c_only);
5514 			(void) zfs_refcount_remove_many(
5515 			    &state->arcs_esize[type],
5516 			    arc_buf_size(buf), buf);
5517 		}
5518 
5519 		hdr->b_l1hdr.b_bufcnt -= 1;
5520 		arc_cksum_verify(buf);
5521 		arc_buf_unwatch(buf);
5522 
5523 		mutex_exit(hash_lock);
5524 
5525 		/*
5526 		 * Allocate a new hdr. The new hdr will contain a b_pabd
5527 		 * buffer which will be freed in arc_write().
5528 		 */
5529 		nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
5530 		ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
5531 		ASSERT0(nhdr->b_l1hdr.b_bufcnt);
5532 		ASSERT0(zfs_refcount_count(&nhdr->b_l1hdr.b_refcnt));
5533 		VERIFY3U(nhdr->b_type, ==, type);
5534 		ASSERT(!HDR_SHARED_DATA(nhdr));
5535 
5536 		nhdr->b_l1hdr.b_buf = buf;
5537 		nhdr->b_l1hdr.b_bufcnt = 1;
5538 		(void) zfs_refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
5539 		buf->b_hdr = nhdr;
5540 
5541 		mutex_exit(&buf->b_evict_lock);
5542 		(void) zfs_refcount_add_many(&arc_anon->arcs_size,
5543 		    arc_buf_size(buf), buf);
5544 	} else {
5545 		mutex_exit(&buf->b_evict_lock);
5546 		ASSERT(zfs_refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
5547 		/* protected by hash lock, or hdr is on arc_anon */
5548 		ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
5549 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5550 		arc_change_state(arc_anon, hdr, hash_lock);
5551 		hdr->b_l1hdr.b_arc_access = 0;
5552 		mutex_exit(hash_lock);
5553 
5554 		buf_discard_identity(hdr);
5555 		arc_buf_thaw(buf);
5556 	}
5557 }
5558 
5559 int
5560 arc_released(arc_buf_t *buf)
5561 {
5562 	int released;
5563 
5564 	mutex_enter(&buf->b_evict_lock);
5565 	released = (buf->b_data != NULL &&
5566 	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
5567 	mutex_exit(&buf->b_evict_lock);
5568 	return (released);
5569 }
5570 
5571 #ifdef ZFS_DEBUG
5572 int
5573 arc_referenced(arc_buf_t *buf)
5574 {
5575 	int referenced;
5576 
5577 	mutex_enter(&buf->b_evict_lock);
5578 	referenced = (zfs_refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
5579 	mutex_exit(&buf->b_evict_lock);
5580 	return (referenced);
5581 }
5582 #endif
5583 
5584 static void
5585 arc_write_ready(zio_t *zio)
5586 {
5587 	arc_write_callback_t *callback = zio->io_private;
5588 	arc_buf_t *buf = callback->awcb_buf;
5589 	arc_buf_hdr_t *hdr = buf->b_hdr;
5590 	uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
5591 
5592 	ASSERT(HDR_HAS_L1HDR(hdr));
5593 	ASSERT(!zfs_refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
5594 	ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
5595 
5596 	/*
5597 	 * If we're reexecuting this zio because the pool suspended, then
5598 	 * cleanup any state that was previously set the first time the
5599 	 * callback was invoked.
5600 	 */
5601 	if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
5602 		arc_cksum_free(hdr);
5603 		arc_buf_unwatch(buf);
5604 		if (hdr->b_l1hdr.b_pabd != NULL) {
5605 			if (arc_buf_is_shared(buf)) {
5606 				arc_unshare_buf(hdr, buf);
5607 			} else {
5608 				arc_hdr_free_pabd(hdr);
5609 			}
5610 		}
5611 	}
5612 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5613 	ASSERT(!HDR_SHARED_DATA(hdr));
5614 	ASSERT(!arc_buf_is_shared(buf));
5615 
5616 	callback->awcb_ready(zio, buf, callback->awcb_private);
5617 
5618 	if (HDR_IO_IN_PROGRESS(hdr))
5619 		ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
5620 
5621 	arc_cksum_compute(buf);
5622 	arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5623 
5624 	enum zio_compress compress;
5625 	if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5626 		compress = ZIO_COMPRESS_OFF;
5627 	} else {
5628 		ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
5629 		compress = BP_GET_COMPRESS(zio->io_bp);
5630 	}
5631 	HDR_SET_PSIZE(hdr, psize);
5632 	arc_hdr_set_compress(hdr, compress);
5633 
5634 
5635 	/*
5636 	 * Fill the hdr with data. If the hdr is compressed, the data we want
5637 	 * is available from the zio, otherwise we can take it from the buf.
5638 	 *
5639 	 * We might be able to share the buf's data with the hdr here. However,
5640 	 * doing so would cause the ARC to be full of linear ABDs if we write a
5641 	 * lot of shareable data. As a compromise, we check whether scattered
5642 	 * ABDs are allowed, and assume that if they are then the user wants
5643 	 * the ARC to be primarily filled with them regardless of the data being
5644 	 * written. Therefore, if they're allowed then we allocate one and copy
5645 	 * the data into it; otherwise, we share the data directly if we can.
5646 	 */
5647 	if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
5648 		arc_hdr_alloc_pabd(hdr);
5649 
5650 		/*
5651 		 * Ideally, we would always copy the io_abd into b_pabd, but the
5652 		 * user may have disabled compressed ARC, thus we must check the
5653 		 * hdr's compression setting rather than the io_bp's.
5654 		 */
5655 		if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5656 			ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
5657 			    ZIO_COMPRESS_OFF);
5658 			ASSERT3U(psize, >, 0);
5659 
5660 			abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
5661 		} else {
5662 			ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
5663 
5664 			abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
5665 			    arc_buf_size(buf));
5666 		}
5667 	} else {
5668 		ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
5669 		ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
5670 		ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
5671 
5672 		arc_share_buf(hdr, buf);
5673 	}
5674 
5675 	arc_hdr_verify(hdr, zio->io_bp);
5676 }
5677 
5678 static void
5679 arc_write_children_ready(zio_t *zio)
5680 {
5681 	arc_write_callback_t *callback = zio->io_private;
5682 	arc_buf_t *buf = callback->awcb_buf;
5683 
5684 	callback->awcb_children_ready(zio, buf, callback->awcb_private);
5685 }
5686 
5687 /*
5688  * The SPA calls this callback for each physical write that happens on behalf
5689  * of a logical write.  See the comment in dbuf_write_physdone() for details.
5690  */
5691 static void
5692 arc_write_physdone(zio_t *zio)
5693 {
5694 	arc_write_callback_t *cb = zio->io_private;
5695 	if (cb->awcb_physdone != NULL)
5696 		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
5697 }
5698 
5699 static void
5700 arc_write_done(zio_t *zio)
5701 {
5702 	arc_write_callback_t *callback = zio->io_private;
5703 	arc_buf_t *buf = callback->awcb_buf;
5704 	arc_buf_hdr_t *hdr = buf->b_hdr;
5705 
5706 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5707 
5708 	if (zio->io_error == 0) {
5709 		arc_hdr_verify(hdr, zio->io_bp);
5710 
5711 		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
5712 			buf_discard_identity(hdr);
5713 		} else {
5714 			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
5715 			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
5716 		}
5717 	} else {
5718 		ASSERT(HDR_EMPTY(hdr));
5719 	}
5720 
5721 	/*
5722 	 * If the block to be written was all-zero or compressed enough to be
5723 	 * embedded in the BP, no write was performed so there will be no
5724 	 * dva/birth/checksum.  The buffer must therefore remain anonymous
5725 	 * (and uncached).
5726 	 */
5727 	if (!HDR_EMPTY(hdr)) {
5728 		arc_buf_hdr_t *exists;
5729 		kmutex_t *hash_lock;
5730 
5731 		ASSERT3U(zio->io_error, ==, 0);
5732 
5733 		arc_cksum_verify(buf);
5734 
5735 		exists = buf_hash_insert(hdr, &hash_lock);
5736 		if (exists != NULL) {
5737 			/*
5738 			 * This can only happen if we overwrite for
5739 			 * sync-to-convergence, because we remove
5740 			 * buffers from the hash table when we arc_free().
5741 			 */
5742 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
5743 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5744 					panic("bad overwrite, hdr=%p exists=%p",
5745 					    (void *)hdr, (void *)exists);
5746 				ASSERT(zfs_refcount_is_zero(
5747 				    &exists->b_l1hdr.b_refcnt));
5748 				arc_change_state(arc_anon, exists, hash_lock);
5749 				mutex_exit(hash_lock);
5750 				arc_hdr_destroy(exists);
5751 				exists = buf_hash_insert(hdr, &hash_lock);
5752 				ASSERT3P(exists, ==, NULL);
5753 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
5754 				/* nopwrite */
5755 				ASSERT(zio->io_prop.zp_nopwrite);
5756 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
5757 					panic("bad nopwrite, hdr=%p exists=%p",
5758 					    (void *)hdr, (void *)exists);
5759 			} else {
5760 				/* Dedup */
5761 				ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
5762 				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
5763 				ASSERT(BP_GET_DEDUP(zio->io_bp));
5764 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
5765 			}
5766 		}
5767 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5768 		/* if it's not anon, we are doing a scrub */
5769 		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
5770 			arc_access(hdr, hash_lock);
5771 		mutex_exit(hash_lock);
5772 	} else {
5773 		arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5774 	}
5775 
5776 	ASSERT(!zfs_refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5777 	callback->awcb_done(zio, buf, callback->awcb_private);
5778 
5779 	abd_put(zio->io_abd);
5780 	kmem_free(callback, sizeof (arc_write_callback_t));
5781 }
5782 
5783 zio_t *
5784 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
5785     boolean_t l2arc, const zio_prop_t *zp, arc_done_func_t *ready,
5786     arc_done_func_t *children_ready, arc_done_func_t *physdone,
5787     arc_done_func_t *done, void *private, zio_priority_t priority,
5788     int zio_flags, const zbookmark_phys_t *zb)
5789 {
5790 	arc_buf_hdr_t *hdr = buf->b_hdr;
5791 	arc_write_callback_t *callback;
5792 	zio_t *zio;
5793 	zio_prop_t localprop = *zp;
5794 
5795 	ASSERT3P(ready, !=, NULL);
5796 	ASSERT3P(done, !=, NULL);
5797 	ASSERT(!HDR_IO_ERROR(hdr));
5798 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5799 	ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5800 	ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
5801 	if (l2arc)
5802 		arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5803 	if (ARC_BUF_COMPRESSED(buf)) {
5804 		/*
5805 		 * We're writing a pre-compressed buffer.  Make the
5806 		 * compression algorithm requested by the zio_prop_t match
5807 		 * the pre-compressed buffer's compression algorithm.
5808 		 */
5809 		localprop.zp_compress = HDR_GET_COMPRESS(hdr);
5810 
5811 		ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
5812 		zio_flags |= ZIO_FLAG_RAW;
5813 	}
5814 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
5815 	callback->awcb_ready = ready;
5816 	callback->awcb_children_ready = children_ready;
5817 	callback->awcb_physdone = physdone;
5818 	callback->awcb_done = done;
5819 	callback->awcb_private = private;
5820 	callback->awcb_buf = buf;
5821 
5822 	/*
5823 	 * The hdr's b_pabd is now stale, free it now. A new data block
5824 	 * will be allocated when the zio pipeline calls arc_write_ready().
5825 	 */
5826 	if (hdr->b_l1hdr.b_pabd != NULL) {
5827 		/*
5828 		 * If the buf is currently sharing the data block with
5829 		 * the hdr then we need to break that relationship here.
5830 		 * The hdr will remain with a NULL data pointer and the
5831 		 * buf will take sole ownership of the block.
5832 		 */
5833 		if (arc_buf_is_shared(buf)) {
5834 			arc_unshare_buf(hdr, buf);
5835 		} else {
5836 			arc_hdr_free_pabd(hdr);
5837 		}
5838 		VERIFY3P(buf->b_data, !=, NULL);
5839 		arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
5840 	}
5841 	ASSERT(!arc_buf_is_shared(buf));
5842 	ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5843 
5844 	zio = zio_write(pio, spa, txg, bp,
5845 	    abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
5846 	    HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
5847 	    (children_ready != NULL) ? arc_write_children_ready : NULL,
5848 	    arc_write_physdone, arc_write_done, callback,
5849 	    priority, zio_flags, zb);
5850 
5851 	return (zio);
5852 }
5853 
5854 static int
5855 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
5856 {
5857 #ifdef _KERNEL
5858 	uint64_t available_memory = ptob(freemem);
5859 
5860 #if defined(__i386)
5861 	available_memory =
5862 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
5863 #endif
5864 
5865 	if (freemem > physmem * arc_lotsfree_percent / 100)
5866 		return (0);
5867 
5868 	if (txg > spa->spa_lowmem_last_txg) {
5869 		spa->spa_lowmem_last_txg = txg;
5870 		spa->spa_lowmem_page_load = 0;
5871 	}
5872 	/*
5873 	 * If we are in pageout, we know that memory is already tight,
5874 	 * the arc is already going to be evicting, so we just want to
5875 	 * continue to let page writes occur as quickly as possible.
5876 	 */
5877 	if (curproc == proc_pageout) {
5878 		if (spa->spa_lowmem_page_load >
5879 		    MAX(ptob(minfree), available_memory) / 4)
5880 			return (SET_ERROR(ERESTART));
5881 		/* Note: reserve is inflated, so we deflate */
5882 		atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
5883 		return (0);
5884 	} else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
5885 		/* memory is low, delay before restarting */
5886 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
5887 		return (SET_ERROR(EAGAIN));
5888 	}
5889 	spa->spa_lowmem_page_load = 0;
5890 #endif /* _KERNEL */
5891 	return (0);
5892 }
5893 
5894 void
5895 arc_tempreserve_clear(uint64_t reserve)
5896 {
5897 	atomic_add_64(&arc_tempreserve, -reserve);
5898 	ASSERT((int64_t)arc_tempreserve >= 0);
5899 }
5900 
5901 int
5902 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
5903 {
5904 	int error;
5905 	uint64_t anon_size;
5906 
5907 	if (reserve > arc_c/4 && !arc_no_grow)
5908 		arc_c = MIN(arc_c_max, reserve * 4);
5909 	if (reserve > arc_c)
5910 		return (SET_ERROR(ENOMEM));
5911 
5912 	/*
5913 	 * Don't count loaned bufs as in flight dirty data to prevent long
5914 	 * network delays from blocking transactions that are ready to be
5915 	 * assigned to a txg.
5916 	 */
5917 
5918 	/* assert that it has not wrapped around */
5919 	ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
5920 
5921 	anon_size = MAX((int64_t)(zfs_refcount_count(&arc_anon->arcs_size) -
5922 	    arc_loaned_bytes), 0);
5923 
5924 	/*
5925 	 * Writes will, almost always, require additional memory allocations
5926 	 * in order to compress/encrypt/etc the data.  We therefore need to
5927 	 * make sure that there is sufficient available memory for this.
5928 	 */
5929 	error = arc_memory_throttle(spa, reserve, txg);
5930 	if (error != 0)
5931 		return (error);
5932 
5933 	/*
5934 	 * Throttle writes when the amount of dirty data in the cache
5935 	 * gets too large.  We try to keep the cache less than half full
5936 	 * of dirty blocks so that our sync times don't grow too large.
5937 	 *
5938 	 * In the case of one pool being built on another pool, we want
5939 	 * to make sure we don't end up throttling the lower (backing)
5940 	 * pool when the upper pool is the majority contributor to dirty
5941 	 * data. To insure we make forward progress during throttling, we
5942 	 * also check the current pool's net dirty data and only throttle
5943 	 * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
5944 	 * data in the cache.
5945 	 *
5946 	 * Note: if two requests come in concurrently, we might let them
5947 	 * both succeed, when one of them should fail.  Not a huge deal.
5948 	 */
5949 	uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
5950 	uint64_t spa_dirty_anon = spa_dirty_data(spa);
5951 
5952 	if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
5953 	    anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
5954 	    spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
5955 		uint64_t meta_esize =
5956 		    zfs_refcount_count(
5957 		    &arc_anon->arcs_esize[ARC_BUFC_METADATA]);
5958 		uint64_t data_esize =
5959 		    zfs_refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
5960 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
5961 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
5962 		    arc_tempreserve >> 10, meta_esize >> 10,
5963 		    data_esize >> 10, reserve >> 10, arc_c >> 10);
5964 		return (SET_ERROR(ERESTART));
5965 	}
5966 	atomic_add_64(&arc_tempreserve, reserve);
5967 	return (0);
5968 }
5969 
5970 static void
5971 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
5972     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
5973 {
5974 	size->value.ui64 = zfs_refcount_count(&state->arcs_size);
5975 	evict_data->value.ui64 =
5976 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
5977 	evict_metadata->value.ui64 =
5978 	    zfs_refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
5979 }
5980 
5981 static int
5982 arc_kstat_update(kstat_t *ksp, int rw)
5983 {
5984 	arc_stats_t *as = ksp->ks_data;
5985 
5986 	if (rw == KSTAT_WRITE) {
5987 		return (EACCES);
5988 	} else {
5989 		arc_kstat_update_state(arc_anon,
5990 		    &as->arcstat_anon_size,
5991 		    &as->arcstat_anon_evictable_data,
5992 		    &as->arcstat_anon_evictable_metadata);
5993 		arc_kstat_update_state(arc_mru,
5994 		    &as->arcstat_mru_size,
5995 		    &as->arcstat_mru_evictable_data,
5996 		    &as->arcstat_mru_evictable_metadata);
5997 		arc_kstat_update_state(arc_mru_ghost,
5998 		    &as->arcstat_mru_ghost_size,
5999 		    &as->arcstat_mru_ghost_evictable_data,
6000 		    &as->arcstat_mru_ghost_evictable_metadata);
6001 		arc_kstat_update_state(arc_mfu,
6002 		    &as->arcstat_mfu_size,
6003 		    &as->arcstat_mfu_evictable_data,
6004 		    &as->arcstat_mfu_evictable_metadata);
6005 		arc_kstat_update_state(arc_mfu_ghost,
6006 		    &as->arcstat_mfu_ghost_size,
6007 		    &as->arcstat_mfu_ghost_evictable_data,
6008 		    &as->arcstat_mfu_ghost_evictable_metadata);
6009 
6010 		ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6011 		ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6012 		ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6013 		ARCSTAT(arcstat_metadata_size) =
6014 		    aggsum_value(&astat_metadata_size);
6015 		ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6016 		ARCSTAT(arcstat_other_size) = aggsum_value(&astat_other_size);
6017 		ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6018 	}
6019 
6020 	return (0);
6021 }
6022 
6023 /*
6024  * This function *must* return indices evenly distributed between all
6025  * sublists of the multilist. This is needed due to how the ARC eviction
6026  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6027  * distributed between all sublists and uses this assumption when
6028  * deciding which sublist to evict from and how much to evict from it.
6029  */
6030 unsigned int
6031 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6032 {
6033 	arc_buf_hdr_t *hdr = obj;
6034 
6035 	/*
6036 	 * We rely on b_dva to generate evenly distributed index
6037 	 * numbers using buf_hash below. So, as an added precaution,
6038 	 * let's make sure we never add empty buffers to the arc lists.
6039 	 */
6040 	ASSERT(!HDR_EMPTY(hdr));
6041 
6042 	/*
6043 	 * The assumption here, is the hash value for a given
6044 	 * arc_buf_hdr_t will remain constant throughout it's lifetime
6045 	 * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6046 	 * Thus, we don't need to store the header's sublist index
6047 	 * on insertion, as this index can be recalculated on removal.
6048 	 *
6049 	 * Also, the low order bits of the hash value are thought to be
6050 	 * distributed evenly. Otherwise, in the case that the multilist
6051 	 * has a power of two number of sublists, each sublists' usage
6052 	 * would not be evenly distributed.
6053 	 */
6054 	return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6055 	    multilist_get_num_sublists(ml));
6056 }
6057 
6058 static void
6059 arc_state_init(void)
6060 {
6061 	arc_anon = &ARC_anon;
6062 	arc_mru = &ARC_mru;
6063 	arc_mru_ghost = &ARC_mru_ghost;
6064 	arc_mfu = &ARC_mfu;
6065 	arc_mfu_ghost = &ARC_mfu_ghost;
6066 	arc_l2c_only = &ARC_l2c_only;
6067 
6068 	arc_mru->arcs_list[ARC_BUFC_METADATA] =
6069 	    multilist_create(sizeof (arc_buf_hdr_t),
6070 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6071 	    arc_state_multilist_index_func);
6072 	arc_mru->arcs_list[ARC_BUFC_DATA] =
6073 	    multilist_create(sizeof (arc_buf_hdr_t),
6074 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6075 	    arc_state_multilist_index_func);
6076 	arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6077 	    multilist_create(sizeof (arc_buf_hdr_t),
6078 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6079 	    arc_state_multilist_index_func);
6080 	arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6081 	    multilist_create(sizeof (arc_buf_hdr_t),
6082 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6083 	    arc_state_multilist_index_func);
6084 	arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6085 	    multilist_create(sizeof (arc_buf_hdr_t),
6086 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6087 	    arc_state_multilist_index_func);
6088 	arc_mfu->arcs_list[ARC_BUFC_DATA] =
6089 	    multilist_create(sizeof (arc_buf_hdr_t),
6090 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6091 	    arc_state_multilist_index_func);
6092 	arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6093 	    multilist_create(sizeof (arc_buf_hdr_t),
6094 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6095 	    arc_state_multilist_index_func);
6096 	arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6097 	    multilist_create(sizeof (arc_buf_hdr_t),
6098 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6099 	    arc_state_multilist_index_func);
6100 	arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6101 	    multilist_create(sizeof (arc_buf_hdr_t),
6102 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6103 	    arc_state_multilist_index_func);
6104 	arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6105 	    multilist_create(sizeof (arc_buf_hdr_t),
6106 	    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6107 	    arc_state_multilist_index_func);
6108 
6109 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6110 	zfs_refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6111 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6112 	zfs_refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6113 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6114 	zfs_refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6115 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6116 	zfs_refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6117 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6118 	zfs_refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6119 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6120 	zfs_refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6121 
6122 	zfs_refcount_create(&arc_anon->arcs_size);
6123 	zfs_refcount_create(&arc_mru->arcs_size);
6124 	zfs_refcount_create(&arc_mru_ghost->arcs_size);
6125 	zfs_refcount_create(&arc_mfu->arcs_size);
6126 	zfs_refcount_create(&arc_mfu_ghost->arcs_size);
6127 	zfs_refcount_create(&arc_l2c_only->arcs_size);
6128 
6129 	aggsum_init(&arc_meta_used, 0);
6130 	aggsum_init(&arc_size, 0);
6131 	aggsum_init(&astat_data_size, 0);
6132 	aggsum_init(&astat_metadata_size, 0);
6133 	aggsum_init(&astat_hdr_size, 0);
6134 	aggsum_init(&astat_other_size, 0);
6135 	aggsum_init(&astat_l2_hdr_size, 0);
6136 }
6137 
6138 static void
6139 arc_state_fini(void)
6140 {
6141 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6142 	zfs_refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6143 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6144 	zfs_refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6145 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6146 	zfs_refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6147 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6148 	zfs_refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6149 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6150 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6151 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6152 	zfs_refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6153 
6154 	zfs_refcount_destroy(&arc_anon->arcs_size);
6155 	zfs_refcount_destroy(&arc_mru->arcs_size);
6156 	zfs_refcount_destroy(&arc_mru_ghost->arcs_size);
6157 	zfs_refcount_destroy(&arc_mfu->arcs_size);
6158 	zfs_refcount_destroy(&arc_mfu_ghost->arcs_size);
6159 	zfs_refcount_destroy(&arc_l2c_only->arcs_size);
6160 
6161 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6162 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6163 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6164 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
6165 	multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
6166 	multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
6167 	multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
6168 	multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
6169 
6170 	aggsum_fini(&arc_meta_used);
6171 	aggsum_fini(&arc_size);
6172 	aggsum_fini(&astat_data_size);
6173 	aggsum_fini(&astat_metadata_size);
6174 	aggsum_fini(&astat_hdr_size);
6175 	aggsum_fini(&astat_other_size);
6176 	aggsum_fini(&astat_l2_hdr_size);
6177 }
6178 
6179 uint64_t
6180 arc_max_bytes(void)
6181 {
6182 	return (arc_c_max);
6183 }
6184 
6185 void
6186 arc_init(void)
6187 {
6188 	/*
6189 	 * allmem is "all memory that we could possibly use".
6190 	 */
6191 #ifdef _KERNEL
6192 	uint64_t allmem = ptob(physmem - swapfs_minfree);
6193 #else
6194 	uint64_t allmem = (physmem * PAGESIZE) / 2;
6195 #endif
6196 	mutex_init(&arc_adjust_lock, NULL, MUTEX_DEFAULT, NULL);
6197 	cv_init(&arc_adjust_waiters_cv, NULL, CV_DEFAULT, NULL);
6198 
6199 	/* Convert seconds to clock ticks */
6200 	arc_min_prefetch_lifespan = 1 * hz;
6201 
6202 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
6203 	arc_c_min = MAX(allmem / 32, 64 << 20);
6204 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
6205 	if (allmem >= 1 << 30)
6206 		arc_c_max = allmem - (1 << 30);
6207 	else
6208 		arc_c_max = arc_c_min;
6209 	arc_c_max = MAX(allmem * 3 / 4, arc_c_max);
6210 
6211 	/*
6212 	 * In userland, there's only the memory pressure that we artificially
6213 	 * create (see arc_available_memory()).  Don't let arc_c get too
6214 	 * small, because it can cause transactions to be larger than
6215 	 * arc_c, causing arc_tempreserve_space() to fail.
6216 	 */
6217 #ifndef _KERNEL
6218 	arc_c_min = arc_c_max / 2;
6219 #endif
6220 
6221 	/*
6222 	 * Allow the tunables to override our calculations if they are
6223 	 * reasonable (ie. over 64MB)
6224 	 */
6225 	if (zfs_arc_max > 64 << 20 && zfs_arc_max < allmem) {
6226 		arc_c_max = zfs_arc_max;
6227 		arc_c_min = MIN(arc_c_min, arc_c_max);
6228 	}
6229 	if (zfs_arc_min > 64 << 20 && zfs_arc_min <= arc_c_max)
6230 		arc_c_min = zfs_arc_min;
6231 
6232 	arc_c = arc_c_max;
6233 	arc_p = (arc_c >> 1);
6234 
6235 	/* limit meta-data to 1/4 of the arc capacity */
6236 	arc_meta_limit = arc_c_max / 4;
6237 
6238 #ifdef _KERNEL
6239 	/*
6240 	 * Metadata is stored in the kernel's heap.  Don't let us
6241 	 * use more than half the heap for the ARC.
6242 	 */
6243 	arc_meta_limit = MIN(arc_meta_limit,
6244 	    vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
6245 #endif
6246 
6247 	/* Allow the tunable to override if it is reasonable */
6248 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
6249 		arc_meta_limit = zfs_arc_meta_limit;
6250 
6251 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
6252 		arc_c_min = arc_meta_limit / 2;
6253 
6254 	if (zfs_arc_meta_min > 0) {
6255 		arc_meta_min = zfs_arc_meta_min;
6256 	} else {
6257 		arc_meta_min = arc_c_min / 2;
6258 	}
6259 
6260 	if (zfs_arc_grow_retry > 0)
6261 		arc_grow_retry = zfs_arc_grow_retry;
6262 
6263 	if (zfs_arc_shrink_shift > 0)
6264 		arc_shrink_shift = zfs_arc_shrink_shift;
6265 
6266 	/*
6267 	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
6268 	 */
6269 	if (arc_no_grow_shift >= arc_shrink_shift)
6270 		arc_no_grow_shift = arc_shrink_shift - 1;
6271 
6272 	if (zfs_arc_p_min_shift > 0)
6273 		arc_p_min_shift = zfs_arc_p_min_shift;
6274 
6275 	/* if kmem_flags are set, lets try to use less memory */
6276 	if (kmem_debugging())
6277 		arc_c = arc_c / 2;
6278 	if (arc_c < arc_c_min)
6279 		arc_c = arc_c_min;
6280 
6281 	arc_state_init();
6282 
6283 	/*
6284 	 * The arc must be "uninitialized", so that hdr_recl() (which is
6285 	 * registered by buf_init()) will not access arc_reap_zthr before
6286 	 * it is created.
6287 	 */
6288 	ASSERT(!arc_initialized);
6289 	buf_init();
6290 
6291 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
6292 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
6293 
6294 	if (arc_ksp != NULL) {
6295 		arc_ksp->ks_data = &arc_stats;
6296 		arc_ksp->ks_update = arc_kstat_update;
6297 		kstat_install(arc_ksp);
6298 	}
6299 
6300 	arc_adjust_zthr = zthr_create(arc_adjust_cb_check,
6301 	    arc_adjust_cb, NULL);
6302 	arc_reap_zthr = zthr_create_timer(arc_reap_cb_check,
6303 	    arc_reap_cb, NULL, SEC2NSEC(1));
6304 
6305 	arc_initialized = B_TRUE;
6306 	arc_warm = B_FALSE;
6307 
6308 	/*
6309 	 * Calculate maximum amount of dirty data per pool.
6310 	 *
6311 	 * If it has been set by /etc/system, take that.
6312 	 * Otherwise, use a percentage of physical memory defined by
6313 	 * zfs_dirty_data_max_percent (default 10%) with a cap at
6314 	 * zfs_dirty_data_max_max (default 4GB).
6315 	 */
6316 	if (zfs_dirty_data_max == 0) {
6317 		zfs_dirty_data_max = physmem * PAGESIZE *
6318 		    zfs_dirty_data_max_percent / 100;
6319 		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
6320 		    zfs_dirty_data_max_max);
6321 	}
6322 }
6323 
6324 void
6325 arc_fini(void)
6326 {
6327 	/* Use B_TRUE to ensure *all* buffers are evicted */
6328 	arc_flush(NULL, B_TRUE);
6329 
6330 	arc_initialized = B_FALSE;
6331 
6332 	if (arc_ksp != NULL) {
6333 		kstat_delete(arc_ksp);
6334 		arc_ksp = NULL;
6335 	}
6336 
6337 	(void) zthr_cancel(arc_adjust_zthr);
6338 	zthr_destroy(arc_adjust_zthr);
6339 
6340 	(void) zthr_cancel(arc_reap_zthr);
6341 	zthr_destroy(arc_reap_zthr);
6342 
6343 	mutex_destroy(&arc_adjust_lock);
6344 	cv_destroy(&arc_adjust_waiters_cv);
6345 
6346 	/*
6347 	 * buf_fini() must proceed arc_state_fini() because buf_fin() may
6348 	 * trigger the release of kmem magazines, which can callback to
6349 	 * arc_space_return() which accesses aggsums freed in act_state_fini().
6350 	 */
6351 	buf_fini();
6352 	arc_state_fini();
6353 
6354 	ASSERT0(arc_loaned_bytes);
6355 }
6356 
6357 /*
6358  * Level 2 ARC
6359  *
6360  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
6361  * It uses dedicated storage devices to hold cached data, which are populated
6362  * using large infrequent writes.  The main role of this cache is to boost
6363  * the performance of random read workloads.  The intended L2ARC devices
6364  * include short-stroked disks, solid state disks, and other media with
6365  * substantially faster read latency than disk.
6366  *
6367  *                 +-----------------------+
6368  *                 |         ARC           |
6369  *                 +-----------------------+
6370  *                    |         ^     ^
6371  *                    |         |     |
6372  *      l2arc_feed_thread()    arc_read()
6373  *                    |         |     |
6374  *                    |  l2arc read   |
6375  *                    V         |     |
6376  *               +---------------+    |
6377  *               |     L2ARC     |    |
6378  *               +---------------+    |
6379  *                   |    ^           |
6380  *          l2arc_write() |           |
6381  *                   |    |           |
6382  *                   V    |           |
6383  *                 +-------+      +-------+
6384  *                 | vdev  |      | vdev  |
6385  *                 | cache |      | cache |
6386  *                 +-------+      +-------+
6387  *                 +=========+     .-----.
6388  *                 :  L2ARC  :    |-_____-|
6389  *                 : devices :    | Disks |
6390  *                 +=========+    `-_____-'
6391  *
6392  * Read requests are satisfied from the following sources, in order:
6393  *
6394  *	1) ARC
6395  *	2) vdev cache of L2ARC devices
6396  *	3) L2ARC devices
6397  *	4) vdev cache of disks
6398  *	5) disks
6399  *
6400  * Some L2ARC device types exhibit extremely slow write performance.
6401  * To accommodate for this there are some significant differences between
6402  * the L2ARC and traditional cache design:
6403  *
6404  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
6405  * the ARC behave as usual, freeing buffers and placing headers on ghost
6406  * lists.  The ARC does not send buffers to the L2ARC during eviction as
6407  * this would add inflated write latencies for all ARC memory pressure.
6408  *
6409  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
6410  * It does this by periodically scanning buffers from the eviction-end of
6411  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
6412  * not already there. It scans until a headroom of buffers is satisfied,
6413  * which itself is a buffer for ARC eviction. If a compressible buffer is
6414  * found during scanning and selected for writing to an L2ARC device, we
6415  * temporarily boost scanning headroom during the next scan cycle to make
6416  * sure we adapt to compression effects (which might significantly reduce
6417  * the data volume we write to L2ARC). The thread that does this is
6418  * l2arc_feed_thread(), illustrated below; example sizes are included to
6419  * provide a better sense of ratio than this diagram:
6420  *
6421  *	       head -->                        tail
6422  *	        +---------------------+----------+
6423  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
6424  *	        +---------------------+----------+   |   o L2ARC eligible
6425  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
6426  *	        +---------------------+----------+   |
6427  *	             15.9 Gbytes      ^ 32 Mbytes    |
6428  *	                           headroom          |
6429  *	                                      l2arc_feed_thread()
6430  *	                                             |
6431  *	                 l2arc write hand <--[oooo]--'
6432  *	                         |           8 Mbyte
6433  *	                         |          write max
6434  *	                         V
6435  *		  +==============================+
6436  *	L2ARC dev |####|#|###|###|    |####| ... |
6437  *	          +==============================+
6438  *	                     32 Gbytes
6439  *
6440  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
6441  * evicted, then the L2ARC has cached a buffer much sooner than it probably
6442  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
6443  * safe to say that this is an uncommon case, since buffers at the end of
6444  * the ARC lists have moved there due to inactivity.
6445  *
6446  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
6447  * then the L2ARC simply misses copying some buffers.  This serves as a
6448  * pressure valve to prevent heavy read workloads from both stalling the ARC
6449  * with waits and clogging the L2ARC with writes.  This also helps prevent
6450  * the potential for the L2ARC to churn if it attempts to cache content too
6451  * quickly, such as during backups of the entire pool.
6452  *
6453  * 5. After system boot and before the ARC has filled main memory, there are
6454  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
6455  * lists can remain mostly static.  Instead of searching from tail of these
6456  * lists as pictured, the l2arc_feed_thread() will search from the list heads
6457  * for eligible buffers, greatly increasing its chance of finding them.
6458  *
6459  * The L2ARC device write speed is also boosted during this time so that
6460  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
6461  * there are no L2ARC reads, and no fear of degrading read performance
6462  * through increased writes.
6463  *
6464  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
6465  * the vdev queue can aggregate them into larger and fewer writes.  Each
6466  * device is written to in a rotor fashion, sweeping writes through
6467  * available space then repeating.
6468  *
6469  * 7. The L2ARC does not store dirty content.  It never needs to flush
6470  * write buffers back to disk based storage.
6471  *
6472  * 8. If an ARC buffer is written (and dirtied) which also exists in the
6473  * L2ARC, the now stale L2ARC buffer is immediately dropped.
6474  *
6475  * The performance of the L2ARC can be tweaked by a number of tunables, which
6476  * may be necessary for different workloads:
6477  *
6478  *	l2arc_write_max		max write bytes per interval
6479  *	l2arc_write_boost	extra write bytes during device warmup
6480  *	l2arc_noprefetch	skip caching prefetched buffers
6481  *	l2arc_headroom		number of max device writes to precache
6482  *	l2arc_headroom_boost	when we find compressed buffers during ARC
6483  *				scanning, we multiply headroom by this
6484  *				percentage factor for the next scan cycle,
6485  *				since more compressed buffers are likely to
6486  *				be present
6487  *	l2arc_feed_secs		seconds between L2ARC writing
6488  *
6489  * Tunables may be removed or added as future performance improvements are
6490  * integrated, and also may become zpool properties.
6491  *
6492  * There are three key functions that control how the L2ARC warms up:
6493  *
6494  *	l2arc_write_eligible()	check if a buffer is eligible to cache
6495  *	l2arc_write_size()	calculate how much to write
6496  *	l2arc_write_interval()	calculate sleep delay between writes
6497  *
6498  * These three functions determine what to write, how much, and how quickly
6499  * to send writes.
6500  */
6501 
6502 static boolean_t
6503 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
6504 {
6505 	/*
6506 	 * A buffer is *not* eligible for the L2ARC if it:
6507 	 * 1. belongs to a different spa.
6508 	 * 2. is already cached on the L2ARC.
6509 	 * 3. has an I/O in progress (it may be an incomplete read).
6510 	 * 4. is flagged not eligible (zfs property).
6511 	 */
6512 	if (hdr->b_spa != spa_guid || HDR_HAS_L2HDR(hdr) ||
6513 	    HDR_IO_IN_PROGRESS(hdr) || !HDR_L2CACHE(hdr))
6514 		return (B_FALSE);
6515 
6516 	return (B_TRUE);
6517 }
6518 
6519 static uint64_t
6520 l2arc_write_size(void)
6521 {
6522 	uint64_t size;
6523 
6524 	/*
6525 	 * Make sure our globals have meaningful values in case the user
6526 	 * altered them.
6527 	 */
6528 	size = l2arc_write_max;
6529 	if (size == 0) {
6530 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
6531 		    "be greater than zero, resetting it to the default (%d)",
6532 		    L2ARC_WRITE_SIZE);
6533 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
6534 	}
6535 
6536 	if (arc_warm == B_FALSE)
6537 		size += l2arc_write_boost;
6538 
6539 	return (size);
6540 
6541 }
6542 
6543 static clock_t
6544 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
6545 {
6546 	clock_t interval, next, now;
6547 
6548 	/*
6549 	 * If the ARC lists are busy, increase our write rate; if the
6550 	 * lists are stale, idle back.  This is achieved by checking
6551 	 * how much we previously wrote - if it was more than half of
6552 	 * what we wanted, schedule the next write much sooner.
6553 	 */
6554 	if (l2arc_feed_again && wrote > (wanted / 2))
6555 		interval = (hz * l2arc_feed_min_ms) / 1000;
6556 	else
6557 		interval = hz * l2arc_feed_secs;
6558 
6559 	now = ddi_get_lbolt();
6560 	next = MAX(now, MIN(now + interval, began + interval));
6561 
6562 	return (next);
6563 }
6564 
6565 /*
6566  * Cycle through L2ARC devices.  This is how L2ARC load balances.
6567  * If a device is returned, this also returns holding the spa config lock.
6568  */
6569 static l2arc_dev_t *
6570 l2arc_dev_get_next(void)
6571 {
6572 	l2arc_dev_t *first, *next = NULL;
6573 
6574 	/*
6575 	 * Lock out the removal of spas (spa_namespace_lock), then removal
6576 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
6577 	 * both locks will be dropped and a spa config lock held instead.
6578 	 */
6579 	mutex_enter(&spa_namespace_lock);
6580 	mutex_enter(&l2arc_dev_mtx);
6581 
6582 	/* if there are no vdevs, there is nothing to do */
6583 	if (l2arc_ndev == 0)
6584 		goto out;
6585 
6586 	first = NULL;
6587 	next = l2arc_dev_last;
6588 	do {
6589 		/* loop around the list looking for a non-faulted vdev */
6590 		if (next == NULL) {
6591 			next = list_head(l2arc_dev_list);
6592 		} else {
6593 			next = list_next(l2arc_dev_list, next);
6594 			if (next == NULL)
6595 				next = list_head(l2arc_dev_list);
6596 		}
6597 
6598 		/* if we have come back to the start, bail out */
6599 		if (first == NULL)
6600 			first = next;
6601 		else if (next == first)
6602 			break;
6603 
6604 	} while (vdev_is_dead(next->l2ad_vdev));
6605 
6606 	/* if we were unable to find any usable vdevs, return NULL */
6607 	if (vdev_is_dead(next->l2ad_vdev))
6608 		next = NULL;
6609 
6610 	l2arc_dev_last = next;
6611 
6612 out:
6613 	mutex_exit(&l2arc_dev_mtx);
6614 
6615 	/*
6616 	 * Grab the config lock to prevent the 'next' device from being
6617 	 * removed while we are writing to it.
6618 	 */
6619 	if (next != NULL)
6620 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
6621 	mutex_exit(&spa_namespace_lock);
6622 
6623 	return (next);
6624 }
6625 
6626 /*
6627  * Free buffers that were tagged for destruction.
6628  */
6629 static void
6630 l2arc_do_free_on_write()
6631 {
6632 	list_t *buflist;
6633 	l2arc_data_free_t *df, *df_prev;
6634 
6635 	mutex_enter(&l2arc_free_on_write_mtx);
6636 	buflist = l2arc_free_on_write;
6637 
6638 	for (df = list_tail(buflist); df; df = df_prev) {
6639 		df_prev = list_prev(buflist, df);
6640 		ASSERT3P(df->l2df_abd, !=, NULL);
6641 		abd_free(df->l2df_abd);
6642 		list_remove(buflist, df);
6643 		kmem_free(df, sizeof (l2arc_data_free_t));
6644 	}
6645 
6646 	mutex_exit(&l2arc_free_on_write_mtx);
6647 }
6648 
6649 /*
6650  * A write to a cache device has completed.  Update all headers to allow
6651  * reads from these buffers to begin.
6652  */
6653 static void
6654 l2arc_write_done(zio_t *zio)
6655 {
6656 	l2arc_write_callback_t *cb;
6657 	l2arc_dev_t *dev;
6658 	list_t *buflist;
6659 	arc_buf_hdr_t *head, *hdr, *hdr_prev;
6660 	kmutex_t *hash_lock;
6661 	int64_t bytes_dropped = 0;
6662 
6663 	cb = zio->io_private;
6664 	ASSERT3P(cb, !=, NULL);
6665 	dev = cb->l2wcb_dev;
6666 	ASSERT3P(dev, !=, NULL);
6667 	head = cb->l2wcb_head;
6668 	ASSERT3P(head, !=, NULL);
6669 	buflist = &dev->l2ad_buflist;
6670 	ASSERT3P(buflist, !=, NULL);
6671 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
6672 	    l2arc_write_callback_t *, cb);
6673 
6674 	if (zio->io_error != 0)
6675 		ARCSTAT_BUMP(arcstat_l2_writes_error);
6676 
6677 	/*
6678 	 * All writes completed, or an error was hit.
6679 	 */
6680 top:
6681 	mutex_enter(&dev->l2ad_mtx);
6682 	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
6683 		hdr_prev = list_prev(buflist, hdr);
6684 
6685 		hash_lock = HDR_LOCK(hdr);
6686 
6687 		/*
6688 		 * We cannot use mutex_enter or else we can deadlock
6689 		 * with l2arc_write_buffers (due to swapping the order
6690 		 * the hash lock and l2ad_mtx are taken).
6691 		 */
6692 		if (!mutex_tryenter(hash_lock)) {
6693 			/*
6694 			 * Missed the hash lock. We must retry so we
6695 			 * don't leave the ARC_FLAG_L2_WRITING bit set.
6696 			 */
6697 			ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
6698 
6699 			/*
6700 			 * We don't want to rescan the headers we've
6701 			 * already marked as having been written out, so
6702 			 * we reinsert the head node so we can pick up
6703 			 * where we left off.
6704 			 */
6705 			list_remove(buflist, head);
6706 			list_insert_after(buflist, hdr, head);
6707 
6708 			mutex_exit(&dev->l2ad_mtx);
6709 
6710 			/*
6711 			 * We wait for the hash lock to become available
6712 			 * to try and prevent busy waiting, and increase
6713 			 * the chance we'll be able to acquire the lock
6714 			 * the next time around.
6715 			 */
6716 			mutex_enter(hash_lock);
6717 			mutex_exit(hash_lock);
6718 			goto top;
6719 		}
6720 
6721 		/*
6722 		 * We could not have been moved into the arc_l2c_only
6723 		 * state while in-flight due to our ARC_FLAG_L2_WRITING
6724 		 * bit being set. Let's just ensure that's being enforced.
6725 		 */
6726 		ASSERT(HDR_HAS_L1HDR(hdr));
6727 
6728 		if (zio->io_error != 0) {
6729 			/*
6730 			 * Error - drop L2ARC entry.
6731 			 */
6732 			list_remove(buflist, hdr);
6733 			arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
6734 
6735 			ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
6736 			ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
6737 
6738 			bytes_dropped += arc_hdr_size(hdr);
6739 			(void) zfs_refcount_remove_many(&dev->l2ad_alloc,
6740 			    arc_hdr_size(hdr), hdr);
6741 		}
6742 
6743 		/*
6744 		 * Allow ARC to begin reads and ghost list evictions to
6745 		 * this L2ARC entry.
6746 		 */
6747 		arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
6748 
6749 		mutex_exit(hash_lock);
6750 	}
6751 
6752 	atomic_inc_64(&l2arc_writes_done);
6753 	list_remove(buflist, head);
6754 	ASSERT(!HDR_HAS_L1HDR(head));
6755 	kmem_cache_free(hdr_l2only_cache, head);
6756 	mutex_exit(&dev->l2ad_mtx);
6757 
6758 	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
6759 
6760 	l2arc_do_free_on_write();
6761 
6762 	kmem_free(cb, sizeof (l2arc_write_callback_t));
6763 }
6764 
6765 /*
6766  * A read to a cache device completed.  Validate buffer contents before
6767  * handing over to the regular ARC routines.
6768  */
6769 static void
6770 l2arc_read_done(zio_t *zio)
6771 {
6772 	l2arc_read_callback_t *cb;
6773 	arc_buf_hdr_t *hdr;
6774 	kmutex_t *hash_lock;
6775 	boolean_t valid_cksum;
6776 
6777 	ASSERT3P(zio->io_vd, !=, NULL);
6778 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
6779 
6780 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
6781 
6782 	cb = zio->io_private;
6783 	ASSERT3P(cb, !=, NULL);
6784 	hdr = cb->l2rcb_hdr;
6785 	ASSERT3P(hdr, !=, NULL);
6786 
6787 	hash_lock = HDR_LOCK(hdr);
6788 	mutex_enter(hash_lock);
6789 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6790 
6791 	/*
6792 	 * If the data was read into a temporary buffer,
6793 	 * move it and free the buffer.
6794 	 */
6795 	if (cb->l2rcb_abd != NULL) {
6796 		ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
6797 		if (zio->io_error == 0) {
6798 			abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
6799 			    arc_hdr_size(hdr));
6800 		}
6801 
6802 		/*
6803 		 * The following must be done regardless of whether
6804 		 * there was an error:
6805 		 * - free the temporary buffer
6806 		 * - point zio to the real ARC buffer
6807 		 * - set zio size accordingly
6808 		 * These are required because zio is either re-used for
6809 		 * an I/O of the block in the case of the error
6810 		 * or the zio is passed to arc_read_done() and it
6811 		 * needs real data.
6812 		 */
6813 		abd_free(cb->l2rcb_abd);
6814 		zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
6815 		zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
6816 	}
6817 
6818 	ASSERT3P(zio->io_abd, !=, NULL);
6819 
6820 	/*
6821 	 * Check this survived the L2ARC journey.
6822 	 */
6823 	ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
6824 	zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
6825 	zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
6826 
6827 	valid_cksum = arc_cksum_is_equal(hdr, zio);
6828 	if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
6829 		mutex_exit(hash_lock);
6830 		zio->io_private = hdr;
6831 		arc_read_done(zio);
6832 	} else {
6833 		mutex_exit(hash_lock);
6834 		/*
6835 		 * Buffer didn't survive caching.  Increment stats and
6836 		 * reissue to the original storage device.
6837 		 */
6838 		if (zio->io_error != 0) {
6839 			ARCSTAT_BUMP(arcstat_l2_io_error);
6840 		} else {
6841 			zio->io_error = SET_ERROR(EIO);
6842 		}
6843 		if (!valid_cksum)
6844 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
6845 
6846 		/*
6847 		 * If there's no waiter, issue an async i/o to the primary
6848 		 * storage now.  If there *is* a waiter, the caller must
6849 		 * issue the i/o in a context where it's OK to block.
6850 		 */
6851 		if (zio->io_waiter == NULL) {
6852 			zio_t *pio = zio_unique_parent(zio);
6853 
6854 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
6855 
6856 			zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
6857 			    hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
6858 			    hdr, zio->io_priority, cb->l2rcb_flags,
6859 			    &cb->l2rcb_zb));
6860 		}
6861 	}
6862 
6863 	kmem_free(cb, sizeof (l2arc_read_callback_t));
6864 }
6865 
6866 /*
6867  * This is the list priority from which the L2ARC will search for pages to
6868  * cache.  This is used within loops (0..3) to cycle through lists in the
6869  * desired order.  This order can have a significant effect on cache
6870  * performance.
6871  *
6872  * Currently the metadata lists are hit first, MFU then MRU, followed by
6873  * the data lists.  This function returns a locked list, and also returns
6874  * the lock pointer.
6875  */
6876 static multilist_sublist_t *
6877 l2arc_sublist_lock(int list_num)
6878 {
6879 	multilist_t *ml = NULL;
6880 	unsigned int idx;
6881 
6882 	ASSERT(list_num >= 0 && list_num <= 3);
6883 
6884 	switch (list_num) {
6885 	case 0:
6886 		ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
6887 		break;
6888 	case 1:
6889 		ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
6890 		break;
6891 	case 2:
6892 		ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
6893 		break;
6894 	case 3:
6895 		ml = arc_mru->arcs_list[ARC_BUFC_DATA];
6896 		break;
6897 	}
6898 
6899 	/*
6900 	 * Return a randomly-selected sublist. This is acceptable
6901 	 * because the caller feeds only a little bit of data for each
6902 	 * call (8MB). Subsequent calls will result in different
6903 	 * sublists being selected.
6904 	 */
6905 	idx = multilist_get_random_index(ml);
6906 	return (multilist_sublist_lock(ml, idx));
6907 }
6908 
6909 /*
6910  * Evict buffers from the device write hand to the distance specified in
6911  * bytes.  This distance may span populated buffers, it may span nothing.
6912  * This is clearing a region on the L2ARC device ready for writing.
6913  * If the 'all' boolean is set, every buffer is evicted.
6914  */
6915 static void
6916 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
6917 {
6918 	list_t *buflist;
6919 	arc_buf_hdr_t *hdr, *hdr_prev;
6920 	kmutex_t *hash_lock;
6921 	uint64_t taddr;
6922 
6923 	buflist = &dev->l2ad_buflist;
6924 
6925 	if (!all && dev->l2ad_first) {
6926 		/*
6927 		 * This is the first sweep through the device.  There is
6928 		 * nothing to evict.
6929 		 */
6930 		return;
6931 	}
6932 
6933 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
6934 		/*
6935 		 * When nearing the end of the device, evict to the end
6936 		 * before the device write hand jumps to the start.
6937 		 */
6938 		taddr = dev->l2ad_end;
6939 	} else {
6940 		taddr = dev->l2ad_hand + distance;
6941 	}
6942 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
6943 	    uint64_t, taddr, boolean_t, all);
6944 
6945 top:
6946 	mutex_enter(&dev->l2ad_mtx);
6947 	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
6948 		hdr_prev = list_prev(buflist, hdr);
6949 
6950 		hash_lock = HDR_LOCK(hdr);
6951 
6952 		/*
6953 		 * We cannot use mutex_enter or else we can deadlock
6954 		 * with l2arc_write_buffers (due to swapping the order
6955 		 * the hash lock and l2ad_mtx are taken).
6956 		 */
6957 		if (!mutex_tryenter(hash_lock)) {
6958 			/*
6959 			 * Missed the hash lock.  Retry.
6960 			 */
6961 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
6962 			mutex_exit(&dev->l2ad_mtx);
6963 			mutex_enter(hash_lock);
6964 			mutex_exit(hash_lock);
6965 			goto top;
6966 		}
6967 
6968 		/*
6969 		 * A header can't be on this list if it doesn't have L2 header.
6970 		 */
6971 		ASSERT(HDR_HAS_L2HDR(hdr));
6972 
6973 		/* Ensure this header has finished being written. */
6974 		ASSERT(!HDR_L2_WRITING(hdr));
6975 		ASSERT(!HDR_L2_WRITE_HEAD(hdr));
6976 
6977 		if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
6978 		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
6979 			/*
6980 			 * We've evicted to the target address,
6981 			 * or the end of the device.
6982 			 */
6983 			mutex_exit(hash_lock);
6984 			break;
6985 		}
6986 
6987 		if (!HDR_HAS_L1HDR(hdr)) {
6988 			ASSERT(!HDR_L2_READING(hdr));
6989 			/*
6990 			 * This doesn't exist in the ARC.  Destroy.
6991 			 * arc_hdr_destroy() will call list_remove()
6992 			 * and decrement arcstat_l2_lsize.
6993 			 */
6994 			arc_change_state(arc_anon, hdr, hash_lock);
6995 			arc_hdr_destroy(hdr);
6996 		} else {
6997 			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
6998 			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
6999 			/*
7000 			 * Invalidate issued or about to be issued
7001 			 * reads, since we may be about to write
7002 			 * over this location.
7003 			 */
7004 			if (HDR_L2_READING(hdr)) {
7005 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
7006 				arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7007 			}
7008 
7009 			arc_hdr_l2hdr_destroy(hdr);
7010 		}
7011 		mutex_exit(hash_lock);
7012 	}
7013 	mutex_exit(&dev->l2ad_mtx);
7014 }
7015 
7016 /*
7017  * Find and write ARC buffers to the L2ARC device.
7018  *
7019  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7020  * for reading until they have completed writing.
7021  * The headroom_boost is an in-out parameter used to maintain headroom boost
7022  * state between calls to this function.
7023  *
7024  * Returns the number of bytes actually written (which may be smaller than
7025  * the delta by which the device hand has changed due to alignment).
7026  */
7027 static uint64_t
7028 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7029 {
7030 	arc_buf_hdr_t *hdr, *hdr_prev, *head;
7031 	uint64_t write_asize, write_psize, write_lsize, headroom;
7032 	boolean_t full;
7033 	l2arc_write_callback_t *cb;
7034 	zio_t *pio, *wzio;
7035 	uint64_t guid = spa_load_guid(spa);
7036 
7037 	ASSERT3P(dev->l2ad_vdev, !=, NULL);
7038 
7039 	pio = NULL;
7040 	write_lsize = write_asize = write_psize = 0;
7041 	full = B_FALSE;
7042 	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7043 	arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7044 
7045 	/*
7046 	 * Copy buffers for L2ARC writing.
7047 	 */
7048 	for (int try = 0; try <= 3; try++) {
7049 		multilist_sublist_t *mls = l2arc_sublist_lock(try);
7050 		uint64_t passed_sz = 0;
7051 
7052 		/*
7053 		 * L2ARC fast warmup.
7054 		 *
7055 		 * Until the ARC is warm and starts to evict, read from the
7056 		 * head of the ARC lists rather than the tail.
7057 		 */
7058 		if (arc_warm == B_FALSE)
7059 			hdr = multilist_sublist_head(mls);
7060 		else
7061 			hdr = multilist_sublist_tail(mls);
7062 
7063 		headroom = target_sz * l2arc_headroom;
7064 		if (zfs_compressed_arc_enabled)
7065 			headroom = (headroom * l2arc_headroom_boost) / 100;
7066 
7067 		for (; hdr; hdr = hdr_prev) {
7068 			kmutex_t *hash_lock;
7069 
7070 			if (arc_warm == B_FALSE)
7071 				hdr_prev = multilist_sublist_next(mls, hdr);
7072 			else
7073 				hdr_prev = multilist_sublist_prev(mls, hdr);
7074 
7075 			hash_lock = HDR_LOCK(hdr);
7076 			if (!mutex_tryenter(hash_lock)) {
7077 				/*
7078 				 * Skip this buffer rather than waiting.
7079 				 */
7080 				continue;
7081 			}
7082 
7083 			passed_sz += HDR_GET_LSIZE(hdr);
7084 			if (passed_sz > headroom) {
7085 				/*
7086 				 * Searched too far.
7087 				 */
7088 				mutex_exit(hash_lock);
7089 				break;
7090 			}
7091 
7092 			if (!l2arc_write_eligible(guid, hdr)) {
7093 				mutex_exit(hash_lock);
7094 				continue;
7095 			}
7096 
7097 			/*
7098 			 * We rely on the L1 portion of the header below, so
7099 			 * it's invalid for this header to have been evicted out
7100 			 * of the ghost cache, prior to being written out. The
7101 			 * ARC_FLAG_L2_WRITING bit ensures this won't happen.
7102 			 */
7103 			ASSERT(HDR_HAS_L1HDR(hdr));
7104 
7105 			ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
7106 			ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
7107 			ASSERT3U(arc_hdr_size(hdr), >, 0);
7108 			uint64_t psize = arc_hdr_size(hdr);
7109 			uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
7110 			    psize);
7111 
7112 			if ((write_asize + asize) > target_sz) {
7113 				full = B_TRUE;
7114 				mutex_exit(hash_lock);
7115 				break;
7116 			}
7117 
7118 			if (pio == NULL) {
7119 				/*
7120 				 * Insert a dummy header on the buflist so
7121 				 * l2arc_write_done() can find where the
7122 				 * write buffers begin without searching.
7123 				 */
7124 				mutex_enter(&dev->l2ad_mtx);
7125 				list_insert_head(&dev->l2ad_buflist, head);
7126 				mutex_exit(&dev->l2ad_mtx);
7127 
7128 				cb = kmem_alloc(
7129 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
7130 				cb->l2wcb_dev = dev;
7131 				cb->l2wcb_head = head;
7132 				pio = zio_root(spa, l2arc_write_done, cb,
7133 				    ZIO_FLAG_CANFAIL);
7134 			}
7135 
7136 			hdr->b_l2hdr.b_dev = dev;
7137 			hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
7138 			arc_hdr_set_flags(hdr,
7139 			    ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
7140 
7141 			mutex_enter(&dev->l2ad_mtx);
7142 			list_insert_head(&dev->l2ad_buflist, hdr);
7143 			mutex_exit(&dev->l2ad_mtx);
7144 
7145 			(void) zfs_refcount_add_many(&dev->l2ad_alloc, psize,
7146 			    hdr);
7147 
7148 			/*
7149 			 * Normally the L2ARC can use the hdr's data, but if
7150 			 * we're sharing data between the hdr and one of its
7151 			 * bufs, L2ARC needs its own copy of the data so that
7152 			 * the ZIO below can't race with the buf consumer.
7153 			 * Another case where we need to create a copy of the
7154 			 * data is when the buffer size is not device-aligned
7155 			 * and we need to pad the block to make it such.
7156 			 * That also keeps the clock hand suitably aligned.
7157 			 *
7158 			 * To ensure that the copy will be available for the
7159 			 * lifetime of the ZIO and be cleaned up afterwards, we
7160 			 * add it to the l2arc_free_on_write queue.
7161 			 */
7162 			abd_t *to_write;
7163 			if (!HDR_SHARED_DATA(hdr) && psize == asize) {
7164 				to_write = hdr->b_l1hdr.b_pabd;
7165 			} else {
7166 				to_write = abd_alloc_for_io(asize,
7167 				    HDR_ISTYPE_METADATA(hdr));
7168 				abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
7169 				if (asize != psize) {
7170 					abd_zero_off(to_write, psize,
7171 					    asize - psize);
7172 				}
7173 				l2arc_free_abd_on_write(to_write, asize,
7174 				    arc_buf_type(hdr));
7175 			}
7176 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
7177 			    hdr->b_l2hdr.b_daddr, asize, to_write,
7178 			    ZIO_CHECKSUM_OFF, NULL, hdr,
7179 			    ZIO_PRIORITY_ASYNC_WRITE,
7180 			    ZIO_FLAG_CANFAIL, B_FALSE);
7181 
7182 			write_lsize += HDR_GET_LSIZE(hdr);
7183 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
7184 			    zio_t *, wzio);
7185 
7186 			write_psize += psize;
7187 			write_asize += asize;
7188 			dev->l2ad_hand += asize;
7189 
7190 			mutex_exit(hash_lock);
7191 
7192 			(void) zio_nowait(wzio);
7193 		}
7194 
7195 		multilist_sublist_unlock(mls);
7196 
7197 		if (full == B_TRUE)
7198 			break;
7199 	}
7200 
7201 	/* No buffers selected for writing? */
7202 	if (pio == NULL) {
7203 		ASSERT0(write_lsize);
7204 		ASSERT(!HDR_HAS_L1HDR(head));
7205 		kmem_cache_free(hdr_l2only_cache, head);
7206 		return (0);
7207 	}
7208 
7209 	ASSERT3U(write_asize, <=, target_sz);
7210 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
7211 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
7212 	ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
7213 	ARCSTAT_INCR(arcstat_l2_psize, write_psize);
7214 	vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
7215 
7216 	/*
7217 	 * Bump device hand to the device start if it is approaching the end.
7218 	 * l2arc_evict() will already have evicted ahead for this case.
7219 	 */
7220 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
7221 		dev->l2ad_hand = dev->l2ad_start;
7222 		dev->l2ad_first = B_FALSE;
7223 	}
7224 
7225 	dev->l2ad_writing = B_TRUE;
7226 	(void) zio_wait(pio);
7227 	dev->l2ad_writing = B_FALSE;
7228 
7229 	return (write_asize);
7230 }
7231 
7232 /*
7233  * This thread feeds the L2ARC at regular intervals.  This is the beating
7234  * heart of the L2ARC.
7235  */
7236 /* ARGSUSED */
7237 static void
7238 l2arc_feed_thread(void *unused)
7239 {
7240 	callb_cpr_t cpr;
7241 	l2arc_dev_t *dev;
7242 	spa_t *spa;
7243 	uint64_t size, wrote;
7244 	clock_t begin, next = ddi_get_lbolt();
7245 
7246 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
7247 
7248 	mutex_enter(&l2arc_feed_thr_lock);
7249 
7250 	while (l2arc_thread_exit == 0) {
7251 		CALLB_CPR_SAFE_BEGIN(&cpr);
7252 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
7253 		    next);
7254 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
7255 		next = ddi_get_lbolt() + hz;
7256 
7257 		/*
7258 		 * Quick check for L2ARC devices.
7259 		 */
7260 		mutex_enter(&l2arc_dev_mtx);
7261 		if (l2arc_ndev == 0) {
7262 			mutex_exit(&l2arc_dev_mtx);
7263 			continue;
7264 		}
7265 		mutex_exit(&l2arc_dev_mtx);
7266 		begin = ddi_get_lbolt();
7267 
7268 		/*
7269 		 * This selects the next l2arc device to write to, and in
7270 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
7271 		 * will return NULL if there are now no l2arc devices or if
7272 		 * they are all faulted.
7273 		 *
7274 		 * If a device is returned, its spa's config lock is also
7275 		 * held to prevent device removal.  l2arc_dev_get_next()
7276 		 * will grab and release l2arc_dev_mtx.
7277 		 */
7278 		if ((dev = l2arc_dev_get_next()) == NULL)
7279 			continue;
7280 
7281 		spa = dev->l2ad_spa;
7282 		ASSERT3P(spa, !=, NULL);
7283 
7284 		/*
7285 		 * If the pool is read-only then force the feed thread to
7286 		 * sleep a little longer.
7287 		 */
7288 		if (!spa_writeable(spa)) {
7289 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
7290 			spa_config_exit(spa, SCL_L2ARC, dev);
7291 			continue;
7292 		}
7293 
7294 		/*
7295 		 * Avoid contributing to memory pressure.
7296 		 */
7297 		if (arc_reclaim_needed()) {
7298 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
7299 			spa_config_exit(spa, SCL_L2ARC, dev);
7300 			continue;
7301 		}
7302 
7303 		ARCSTAT_BUMP(arcstat_l2_feeds);
7304 
7305 		size = l2arc_write_size();
7306 
7307 		/*
7308 		 * Evict L2ARC buffers that will be overwritten.
7309 		 */
7310 		l2arc_evict(dev, size, B_FALSE);
7311 
7312 		/*
7313 		 * Write ARC buffers.
7314 		 */
7315 		wrote = l2arc_write_buffers(spa, dev, size);
7316 
7317 		/*
7318 		 * Calculate interval between writes.
7319 		 */
7320 		next = l2arc_write_interval(begin, size, wrote);
7321 		spa_config_exit(spa, SCL_L2ARC, dev);
7322 	}
7323 
7324 	l2arc_thread_exit = 0;
7325 	cv_broadcast(&l2arc_feed_thr_cv);
7326 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
7327 	thread_exit();
7328 }
7329 
7330 boolean_t
7331 l2arc_vdev_present(vdev_t *vd)
7332 {
7333 	l2arc_dev_t *dev;
7334 
7335 	mutex_enter(&l2arc_dev_mtx);
7336 	for (dev = list_head(l2arc_dev_list); dev != NULL;
7337 	    dev = list_next(l2arc_dev_list, dev)) {
7338 		if (dev->l2ad_vdev == vd)
7339 			break;
7340 	}
7341 	mutex_exit(&l2arc_dev_mtx);
7342 
7343 	return (dev != NULL);
7344 }
7345 
7346 /*
7347  * Add a vdev for use by the L2ARC.  By this point the spa has already
7348  * validated the vdev and opened it.
7349  */
7350 void
7351 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
7352 {
7353 	l2arc_dev_t *adddev;
7354 
7355 	ASSERT(!l2arc_vdev_present(vd));
7356 
7357 	/*
7358 	 * Create a new l2arc device entry.
7359 	 */
7360 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
7361 	adddev->l2ad_spa = spa;
7362 	adddev->l2ad_vdev = vd;
7363 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
7364 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
7365 	adddev->l2ad_hand = adddev->l2ad_start;
7366 	adddev->l2ad_first = B_TRUE;
7367 	adddev->l2ad_writing = B_FALSE;
7368 
7369 	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
7370 	/*
7371 	 * This is a list of all ARC buffers that are still valid on the
7372 	 * device.
7373 	 */
7374 	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
7375 	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
7376 
7377 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
7378 	zfs_refcount_create(&adddev->l2ad_alloc);
7379 
7380 	/*
7381 	 * Add device to global list
7382 	 */
7383 	mutex_enter(&l2arc_dev_mtx);
7384 	list_insert_head(l2arc_dev_list, adddev);
7385 	atomic_inc_64(&l2arc_ndev);
7386 	mutex_exit(&l2arc_dev_mtx);
7387 }
7388 
7389 /*
7390  * Remove a vdev from the L2ARC.
7391  */
7392 void
7393 l2arc_remove_vdev(vdev_t *vd)
7394 {
7395 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
7396 
7397 	/*
7398 	 * Find the device by vdev
7399 	 */
7400 	mutex_enter(&l2arc_dev_mtx);
7401 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
7402 		nextdev = list_next(l2arc_dev_list, dev);
7403 		if (vd == dev->l2ad_vdev) {
7404 			remdev = dev;
7405 			break;
7406 		}
7407 	}
7408 	ASSERT3P(remdev, !=, NULL);
7409 
7410 	/*
7411 	 * Remove device from global list
7412 	 */
7413 	list_remove(l2arc_dev_list, remdev);
7414 	l2arc_dev_last = NULL;		/* may have been invalidated */
7415 	atomic_dec_64(&l2arc_ndev);
7416 	mutex_exit(&l2arc_dev_mtx);
7417 
7418 	/*
7419 	 * Clear all buflists and ARC references.  L2ARC device flush.
7420 	 */
7421 	l2arc_evict(remdev, 0, B_TRUE);
7422 	list_destroy(&remdev->l2ad_buflist);
7423 	mutex_destroy(&remdev->l2ad_mtx);
7424 	zfs_refcount_destroy(&remdev->l2ad_alloc);
7425 	kmem_free(remdev, sizeof (l2arc_dev_t));
7426 }
7427 
7428 void
7429 l2arc_init(void)
7430 {
7431 	l2arc_thread_exit = 0;
7432 	l2arc_ndev = 0;
7433 	l2arc_writes_sent = 0;
7434 	l2arc_writes_done = 0;
7435 
7436 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
7437 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
7438 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
7439 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
7440 
7441 	l2arc_dev_list = &L2ARC_dev_list;
7442 	l2arc_free_on_write = &L2ARC_free_on_write;
7443 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
7444 	    offsetof(l2arc_dev_t, l2ad_node));
7445 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
7446 	    offsetof(l2arc_data_free_t, l2df_list_node));
7447 }
7448 
7449 void
7450 l2arc_fini(void)
7451 {
7452 	/*
7453 	 * This is called from dmu_fini(), which is called from spa_fini();
7454 	 * Because of this, we can assume that all l2arc devices have
7455 	 * already been removed when the pools themselves were removed.
7456 	 */
7457 
7458 	l2arc_do_free_on_write();
7459 
7460 	mutex_destroy(&l2arc_feed_thr_lock);
7461 	cv_destroy(&l2arc_feed_thr_cv);
7462 	mutex_destroy(&l2arc_dev_mtx);
7463 	mutex_destroy(&l2arc_free_on_write_mtx);
7464 
7465 	list_destroy(l2arc_dev_list);
7466 	list_destroy(l2arc_free_on_write);
7467 }
7468 
7469 void
7470 l2arc_start(void)
7471 {
7472 	if (!(spa_mode_global & FWRITE))
7473 		return;
7474 
7475 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
7476 	    TS_RUN, minclsyspri);
7477 }
7478 
7479 void
7480 l2arc_stop(void)
7481 {
7482 	if (!(spa_mode_global & FWRITE))
7483 		return;
7484 
7485 	mutex_enter(&l2arc_feed_thr_lock);
7486 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
7487 	l2arc_thread_exit = 1;
7488 	while (l2arc_thread_exit != 0)
7489 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
7490 	mutex_exit(&l2arc_feed_thr_lock);
7491 }
7492