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