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