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