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