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