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