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