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