xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision a3f829ae41ece20e7f5f63604e177aeeb8b24628)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * DVA-based Adjustable Replacement Cache
28  *
29  * While much of the theory of operation used here is
30  * based on the self-tuning, low overhead replacement cache
31  * presented by Megiddo and Modha at FAST 2003, there are some
32  * significant differences:
33  *
34  * 1. The Megiddo and Modha model assumes any page is evictable.
35  * Pages in its cache cannot be "locked" into memory.  This makes
36  * the eviction algorithm simple: evict the last page in the list.
37  * This also make the performance characteristics easy to reason
38  * about.  Our cache is not so simple.  At any given moment, some
39  * subset of the blocks in the cache are un-evictable because we
40  * have handed out a reference to them.  Blocks are only evictable
41  * when there are no external references active.  This makes
42  * eviction far more problematic:  we choose to evict the evictable
43  * blocks that are the "lowest" in the list.
44  *
45  * There are times when it is not possible to evict the requested
46  * space.  In these circumstances we are unable to adjust the cache
47  * size.  To prevent the cache growing unbounded at these times we
48  * implement a "cache throttle" that slows the flow of new data
49  * into the cache until we can make space available.
50  *
51  * 2. The Megiddo and Modha model assumes a fixed cache size.
52  * Pages are evicted when the cache is full and there is a cache
53  * miss.  Our model has a variable sized cache.  It grows with
54  * high use, but also tries to react to memory pressure from the
55  * operating system: decreasing its size when system memory is
56  * tight.
57  *
58  * 3. The Megiddo and Modha model assumes a fixed page size. All
59  * elements of the cache are therefor exactly the same size.  So
60  * when adjusting the cache size following a cache miss, its simply
61  * a matter of choosing a single page to evict.  In our model, we
62  * have variable sized cache blocks (rangeing from 512 bytes to
63  * 128K bytes).  We therefor choose a set of blocks to evict to make
64  * space for a cache miss that approximates as closely as possible
65  * the space used by the new block.
66  *
67  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
68  * by N. Megiddo & D. Modha, FAST 2003
69  */
70 
71 /*
72  * The locking model:
73  *
74  * A new reference to a cache buffer can be obtained in two
75  * ways: 1) via a hash table lookup using the DVA as a key,
76  * or 2) via one of the ARC lists.  The arc_read() interface
77  * uses method 1, while the internal arc algorithms for
78  * adjusting the cache use method 2.  We therefor provide two
79  * types of locks: 1) the hash table lock array, and 2) the
80  * arc list locks.
81  *
82  * Buffers do not have their own mutexs, rather they rely on the
83  * hash table mutexs for the bulk of their protection (i.e. most
84  * fields in the arc_buf_hdr_t are protected by these mutexs).
85  *
86  * buf_hash_find() returns the appropriate mutex (held) when it
87  * locates the requested buffer in the hash table.  It returns
88  * NULL for the mutex if the buffer was not in the table.
89  *
90  * buf_hash_remove() expects the appropriate hash mutex to be
91  * already held before it is invoked.
92  *
93  * Each arc state also has a mutex which is used to protect the
94  * buffer list associated with the state.  When attempting to
95  * obtain a hash table lock while holding an arc list lock you
96  * must use: mutex_tryenter() to avoid deadlock.  Also note that
97  * the active state mutex must be held before the ghost state mutex.
98  *
99  * Arc buffers may have an associated eviction callback function.
100  * This function will be invoked prior to removing the buffer (e.g.
101  * in arc_do_user_evicts()).  Note however that the data associated
102  * with the buffer may be evicted prior to the callback.  The callback
103  * must be made with *no locks held* (to prevent deadlock).  Additionally,
104  * the users of callbacks must ensure that their private data is
105  * protected from simultaneous callbacks from arc_buf_evict()
106  * and arc_do_user_evicts().
107  *
108  * Note that the majority of the performance stats are manipulated
109  * with atomic operations.
110  *
111  * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
112  *
113  *	- L2ARC buflist creation
114  *	- L2ARC buflist eviction
115  *	- L2ARC write completion, which walks L2ARC buflists
116  *	- ARC header destruction, as it removes from L2ARC buflists
117  *	- ARC header release, as it removes from L2ARC buflists
118  */
119 
120 #include <sys/spa.h>
121 #include <sys/zio.h>
122 #include <sys/zio_checksum.h>
123 #include <sys/zfs_context.h>
124 #include <sys/arc.h>
125 #include <sys/refcount.h>
126 #include <sys/vdev.h>
127 #ifdef _KERNEL
128 #include <sys/vmsystm.h>
129 #include <vm/anon.h>
130 #include <sys/fs/swapnode.h>
131 #include <sys/dnlc.h>
132 #endif
133 #include <sys/callb.h>
134 #include <sys/kstat.h>
135 
136 static kmutex_t		arc_reclaim_thr_lock;
137 static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
138 static uint8_t		arc_thread_exit;
139 
140 extern int zfs_write_limit_shift;
141 extern uint64_t zfs_write_limit_max;
142 extern kmutex_t zfs_write_limit_lock;
143 
144 #define	ARC_REDUCE_DNLC_PERCENT	3
145 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
146 
147 typedef enum arc_reclaim_strategy {
148 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
149 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
150 } arc_reclaim_strategy_t;
151 
152 /* number of seconds before growing cache again */
153 static int		arc_grow_retry = 60;
154 
155 /* shift of arc_c for calculating both min and max arc_p */
156 static int		arc_p_min_shift = 4;
157 
158 /* log2(fraction of arc to reclaim) */
159 static int		arc_shrink_shift = 5;
160 
161 /*
162  * minimum lifespan of a prefetch block in clock ticks
163  * (initialized in arc_init())
164  */
165 static int		arc_min_prefetch_lifespan;
166 
167 static int arc_dead;
168 
169 /*
170  * The arc has filled available memory and has now warmed up.
171  */
172 static boolean_t arc_warm;
173 
174 /*
175  * These tunables are for performance analysis.
176  */
177 uint64_t zfs_arc_max;
178 uint64_t zfs_arc_min;
179 uint64_t zfs_arc_meta_limit = 0;
180 int zfs_mdcomp_disable = 0;
181 int zfs_arc_grow_retry = 0;
182 int zfs_arc_shrink_shift = 0;
183 int zfs_arc_p_min_shift = 0;
184 
185 /*
186  * Note that buffers can be in one of 6 states:
187  *	ARC_anon	- anonymous (discussed below)
188  *	ARC_mru		- recently used, currently cached
189  *	ARC_mru_ghost	- recentely used, no longer in cache
190  *	ARC_mfu		- frequently used, currently cached
191  *	ARC_mfu_ghost	- frequently used, no longer in cache
192  *	ARC_l2c_only	- exists in L2ARC but not other states
193  * When there are no active references to the buffer, they are
194  * are linked onto a list in one of these arc states.  These are
195  * the only buffers that can be evicted or deleted.  Within each
196  * state there are multiple lists, one for meta-data and one for
197  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
198  * etc.) is tracked separately so that it can be managed more
199  * explicitly: favored over data, limited explicitly.
200  *
201  * Anonymous buffers are buffers that are not associated with
202  * a DVA.  These are buffers that hold dirty block copies
203  * before they are written to stable storage.  By definition,
204  * they are "ref'd" and are considered part of arc_mru
205  * that cannot be freed.  Generally, they will aquire a DVA
206  * as they are written and migrate onto the arc_mru list.
207  *
208  * The ARC_l2c_only state is for buffers that are in the second
209  * level ARC but no longer in any of the ARC_m* lists.  The second
210  * level ARC itself may also contain buffers that are in any of
211  * the ARC_m* states - meaning that a buffer can exist in two
212  * places.  The reason for the ARC_l2c_only state is to keep the
213  * buffer header in the hash table, so that reads that hit the
214  * second level ARC benefit from these fast lookups.
215  */
216 
217 typedef struct arc_state {
218 	list_t	arcs_list[ARC_BUFC_NUMTYPES];	/* list of evictable buffers */
219 	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
220 	uint64_t arcs_size;	/* total amount of data in this state */
221 	kmutex_t arcs_mtx;
222 } arc_state_t;
223 
224 /* The 6 states: */
225 static arc_state_t ARC_anon;
226 static arc_state_t ARC_mru;
227 static arc_state_t ARC_mru_ghost;
228 static arc_state_t ARC_mfu;
229 static arc_state_t ARC_mfu_ghost;
230 static arc_state_t ARC_l2c_only;
231 
232 typedef struct arc_stats {
233 	kstat_named_t arcstat_hits;
234 	kstat_named_t arcstat_misses;
235 	kstat_named_t arcstat_demand_data_hits;
236 	kstat_named_t arcstat_demand_data_misses;
237 	kstat_named_t arcstat_demand_metadata_hits;
238 	kstat_named_t arcstat_demand_metadata_misses;
239 	kstat_named_t arcstat_prefetch_data_hits;
240 	kstat_named_t arcstat_prefetch_data_misses;
241 	kstat_named_t arcstat_prefetch_metadata_hits;
242 	kstat_named_t arcstat_prefetch_metadata_misses;
243 	kstat_named_t arcstat_mru_hits;
244 	kstat_named_t arcstat_mru_ghost_hits;
245 	kstat_named_t arcstat_mfu_hits;
246 	kstat_named_t arcstat_mfu_ghost_hits;
247 	kstat_named_t arcstat_deleted;
248 	kstat_named_t arcstat_recycle_miss;
249 	kstat_named_t arcstat_mutex_miss;
250 	kstat_named_t arcstat_evict_skip;
251 	kstat_named_t arcstat_hash_elements;
252 	kstat_named_t arcstat_hash_elements_max;
253 	kstat_named_t arcstat_hash_collisions;
254 	kstat_named_t arcstat_hash_chains;
255 	kstat_named_t arcstat_hash_chain_max;
256 	kstat_named_t arcstat_p;
257 	kstat_named_t arcstat_c;
258 	kstat_named_t arcstat_c_min;
259 	kstat_named_t arcstat_c_max;
260 	kstat_named_t arcstat_size;
261 	kstat_named_t arcstat_hdr_size;
262 	kstat_named_t arcstat_data_size;
263 	kstat_named_t arcstat_other_size;
264 	kstat_named_t arcstat_l2_hits;
265 	kstat_named_t arcstat_l2_misses;
266 	kstat_named_t arcstat_l2_feeds;
267 	kstat_named_t arcstat_l2_rw_clash;
268 	kstat_named_t arcstat_l2_read_bytes;
269 	kstat_named_t arcstat_l2_write_bytes;
270 	kstat_named_t arcstat_l2_writes_sent;
271 	kstat_named_t arcstat_l2_writes_done;
272 	kstat_named_t arcstat_l2_writes_error;
273 	kstat_named_t arcstat_l2_writes_hdr_miss;
274 	kstat_named_t arcstat_l2_evict_lock_retry;
275 	kstat_named_t arcstat_l2_evict_reading;
276 	kstat_named_t arcstat_l2_free_on_write;
277 	kstat_named_t arcstat_l2_abort_lowmem;
278 	kstat_named_t arcstat_l2_cksum_bad;
279 	kstat_named_t arcstat_l2_io_error;
280 	kstat_named_t arcstat_l2_size;
281 	kstat_named_t arcstat_l2_hdr_size;
282 	kstat_named_t arcstat_memory_throttle_count;
283 } arc_stats_t;
284 
285 static arc_stats_t arc_stats = {
286 	{ "hits",			KSTAT_DATA_UINT64 },
287 	{ "misses",			KSTAT_DATA_UINT64 },
288 	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
289 	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
290 	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
291 	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
292 	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
293 	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
294 	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
295 	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
296 	{ "mru_hits",			KSTAT_DATA_UINT64 },
297 	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
298 	{ "mfu_hits",			KSTAT_DATA_UINT64 },
299 	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
300 	{ "deleted",			KSTAT_DATA_UINT64 },
301 	{ "recycle_miss",		KSTAT_DATA_UINT64 },
302 	{ "mutex_miss",			KSTAT_DATA_UINT64 },
303 	{ "evict_skip",			KSTAT_DATA_UINT64 },
304 	{ "hash_elements",		KSTAT_DATA_UINT64 },
305 	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
306 	{ "hash_collisions",		KSTAT_DATA_UINT64 },
307 	{ "hash_chains",		KSTAT_DATA_UINT64 },
308 	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
309 	{ "p",				KSTAT_DATA_UINT64 },
310 	{ "c",				KSTAT_DATA_UINT64 },
311 	{ "c_min",			KSTAT_DATA_UINT64 },
312 	{ "c_max",			KSTAT_DATA_UINT64 },
313 	{ "size",			KSTAT_DATA_UINT64 },
314 	{ "hdr_size",			KSTAT_DATA_UINT64 },
315 	{ "data_size",			KSTAT_DATA_UINT64 },
316 	{ "other_size",			KSTAT_DATA_UINT64 },
317 	{ "l2_hits",			KSTAT_DATA_UINT64 },
318 	{ "l2_misses",			KSTAT_DATA_UINT64 },
319 	{ "l2_feeds",			KSTAT_DATA_UINT64 },
320 	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
321 	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
322 	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
323 	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
324 	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
325 	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
326 	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
327 	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
328 	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
329 	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
330 	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
331 	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
332 	{ "l2_io_error",		KSTAT_DATA_UINT64 },
333 	{ "l2_size",			KSTAT_DATA_UINT64 },
334 	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
335 	{ "memory_throttle_count",	KSTAT_DATA_UINT64 }
336 };
337 
338 #define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
339 
340 #define	ARCSTAT_INCR(stat, val) \
341 	atomic_add_64(&arc_stats.stat.value.ui64, (val));
342 
343 #define	ARCSTAT_BUMP(stat) 	ARCSTAT_INCR(stat, 1)
344 #define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
345 
346 #define	ARCSTAT_MAX(stat, val) {					\
347 	uint64_t m;							\
348 	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
349 	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
350 		continue;						\
351 }
352 
353 #define	ARCSTAT_MAXSTAT(stat) \
354 	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
355 
356 /*
357  * We define a macro to allow ARC hits/misses to be easily broken down by
358  * two separate conditions, giving a total of four different subtypes for
359  * each of hits and misses (so eight statistics total).
360  */
361 #define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
362 	if (cond1) {							\
363 		if (cond2) {						\
364 			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
365 		} else {						\
366 			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
367 		}							\
368 	} else {							\
369 		if (cond2) {						\
370 			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
371 		} else {						\
372 			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
373 		}							\
374 	}
375 
376 kstat_t			*arc_ksp;
377 static arc_state_t 	*arc_anon;
378 static arc_state_t	*arc_mru;
379 static arc_state_t	*arc_mru_ghost;
380 static arc_state_t	*arc_mfu;
381 static arc_state_t	*arc_mfu_ghost;
382 static arc_state_t	*arc_l2c_only;
383 
384 /*
385  * There are several ARC variables that are critical to export as kstats --
386  * but we don't want to have to grovel around in the kstat whenever we wish to
387  * manipulate them.  For these variables, we therefore define them to be in
388  * terms of the statistic variable.  This assures that we are not introducing
389  * the possibility of inconsistency by having shadow copies of the variables,
390  * while still allowing the code to be readable.
391  */
392 #define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
393 #define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
394 #define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
395 #define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
396 #define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
397 
398 static int		arc_no_grow;	/* Don't try to grow cache size */
399 static uint64_t		arc_tempreserve;
400 static uint64_t		arc_meta_used;
401 static uint64_t		arc_meta_limit;
402 static uint64_t		arc_meta_max = 0;
403 
404 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
405 
406 typedef struct arc_callback arc_callback_t;
407 
408 struct arc_callback {
409 	void			*acb_private;
410 	arc_done_func_t		*acb_done;
411 	arc_buf_t		*acb_buf;
412 	zio_t			*acb_zio_dummy;
413 	arc_callback_t		*acb_next;
414 };
415 
416 typedef struct arc_write_callback arc_write_callback_t;
417 
418 struct arc_write_callback {
419 	void		*awcb_private;
420 	arc_done_func_t	*awcb_ready;
421 	arc_done_func_t	*awcb_done;
422 	arc_buf_t	*awcb_buf;
423 };
424 
425 struct arc_buf_hdr {
426 	/* protected by hash lock */
427 	dva_t			b_dva;
428 	uint64_t		b_birth;
429 	uint64_t		b_cksum0;
430 
431 	kmutex_t		b_freeze_lock;
432 	zio_cksum_t		*b_freeze_cksum;
433 
434 	arc_buf_hdr_t		*b_hash_next;
435 	arc_buf_t		*b_buf;
436 	uint32_t		b_flags;
437 	uint32_t		b_datacnt;
438 
439 	arc_callback_t		*b_acb;
440 	kcondvar_t		b_cv;
441 
442 	/* immutable */
443 	arc_buf_contents_t	b_type;
444 	uint64_t		b_size;
445 	spa_t			*b_spa;
446 
447 	/* protected by arc state mutex */
448 	arc_state_t		*b_state;
449 	list_node_t		b_arc_node;
450 
451 	/* updated atomically */
452 	clock_t			b_arc_access;
453 
454 	/* self protecting */
455 	refcount_t		b_refcnt;
456 
457 	l2arc_buf_hdr_t		*b_l2hdr;
458 	list_node_t		b_l2node;
459 };
460 
461 static arc_buf_t *arc_eviction_list;
462 static kmutex_t arc_eviction_mtx;
463 static arc_buf_hdr_t arc_eviction_hdr;
464 static void arc_get_data_buf(arc_buf_t *buf);
465 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
466 static int arc_evict_needed(arc_buf_contents_t type);
467 static void arc_evict_ghost(arc_state_t *state, spa_t *spa, int64_t bytes);
468 
469 #define	GHOST_STATE(state)	\
470 	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
471 	(state) == arc_l2c_only)
472 
473 /*
474  * Private ARC flags.  These flags are private ARC only flags that will show up
475  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
476  * be passed in as arc_flags in things like arc_read.  However, these flags
477  * should never be passed and should only be set by ARC code.  When adding new
478  * public flags, make sure not to smash the private ones.
479  */
480 
481 #define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
482 #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
483 #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
484 #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
485 #define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
486 #define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
487 #define	ARC_FREE_IN_PROGRESS	(1 << 15)	/* hdr about to be freed */
488 #define	ARC_L2_WRITING		(1 << 16)	/* L2ARC write in progress */
489 #define	ARC_L2_EVICTED		(1 << 17)	/* evicted during I/O */
490 #define	ARC_L2_WRITE_HEAD	(1 << 18)	/* head of write list */
491 #define	ARC_STORED		(1 << 19)	/* has been store()d to */
492 
493 #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
494 #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
495 #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
496 #define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_PREFETCH)
497 #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
498 #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
499 #define	HDR_FREE_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
500 #define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_L2CACHE)
501 #define	HDR_L2_READING(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS &&	\
502 				    (hdr)->b_l2hdr != NULL)
503 #define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_L2_WRITING)
504 #define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_L2_EVICTED)
505 #define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_L2_WRITE_HEAD)
506 
507 /*
508  * Other sizes
509  */
510 
511 #define	HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
512 #define	L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
513 
514 /*
515  * Hash table routines
516  */
517 
518 #define	HT_LOCK_PAD	64
519 
520 struct ht_lock {
521 	kmutex_t	ht_lock;
522 #ifdef _KERNEL
523 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
524 #endif
525 };
526 
527 #define	BUF_LOCKS 256
528 typedef struct buf_hash_table {
529 	uint64_t ht_mask;
530 	arc_buf_hdr_t **ht_table;
531 	struct ht_lock ht_locks[BUF_LOCKS];
532 } buf_hash_table_t;
533 
534 static buf_hash_table_t buf_hash_table;
535 
536 #define	BUF_HASH_INDEX(spa, dva, birth) \
537 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
538 #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
539 #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
540 #define	HDR_LOCK(buf) \
541 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
542 
543 uint64_t zfs_crc64_table[256];
544 
545 /*
546  * Level 2 ARC
547  */
548 
549 #define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
550 #define	L2ARC_HEADROOM		2		/* num of writes */
551 #define	L2ARC_FEED_SECS		1		/* caching interval secs */
552 #define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
553 
554 #define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
555 #define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
556 
557 /*
558  * L2ARC Performance Tunables
559  */
560 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
561 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
562 uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
563 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
564 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
565 boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
566 boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
567 boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
568 
569 /*
570  * L2ARC Internals
571  */
572 typedef struct l2arc_dev {
573 	vdev_t			*l2ad_vdev;	/* vdev */
574 	spa_t			*l2ad_spa;	/* spa */
575 	uint64_t		l2ad_hand;	/* next write location */
576 	uint64_t		l2ad_write;	/* desired write size, bytes */
577 	uint64_t		l2ad_boost;	/* warmup write boost, bytes */
578 	uint64_t		l2ad_start;	/* first addr on device */
579 	uint64_t		l2ad_end;	/* last addr on device */
580 	uint64_t		l2ad_evict;	/* last addr eviction reached */
581 	boolean_t		l2ad_first;	/* first sweep through */
582 	boolean_t		l2ad_writing;	/* currently writing */
583 	list_t			*l2ad_buflist;	/* buffer list */
584 	list_node_t		l2ad_node;	/* device list node */
585 } l2arc_dev_t;
586 
587 static list_t L2ARC_dev_list;			/* device list */
588 static list_t *l2arc_dev_list;			/* device list pointer */
589 static kmutex_t l2arc_dev_mtx;			/* device list mutex */
590 static l2arc_dev_t *l2arc_dev_last;		/* last device used */
591 static kmutex_t l2arc_buflist_mtx;		/* mutex for all buflists */
592 static list_t L2ARC_free_on_write;		/* free after write buf list */
593 static list_t *l2arc_free_on_write;		/* free after write list ptr */
594 static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
595 static uint64_t l2arc_ndev;			/* number of devices */
596 
597 typedef struct l2arc_read_callback {
598 	arc_buf_t	*l2rcb_buf;		/* read buffer */
599 	spa_t		*l2rcb_spa;		/* spa */
600 	blkptr_t	l2rcb_bp;		/* original blkptr */
601 	zbookmark_t	l2rcb_zb;		/* original bookmark */
602 	int		l2rcb_flags;		/* original flags */
603 } l2arc_read_callback_t;
604 
605 typedef struct l2arc_write_callback {
606 	l2arc_dev_t	*l2wcb_dev;		/* device info */
607 	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
608 } l2arc_write_callback_t;
609 
610 struct l2arc_buf_hdr {
611 	/* protected by arc_buf_hdr  mutex */
612 	l2arc_dev_t	*b_dev;			/* L2ARC device */
613 	daddr_t		b_daddr;		/* disk address, offset byte */
614 };
615 
616 typedef struct l2arc_data_free {
617 	/* protected by l2arc_free_on_write_mtx */
618 	void		*l2df_data;
619 	size_t		l2df_size;
620 	void		(*l2df_func)(void *, size_t);
621 	list_node_t	l2df_list_node;
622 } l2arc_data_free_t;
623 
624 static kmutex_t l2arc_feed_thr_lock;
625 static kcondvar_t l2arc_feed_thr_cv;
626 static uint8_t l2arc_thread_exit;
627 
628 static void l2arc_read_done(zio_t *zio);
629 static void l2arc_hdr_stat_add(void);
630 static void l2arc_hdr_stat_remove(void);
631 
632 static uint64_t
633 buf_hash(spa_t *spa, const dva_t *dva, uint64_t birth)
634 {
635 	uintptr_t spav = (uintptr_t)spa;
636 	uint8_t *vdva = (uint8_t *)dva;
637 	uint64_t crc = -1ULL;
638 	int i;
639 
640 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
641 
642 	for (i = 0; i < sizeof (dva_t); i++)
643 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
644 
645 	crc ^= (spav>>8) ^ birth;
646 
647 	return (crc);
648 }
649 
650 #define	BUF_EMPTY(buf)						\
651 	((buf)->b_dva.dva_word[0] == 0 &&			\
652 	(buf)->b_dva.dva_word[1] == 0 &&			\
653 	(buf)->b_birth == 0)
654 
655 #define	BUF_EQUAL(spa, dva, birth, buf)				\
656 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
657 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
658 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
659 
660 static arc_buf_hdr_t *
661 buf_hash_find(spa_t *spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
662 {
663 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
664 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
665 	arc_buf_hdr_t *buf;
666 
667 	mutex_enter(hash_lock);
668 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
669 	    buf = buf->b_hash_next) {
670 		if (BUF_EQUAL(spa, dva, birth, buf)) {
671 			*lockp = hash_lock;
672 			return (buf);
673 		}
674 	}
675 	mutex_exit(hash_lock);
676 	*lockp = NULL;
677 	return (NULL);
678 }
679 
680 /*
681  * Insert an entry into the hash table.  If there is already an element
682  * equal to elem in the hash table, then the already existing element
683  * will be returned and the new element will not be inserted.
684  * Otherwise returns NULL.
685  */
686 static arc_buf_hdr_t *
687 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
688 {
689 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
690 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
691 	arc_buf_hdr_t *fbuf;
692 	uint32_t i;
693 
694 	ASSERT(!HDR_IN_HASH_TABLE(buf));
695 	*lockp = hash_lock;
696 	mutex_enter(hash_lock);
697 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
698 	    fbuf = fbuf->b_hash_next, i++) {
699 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
700 			return (fbuf);
701 	}
702 
703 	buf->b_hash_next = buf_hash_table.ht_table[idx];
704 	buf_hash_table.ht_table[idx] = buf;
705 	buf->b_flags |= ARC_IN_HASH_TABLE;
706 
707 	/* collect some hash table performance data */
708 	if (i > 0) {
709 		ARCSTAT_BUMP(arcstat_hash_collisions);
710 		if (i == 1)
711 			ARCSTAT_BUMP(arcstat_hash_chains);
712 
713 		ARCSTAT_MAX(arcstat_hash_chain_max, i);
714 	}
715 
716 	ARCSTAT_BUMP(arcstat_hash_elements);
717 	ARCSTAT_MAXSTAT(arcstat_hash_elements);
718 
719 	return (NULL);
720 }
721 
722 static void
723 buf_hash_remove(arc_buf_hdr_t *buf)
724 {
725 	arc_buf_hdr_t *fbuf, **bufp;
726 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
727 
728 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
729 	ASSERT(HDR_IN_HASH_TABLE(buf));
730 
731 	bufp = &buf_hash_table.ht_table[idx];
732 	while ((fbuf = *bufp) != buf) {
733 		ASSERT(fbuf != NULL);
734 		bufp = &fbuf->b_hash_next;
735 	}
736 	*bufp = buf->b_hash_next;
737 	buf->b_hash_next = NULL;
738 	buf->b_flags &= ~ARC_IN_HASH_TABLE;
739 
740 	/* collect some hash table performance data */
741 	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
742 
743 	if (buf_hash_table.ht_table[idx] &&
744 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
745 		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
746 }
747 
748 /*
749  * Global data structures and functions for the buf kmem cache.
750  */
751 static kmem_cache_t *hdr_cache;
752 static kmem_cache_t *buf_cache;
753 
754 static void
755 buf_fini(void)
756 {
757 	int i;
758 
759 	kmem_free(buf_hash_table.ht_table,
760 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
761 	for (i = 0; i < BUF_LOCKS; i++)
762 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
763 	kmem_cache_destroy(hdr_cache);
764 	kmem_cache_destroy(buf_cache);
765 }
766 
767 /*
768  * Constructor callback - called when the cache is empty
769  * and a new buf is requested.
770  */
771 /* ARGSUSED */
772 static int
773 hdr_cons(void *vbuf, void *unused, int kmflag)
774 {
775 	arc_buf_hdr_t *buf = vbuf;
776 
777 	bzero(buf, sizeof (arc_buf_hdr_t));
778 	refcount_create(&buf->b_refcnt);
779 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
780 	mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
781 	arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
782 
783 	return (0);
784 }
785 
786 /* ARGSUSED */
787 static int
788 buf_cons(void *vbuf, void *unused, int kmflag)
789 {
790 	arc_buf_t *buf = vbuf;
791 
792 	bzero(buf, sizeof (arc_buf_t));
793 	rw_init(&buf->b_lock, NULL, RW_DEFAULT, NULL);
794 	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
795 
796 	return (0);
797 }
798 
799 /*
800  * Destructor callback - called when a cached buf is
801  * no longer required.
802  */
803 /* ARGSUSED */
804 static void
805 hdr_dest(void *vbuf, void *unused)
806 {
807 	arc_buf_hdr_t *buf = vbuf;
808 
809 	refcount_destroy(&buf->b_refcnt);
810 	cv_destroy(&buf->b_cv);
811 	mutex_destroy(&buf->b_freeze_lock);
812 	arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
813 }
814 
815 /* ARGSUSED */
816 static void
817 buf_dest(void *vbuf, void *unused)
818 {
819 	arc_buf_t *buf = vbuf;
820 
821 	rw_destroy(&buf->b_lock);
822 	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
823 }
824 
825 /*
826  * Reclaim callback -- invoked when memory is low.
827  */
828 /* ARGSUSED */
829 static void
830 hdr_recl(void *unused)
831 {
832 	dprintf("hdr_recl called\n");
833 	/*
834 	 * umem calls the reclaim func when we destroy the buf cache,
835 	 * which is after we do arc_fini().
836 	 */
837 	if (!arc_dead)
838 		cv_signal(&arc_reclaim_thr_cv);
839 }
840 
841 static void
842 buf_init(void)
843 {
844 	uint64_t *ct;
845 	uint64_t hsize = 1ULL << 12;
846 	int i, j;
847 
848 	/*
849 	 * The hash table is big enough to fill all of physical memory
850 	 * with an average 64K block size.  The table will take up
851 	 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
852 	 */
853 	while (hsize * 65536 < physmem * PAGESIZE)
854 		hsize <<= 1;
855 retry:
856 	buf_hash_table.ht_mask = hsize - 1;
857 	buf_hash_table.ht_table =
858 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
859 	if (buf_hash_table.ht_table == NULL) {
860 		ASSERT(hsize > (1ULL << 8));
861 		hsize >>= 1;
862 		goto retry;
863 	}
864 
865 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
866 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
867 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
868 	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
869 
870 	for (i = 0; i < 256; i++)
871 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
872 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
873 
874 	for (i = 0; i < BUF_LOCKS; i++) {
875 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
876 		    NULL, MUTEX_DEFAULT, NULL);
877 	}
878 }
879 
880 #define	ARC_MINTIME	(hz>>4) /* 62 ms */
881 
882 static void
883 arc_cksum_verify(arc_buf_t *buf)
884 {
885 	zio_cksum_t zc;
886 
887 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
888 		return;
889 
890 	mutex_enter(&buf->b_hdr->b_freeze_lock);
891 	if (buf->b_hdr->b_freeze_cksum == NULL ||
892 	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
893 		mutex_exit(&buf->b_hdr->b_freeze_lock);
894 		return;
895 	}
896 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
897 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
898 		panic("buffer modified while frozen!");
899 	mutex_exit(&buf->b_hdr->b_freeze_lock);
900 }
901 
902 static int
903 arc_cksum_equal(arc_buf_t *buf)
904 {
905 	zio_cksum_t zc;
906 	int equal;
907 
908 	mutex_enter(&buf->b_hdr->b_freeze_lock);
909 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
910 	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
911 	mutex_exit(&buf->b_hdr->b_freeze_lock);
912 
913 	return (equal);
914 }
915 
916 static void
917 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
918 {
919 	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
920 		return;
921 
922 	mutex_enter(&buf->b_hdr->b_freeze_lock);
923 	if (buf->b_hdr->b_freeze_cksum != NULL) {
924 		mutex_exit(&buf->b_hdr->b_freeze_lock);
925 		return;
926 	}
927 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
928 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
929 	    buf->b_hdr->b_freeze_cksum);
930 	mutex_exit(&buf->b_hdr->b_freeze_lock);
931 }
932 
933 void
934 arc_buf_thaw(arc_buf_t *buf)
935 {
936 	if (zfs_flags & ZFS_DEBUG_MODIFY) {
937 		if (buf->b_hdr->b_state != arc_anon)
938 			panic("modifying non-anon buffer!");
939 		if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
940 			panic("modifying buffer while i/o in progress!");
941 		arc_cksum_verify(buf);
942 	}
943 
944 	mutex_enter(&buf->b_hdr->b_freeze_lock);
945 	if (buf->b_hdr->b_freeze_cksum != NULL) {
946 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
947 		buf->b_hdr->b_freeze_cksum = NULL;
948 	}
949 	mutex_exit(&buf->b_hdr->b_freeze_lock);
950 }
951 
952 void
953 arc_buf_freeze(arc_buf_t *buf)
954 {
955 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
956 		return;
957 
958 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
959 	    buf->b_hdr->b_state == arc_anon);
960 	arc_cksum_compute(buf, B_FALSE);
961 }
962 
963 static void
964 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
965 {
966 	ASSERT(MUTEX_HELD(hash_lock));
967 
968 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
969 	    (ab->b_state != arc_anon)) {
970 		uint64_t delta = ab->b_size * ab->b_datacnt;
971 		list_t *list = &ab->b_state->arcs_list[ab->b_type];
972 		uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
973 
974 		ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
975 		mutex_enter(&ab->b_state->arcs_mtx);
976 		ASSERT(list_link_active(&ab->b_arc_node));
977 		list_remove(list, ab);
978 		if (GHOST_STATE(ab->b_state)) {
979 			ASSERT3U(ab->b_datacnt, ==, 0);
980 			ASSERT3P(ab->b_buf, ==, NULL);
981 			delta = ab->b_size;
982 		}
983 		ASSERT(delta > 0);
984 		ASSERT3U(*size, >=, delta);
985 		atomic_add_64(size, -delta);
986 		mutex_exit(&ab->b_state->arcs_mtx);
987 		/* remove the prefetch flag if we get a reference */
988 		if (ab->b_flags & ARC_PREFETCH)
989 			ab->b_flags &= ~ARC_PREFETCH;
990 	}
991 }
992 
993 static int
994 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
995 {
996 	int cnt;
997 	arc_state_t *state = ab->b_state;
998 
999 	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1000 	ASSERT(!GHOST_STATE(state));
1001 
1002 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1003 	    (state != arc_anon)) {
1004 		uint64_t *size = &state->arcs_lsize[ab->b_type];
1005 
1006 		ASSERT(!MUTEX_HELD(&state->arcs_mtx));
1007 		mutex_enter(&state->arcs_mtx);
1008 		ASSERT(!list_link_active(&ab->b_arc_node));
1009 		list_insert_head(&state->arcs_list[ab->b_type], ab);
1010 		ASSERT(ab->b_datacnt > 0);
1011 		atomic_add_64(size, ab->b_size * ab->b_datacnt);
1012 		mutex_exit(&state->arcs_mtx);
1013 	}
1014 	return (cnt);
1015 }
1016 
1017 /*
1018  * Move the supplied buffer to the indicated state.  The mutex
1019  * for the buffer must be held by the caller.
1020  */
1021 static void
1022 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1023 {
1024 	arc_state_t *old_state = ab->b_state;
1025 	int64_t refcnt = refcount_count(&ab->b_refcnt);
1026 	uint64_t from_delta, to_delta;
1027 
1028 	ASSERT(MUTEX_HELD(hash_lock));
1029 	ASSERT(new_state != old_state);
1030 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1031 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1032 
1033 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
1034 
1035 	/*
1036 	 * If this buffer is evictable, transfer it from the
1037 	 * old state list to the new state list.
1038 	 */
1039 	if (refcnt == 0) {
1040 		if (old_state != arc_anon) {
1041 			int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
1042 			uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1043 
1044 			if (use_mutex)
1045 				mutex_enter(&old_state->arcs_mtx);
1046 
1047 			ASSERT(list_link_active(&ab->b_arc_node));
1048 			list_remove(&old_state->arcs_list[ab->b_type], ab);
1049 
1050 			/*
1051 			 * If prefetching out of the ghost cache,
1052 			 * we will have a non-null datacnt.
1053 			 */
1054 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1055 				/* ghost elements have a ghost size */
1056 				ASSERT(ab->b_buf == NULL);
1057 				from_delta = ab->b_size;
1058 			}
1059 			ASSERT3U(*size, >=, from_delta);
1060 			atomic_add_64(size, -from_delta);
1061 
1062 			if (use_mutex)
1063 				mutex_exit(&old_state->arcs_mtx);
1064 		}
1065 		if (new_state != arc_anon) {
1066 			int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
1067 			uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1068 
1069 			if (use_mutex)
1070 				mutex_enter(&new_state->arcs_mtx);
1071 
1072 			list_insert_head(&new_state->arcs_list[ab->b_type], ab);
1073 
1074 			/* ghost elements have a ghost size */
1075 			if (GHOST_STATE(new_state)) {
1076 				ASSERT(ab->b_datacnt == 0);
1077 				ASSERT(ab->b_buf == NULL);
1078 				to_delta = ab->b_size;
1079 			}
1080 			atomic_add_64(size, to_delta);
1081 
1082 			if (use_mutex)
1083 				mutex_exit(&new_state->arcs_mtx);
1084 		}
1085 	}
1086 
1087 	ASSERT(!BUF_EMPTY(ab));
1088 	if (new_state == arc_anon) {
1089 		buf_hash_remove(ab);
1090 	}
1091 
1092 	/* adjust state sizes */
1093 	if (to_delta)
1094 		atomic_add_64(&new_state->arcs_size, to_delta);
1095 	if (from_delta) {
1096 		ASSERT3U(old_state->arcs_size, >=, from_delta);
1097 		atomic_add_64(&old_state->arcs_size, -from_delta);
1098 	}
1099 	ab->b_state = new_state;
1100 
1101 	/* adjust l2arc hdr stats */
1102 	if (new_state == arc_l2c_only)
1103 		l2arc_hdr_stat_add();
1104 	else if (old_state == arc_l2c_only)
1105 		l2arc_hdr_stat_remove();
1106 }
1107 
1108 void
1109 arc_space_consume(uint64_t space, arc_space_type_t type)
1110 {
1111 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1112 
1113 	switch (type) {
1114 	case ARC_SPACE_DATA:
1115 		ARCSTAT_INCR(arcstat_data_size, space);
1116 		break;
1117 	case ARC_SPACE_OTHER:
1118 		ARCSTAT_INCR(arcstat_other_size, space);
1119 		break;
1120 	case ARC_SPACE_HDRS:
1121 		ARCSTAT_INCR(arcstat_hdr_size, space);
1122 		break;
1123 	case ARC_SPACE_L2HDRS:
1124 		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1125 		break;
1126 	}
1127 
1128 	atomic_add_64(&arc_meta_used, space);
1129 	atomic_add_64(&arc_size, space);
1130 }
1131 
1132 void
1133 arc_space_return(uint64_t space, arc_space_type_t type)
1134 {
1135 	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1136 
1137 	switch (type) {
1138 	case ARC_SPACE_DATA:
1139 		ARCSTAT_INCR(arcstat_data_size, -space);
1140 		break;
1141 	case ARC_SPACE_OTHER:
1142 		ARCSTAT_INCR(arcstat_other_size, -space);
1143 		break;
1144 	case ARC_SPACE_HDRS:
1145 		ARCSTAT_INCR(arcstat_hdr_size, -space);
1146 		break;
1147 	case ARC_SPACE_L2HDRS:
1148 		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1149 		break;
1150 	}
1151 
1152 	ASSERT(arc_meta_used >= space);
1153 	if (arc_meta_max < arc_meta_used)
1154 		arc_meta_max = arc_meta_used;
1155 	atomic_add_64(&arc_meta_used, -space);
1156 	ASSERT(arc_size >= space);
1157 	atomic_add_64(&arc_size, -space);
1158 }
1159 
1160 void *
1161 arc_data_buf_alloc(uint64_t size)
1162 {
1163 	if (arc_evict_needed(ARC_BUFC_DATA))
1164 		cv_signal(&arc_reclaim_thr_cv);
1165 	atomic_add_64(&arc_size, size);
1166 	return (zio_data_buf_alloc(size));
1167 }
1168 
1169 void
1170 arc_data_buf_free(void *buf, uint64_t size)
1171 {
1172 	zio_data_buf_free(buf, size);
1173 	ASSERT(arc_size >= size);
1174 	atomic_add_64(&arc_size, -size);
1175 }
1176 
1177 arc_buf_t *
1178 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1179 {
1180 	arc_buf_hdr_t *hdr;
1181 	arc_buf_t *buf;
1182 
1183 	ASSERT3U(size, >, 0);
1184 	hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1185 	ASSERT(BUF_EMPTY(hdr));
1186 	hdr->b_size = size;
1187 	hdr->b_type = type;
1188 	hdr->b_spa = spa;
1189 	hdr->b_state = arc_anon;
1190 	hdr->b_arc_access = 0;
1191 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1192 	buf->b_hdr = hdr;
1193 	buf->b_data = NULL;
1194 	buf->b_efunc = NULL;
1195 	buf->b_private = NULL;
1196 	buf->b_next = NULL;
1197 	hdr->b_buf = buf;
1198 	arc_get_data_buf(buf);
1199 	hdr->b_datacnt = 1;
1200 	hdr->b_flags = 0;
1201 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1202 	(void) refcount_add(&hdr->b_refcnt, tag);
1203 
1204 	return (buf);
1205 }
1206 
1207 static arc_buf_t *
1208 arc_buf_clone(arc_buf_t *from)
1209 {
1210 	arc_buf_t *buf;
1211 	arc_buf_hdr_t *hdr = from->b_hdr;
1212 	uint64_t size = hdr->b_size;
1213 
1214 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1215 	buf->b_hdr = hdr;
1216 	buf->b_data = NULL;
1217 	buf->b_efunc = NULL;
1218 	buf->b_private = NULL;
1219 	buf->b_next = hdr->b_buf;
1220 	hdr->b_buf = buf;
1221 	arc_get_data_buf(buf);
1222 	bcopy(from->b_data, buf->b_data, size);
1223 	hdr->b_datacnt += 1;
1224 	return (buf);
1225 }
1226 
1227 void
1228 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1229 {
1230 	arc_buf_hdr_t *hdr;
1231 	kmutex_t *hash_lock;
1232 
1233 	/*
1234 	 * Check to see if this buffer is evicted.  Callers
1235 	 * must verify b_data != NULL to know if the add_ref
1236 	 * was successful.
1237 	 */
1238 	rw_enter(&buf->b_lock, RW_READER);
1239 	if (buf->b_data == NULL) {
1240 		rw_exit(&buf->b_lock);
1241 		return;
1242 	}
1243 	hdr = buf->b_hdr;
1244 	ASSERT(hdr != NULL);
1245 	hash_lock = HDR_LOCK(hdr);
1246 	mutex_enter(hash_lock);
1247 	rw_exit(&buf->b_lock);
1248 
1249 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1250 	add_reference(hdr, hash_lock, tag);
1251 	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1252 	arc_access(hdr, hash_lock);
1253 	mutex_exit(hash_lock);
1254 	ARCSTAT_BUMP(arcstat_hits);
1255 	ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1256 	    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1257 	    data, metadata, hits);
1258 }
1259 
1260 /*
1261  * Free the arc data buffer.  If it is an l2arc write in progress,
1262  * the buffer is placed on l2arc_free_on_write to be freed later.
1263  */
1264 static void
1265 arc_buf_data_free(arc_buf_hdr_t *hdr, void (*free_func)(void *, size_t),
1266     void *data, size_t size)
1267 {
1268 	if (HDR_L2_WRITING(hdr)) {
1269 		l2arc_data_free_t *df;
1270 		df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
1271 		df->l2df_data = data;
1272 		df->l2df_size = size;
1273 		df->l2df_func = free_func;
1274 		mutex_enter(&l2arc_free_on_write_mtx);
1275 		list_insert_head(l2arc_free_on_write, df);
1276 		mutex_exit(&l2arc_free_on_write_mtx);
1277 		ARCSTAT_BUMP(arcstat_l2_free_on_write);
1278 	} else {
1279 		free_func(data, size);
1280 	}
1281 }
1282 
1283 static void
1284 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
1285 {
1286 	arc_buf_t **bufp;
1287 
1288 	/* free up data associated with the buf */
1289 	if (buf->b_data) {
1290 		arc_state_t *state = buf->b_hdr->b_state;
1291 		uint64_t size = buf->b_hdr->b_size;
1292 		arc_buf_contents_t type = buf->b_hdr->b_type;
1293 
1294 		arc_cksum_verify(buf);
1295 		if (!recycle) {
1296 			if (type == ARC_BUFC_METADATA) {
1297 				arc_buf_data_free(buf->b_hdr, zio_buf_free,
1298 				    buf->b_data, size);
1299 				arc_space_return(size, ARC_SPACE_DATA);
1300 			} else {
1301 				ASSERT(type == ARC_BUFC_DATA);
1302 				arc_buf_data_free(buf->b_hdr,
1303 				    zio_data_buf_free, buf->b_data, size);
1304 				ARCSTAT_INCR(arcstat_data_size, -size);
1305 				atomic_add_64(&arc_size, -size);
1306 			}
1307 		}
1308 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
1309 			uint64_t *cnt = &state->arcs_lsize[type];
1310 
1311 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1312 			ASSERT(state != arc_anon);
1313 
1314 			ASSERT3U(*cnt, >=, size);
1315 			atomic_add_64(cnt, -size);
1316 		}
1317 		ASSERT3U(state->arcs_size, >=, size);
1318 		atomic_add_64(&state->arcs_size, -size);
1319 		buf->b_data = NULL;
1320 		ASSERT(buf->b_hdr->b_datacnt > 0);
1321 		buf->b_hdr->b_datacnt -= 1;
1322 	}
1323 
1324 	/* only remove the buf if requested */
1325 	if (!all)
1326 		return;
1327 
1328 	/* remove the buf from the hdr list */
1329 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1330 		continue;
1331 	*bufp = buf->b_next;
1332 
1333 	ASSERT(buf->b_efunc == NULL);
1334 
1335 	/* clean up the buf */
1336 	buf->b_hdr = NULL;
1337 	kmem_cache_free(buf_cache, buf);
1338 }
1339 
1340 static void
1341 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1342 {
1343 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
1344 	ASSERT3P(hdr->b_state, ==, arc_anon);
1345 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1346 	ASSERT(!(hdr->b_flags & ARC_STORED));
1347 
1348 	if (hdr->b_l2hdr != NULL) {
1349 		if (!MUTEX_HELD(&l2arc_buflist_mtx)) {
1350 			/*
1351 			 * To prevent arc_free() and l2arc_evict() from
1352 			 * attempting to free the same buffer at the same time,
1353 			 * a FREE_IN_PROGRESS flag is given to arc_free() to
1354 			 * give it priority.  l2arc_evict() can't destroy this
1355 			 * header while we are waiting on l2arc_buflist_mtx.
1356 			 *
1357 			 * The hdr may be removed from l2ad_buflist before we
1358 			 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1359 			 */
1360 			mutex_enter(&l2arc_buflist_mtx);
1361 			if (hdr->b_l2hdr != NULL) {
1362 				list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist,
1363 				    hdr);
1364 			}
1365 			mutex_exit(&l2arc_buflist_mtx);
1366 		} else {
1367 			list_remove(hdr->b_l2hdr->b_dev->l2ad_buflist, hdr);
1368 		}
1369 		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1370 		kmem_free(hdr->b_l2hdr, sizeof (l2arc_buf_hdr_t));
1371 		if (hdr->b_state == arc_l2c_only)
1372 			l2arc_hdr_stat_remove();
1373 		hdr->b_l2hdr = NULL;
1374 	}
1375 
1376 	if (!BUF_EMPTY(hdr)) {
1377 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
1378 		bzero(&hdr->b_dva, sizeof (dva_t));
1379 		hdr->b_birth = 0;
1380 		hdr->b_cksum0 = 0;
1381 	}
1382 	while (hdr->b_buf) {
1383 		arc_buf_t *buf = hdr->b_buf;
1384 
1385 		if (buf->b_efunc) {
1386 			mutex_enter(&arc_eviction_mtx);
1387 			rw_enter(&buf->b_lock, RW_WRITER);
1388 			ASSERT(buf->b_hdr != NULL);
1389 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1390 			hdr->b_buf = buf->b_next;
1391 			buf->b_hdr = &arc_eviction_hdr;
1392 			buf->b_next = arc_eviction_list;
1393 			arc_eviction_list = buf;
1394 			rw_exit(&buf->b_lock);
1395 			mutex_exit(&arc_eviction_mtx);
1396 		} else {
1397 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1398 		}
1399 	}
1400 	if (hdr->b_freeze_cksum != NULL) {
1401 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1402 		hdr->b_freeze_cksum = NULL;
1403 	}
1404 
1405 	ASSERT(!list_link_active(&hdr->b_arc_node));
1406 	ASSERT3P(hdr->b_hash_next, ==, NULL);
1407 	ASSERT3P(hdr->b_acb, ==, NULL);
1408 	kmem_cache_free(hdr_cache, hdr);
1409 }
1410 
1411 void
1412 arc_buf_free(arc_buf_t *buf, void *tag)
1413 {
1414 	arc_buf_hdr_t *hdr = buf->b_hdr;
1415 	int hashed = hdr->b_state != arc_anon;
1416 
1417 	ASSERT(buf->b_efunc == NULL);
1418 	ASSERT(buf->b_data != NULL);
1419 
1420 	if (hashed) {
1421 		kmutex_t *hash_lock = HDR_LOCK(hdr);
1422 
1423 		mutex_enter(hash_lock);
1424 		(void) remove_reference(hdr, hash_lock, tag);
1425 		if (hdr->b_datacnt > 1)
1426 			arc_buf_destroy(buf, FALSE, TRUE);
1427 		else
1428 			hdr->b_flags |= ARC_BUF_AVAILABLE;
1429 		mutex_exit(hash_lock);
1430 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
1431 		int destroy_hdr;
1432 		/*
1433 		 * We are in the middle of an async write.  Don't destroy
1434 		 * this buffer unless the write completes before we finish
1435 		 * decrementing the reference count.
1436 		 */
1437 		mutex_enter(&arc_eviction_mtx);
1438 		(void) remove_reference(hdr, NULL, tag);
1439 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
1440 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1441 		mutex_exit(&arc_eviction_mtx);
1442 		if (destroy_hdr)
1443 			arc_hdr_destroy(hdr);
1444 	} else {
1445 		if (remove_reference(hdr, NULL, tag) > 0) {
1446 			ASSERT(HDR_IO_ERROR(hdr));
1447 			arc_buf_destroy(buf, FALSE, TRUE);
1448 		} else {
1449 			arc_hdr_destroy(hdr);
1450 		}
1451 	}
1452 }
1453 
1454 int
1455 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1456 {
1457 	arc_buf_hdr_t *hdr = buf->b_hdr;
1458 	kmutex_t *hash_lock = HDR_LOCK(hdr);
1459 	int no_callback = (buf->b_efunc == NULL);
1460 
1461 	if (hdr->b_state == arc_anon) {
1462 		arc_buf_free(buf, tag);
1463 		return (no_callback);
1464 	}
1465 
1466 	mutex_enter(hash_lock);
1467 	ASSERT(hdr->b_state != arc_anon);
1468 	ASSERT(buf->b_data != NULL);
1469 
1470 	(void) remove_reference(hdr, hash_lock, tag);
1471 	if (hdr->b_datacnt > 1) {
1472 		if (no_callback)
1473 			arc_buf_destroy(buf, FALSE, TRUE);
1474 	} else if (no_callback) {
1475 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1476 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1477 	}
1478 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
1479 	    refcount_is_zero(&hdr->b_refcnt));
1480 	mutex_exit(hash_lock);
1481 	return (no_callback);
1482 }
1483 
1484 int
1485 arc_buf_size(arc_buf_t *buf)
1486 {
1487 	return (buf->b_hdr->b_size);
1488 }
1489 
1490 /*
1491  * Evict buffers from list until we've removed the specified number of
1492  * bytes.  Move the removed buffers to the appropriate evict state.
1493  * If the recycle flag is set, then attempt to "recycle" a buffer:
1494  * - look for a buffer to evict that is `bytes' long.
1495  * - return the data block from this buffer rather than freeing it.
1496  * This flag is used by callers that are trying to make space for a
1497  * new buffer in a full arc cache.
1498  *
1499  * This function makes a "best effort".  It skips over any buffers
1500  * it can't get a hash_lock on, and so may not catch all candidates.
1501  * It may also return without evicting as much space as requested.
1502  */
1503 static void *
1504 arc_evict(arc_state_t *state, spa_t *spa, int64_t bytes, boolean_t recycle,
1505     arc_buf_contents_t type)
1506 {
1507 	arc_state_t *evicted_state;
1508 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1509 	arc_buf_hdr_t *ab, *ab_prev = NULL;
1510 	list_t *list = &state->arcs_list[type];
1511 	kmutex_t *hash_lock;
1512 	boolean_t have_lock;
1513 	void *stolen = NULL;
1514 
1515 	ASSERT(state == arc_mru || state == arc_mfu);
1516 
1517 	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1518 
1519 	mutex_enter(&state->arcs_mtx);
1520 	mutex_enter(&evicted_state->arcs_mtx);
1521 
1522 	for (ab = list_tail(list); ab; ab = ab_prev) {
1523 		ab_prev = list_prev(list, ab);
1524 		/* prefetch buffers have a minimum lifespan */
1525 		if (HDR_IO_IN_PROGRESS(ab) ||
1526 		    (spa && ab->b_spa != spa) ||
1527 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1528 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
1529 			skipped++;
1530 			continue;
1531 		}
1532 		/* "lookahead" for better eviction candidate */
1533 		if (recycle && ab->b_size != bytes &&
1534 		    ab_prev && ab_prev->b_size == bytes)
1535 			continue;
1536 		hash_lock = HDR_LOCK(ab);
1537 		have_lock = MUTEX_HELD(hash_lock);
1538 		if (have_lock || mutex_tryenter(hash_lock)) {
1539 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
1540 			ASSERT(ab->b_datacnt > 0);
1541 			while (ab->b_buf) {
1542 				arc_buf_t *buf = ab->b_buf;
1543 				if (!rw_tryenter(&buf->b_lock, RW_WRITER)) {
1544 					missed += 1;
1545 					break;
1546 				}
1547 				if (buf->b_data) {
1548 					bytes_evicted += ab->b_size;
1549 					if (recycle && ab->b_type == type &&
1550 					    ab->b_size == bytes &&
1551 					    !HDR_L2_WRITING(ab)) {
1552 						stolen = buf->b_data;
1553 						recycle = FALSE;
1554 					}
1555 				}
1556 				if (buf->b_efunc) {
1557 					mutex_enter(&arc_eviction_mtx);
1558 					arc_buf_destroy(buf,
1559 					    buf->b_data == stolen, FALSE);
1560 					ab->b_buf = buf->b_next;
1561 					buf->b_hdr = &arc_eviction_hdr;
1562 					buf->b_next = arc_eviction_list;
1563 					arc_eviction_list = buf;
1564 					mutex_exit(&arc_eviction_mtx);
1565 					rw_exit(&buf->b_lock);
1566 				} else {
1567 					rw_exit(&buf->b_lock);
1568 					arc_buf_destroy(buf,
1569 					    buf->b_data == stolen, TRUE);
1570 				}
1571 			}
1572 			if (ab->b_datacnt == 0) {
1573 				arc_change_state(evicted_state, ab, hash_lock);
1574 				ASSERT(HDR_IN_HASH_TABLE(ab));
1575 				ab->b_flags |= ARC_IN_HASH_TABLE;
1576 				ab->b_flags &= ~ARC_BUF_AVAILABLE;
1577 				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
1578 			}
1579 			if (!have_lock)
1580 				mutex_exit(hash_lock);
1581 			if (bytes >= 0 && bytes_evicted >= bytes)
1582 				break;
1583 		} else {
1584 			missed += 1;
1585 		}
1586 	}
1587 
1588 	mutex_exit(&evicted_state->arcs_mtx);
1589 	mutex_exit(&state->arcs_mtx);
1590 
1591 	if (bytes_evicted < bytes)
1592 		dprintf("only evicted %lld bytes from %x",
1593 		    (longlong_t)bytes_evicted, state);
1594 
1595 	if (skipped)
1596 		ARCSTAT_INCR(arcstat_evict_skip, skipped);
1597 
1598 	if (missed)
1599 		ARCSTAT_INCR(arcstat_mutex_miss, missed);
1600 
1601 	/*
1602 	 * We have just evicted some date into the ghost state, make
1603 	 * sure we also adjust the ghost state size if necessary.
1604 	 */
1605 	if (arc_no_grow &&
1606 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size > arc_c) {
1607 		int64_t mru_over = arc_anon->arcs_size + arc_mru->arcs_size +
1608 		    arc_mru_ghost->arcs_size - arc_c;
1609 
1610 		if (mru_over > 0 && arc_mru_ghost->arcs_lsize[type] > 0) {
1611 			int64_t todelete =
1612 			    MIN(arc_mru_ghost->arcs_lsize[type], mru_over);
1613 			arc_evict_ghost(arc_mru_ghost, NULL, todelete);
1614 		} else if (arc_mfu_ghost->arcs_lsize[type] > 0) {
1615 			int64_t todelete = MIN(arc_mfu_ghost->arcs_lsize[type],
1616 			    arc_mru_ghost->arcs_size +
1617 			    arc_mfu_ghost->arcs_size - arc_c);
1618 			arc_evict_ghost(arc_mfu_ghost, NULL, todelete);
1619 		}
1620 	}
1621 
1622 	return (stolen);
1623 }
1624 
1625 /*
1626  * Remove buffers from list until we've removed the specified number of
1627  * bytes.  Destroy the buffers that are removed.
1628  */
1629 static void
1630 arc_evict_ghost(arc_state_t *state, spa_t *spa, int64_t bytes)
1631 {
1632 	arc_buf_hdr_t *ab, *ab_prev;
1633 	list_t *list = &state->arcs_list[ARC_BUFC_DATA];
1634 	kmutex_t *hash_lock;
1635 	uint64_t bytes_deleted = 0;
1636 	uint64_t bufs_skipped = 0;
1637 
1638 	ASSERT(GHOST_STATE(state));
1639 top:
1640 	mutex_enter(&state->arcs_mtx);
1641 	for (ab = list_tail(list); ab; ab = ab_prev) {
1642 		ab_prev = list_prev(list, ab);
1643 		if (spa && ab->b_spa != spa)
1644 			continue;
1645 		hash_lock = HDR_LOCK(ab);
1646 		if (mutex_tryenter(hash_lock)) {
1647 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
1648 			ASSERT(ab->b_buf == NULL);
1649 			ARCSTAT_BUMP(arcstat_deleted);
1650 			bytes_deleted += ab->b_size;
1651 
1652 			if (ab->b_l2hdr != NULL) {
1653 				/*
1654 				 * This buffer is cached on the 2nd Level ARC;
1655 				 * don't destroy the header.
1656 				 */
1657 				arc_change_state(arc_l2c_only, ab, hash_lock);
1658 				mutex_exit(hash_lock);
1659 			} else {
1660 				arc_change_state(arc_anon, ab, hash_lock);
1661 				mutex_exit(hash_lock);
1662 				arc_hdr_destroy(ab);
1663 			}
1664 
1665 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1666 			if (bytes >= 0 && bytes_deleted >= bytes)
1667 				break;
1668 		} else {
1669 			if (bytes < 0) {
1670 				mutex_exit(&state->arcs_mtx);
1671 				mutex_enter(hash_lock);
1672 				mutex_exit(hash_lock);
1673 				goto top;
1674 			}
1675 			bufs_skipped += 1;
1676 		}
1677 	}
1678 	mutex_exit(&state->arcs_mtx);
1679 
1680 	if (list == &state->arcs_list[ARC_BUFC_DATA] &&
1681 	    (bytes < 0 || bytes_deleted < bytes)) {
1682 		list = &state->arcs_list[ARC_BUFC_METADATA];
1683 		goto top;
1684 	}
1685 
1686 	if (bufs_skipped) {
1687 		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
1688 		ASSERT(bytes >= 0);
1689 	}
1690 
1691 	if (bytes_deleted < bytes)
1692 		dprintf("only deleted %lld bytes from %p",
1693 		    (longlong_t)bytes_deleted, state);
1694 }
1695 
1696 static void
1697 arc_adjust(void)
1698 {
1699 	int64_t adjustment, delta;
1700 
1701 	/*
1702 	 * Adjust MRU size
1703 	 */
1704 
1705 	adjustment = MIN(arc_size - arc_c,
1706 	    arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used - arc_p);
1707 
1708 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
1709 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
1710 		(void) arc_evict(arc_mru, NULL, delta, FALSE, ARC_BUFC_DATA);
1711 		adjustment -= delta;
1712 	}
1713 
1714 	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
1715 		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
1716 		(void) arc_evict(arc_mru, NULL, delta, FALSE,
1717 		    ARC_BUFC_METADATA);
1718 	}
1719 
1720 	/*
1721 	 * Adjust MFU size
1722 	 */
1723 
1724 	adjustment = arc_size - arc_c;
1725 
1726 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
1727 		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
1728 		(void) arc_evict(arc_mfu, NULL, delta, FALSE, ARC_BUFC_DATA);
1729 		adjustment -= delta;
1730 	}
1731 
1732 	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
1733 		int64_t delta = MIN(adjustment,
1734 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
1735 		(void) arc_evict(arc_mfu, NULL, delta, FALSE,
1736 		    ARC_BUFC_METADATA);
1737 	}
1738 
1739 	/*
1740 	 * Adjust ghost lists
1741 	 */
1742 
1743 	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
1744 
1745 	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
1746 		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
1747 		arc_evict_ghost(arc_mru_ghost, NULL, delta);
1748 	}
1749 
1750 	adjustment =
1751 	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
1752 
1753 	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
1754 		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
1755 		arc_evict_ghost(arc_mfu_ghost, NULL, delta);
1756 	}
1757 }
1758 
1759 static void
1760 arc_do_user_evicts(void)
1761 {
1762 	mutex_enter(&arc_eviction_mtx);
1763 	while (arc_eviction_list != NULL) {
1764 		arc_buf_t *buf = arc_eviction_list;
1765 		arc_eviction_list = buf->b_next;
1766 		rw_enter(&buf->b_lock, RW_WRITER);
1767 		buf->b_hdr = NULL;
1768 		rw_exit(&buf->b_lock);
1769 		mutex_exit(&arc_eviction_mtx);
1770 
1771 		if (buf->b_efunc != NULL)
1772 			VERIFY(buf->b_efunc(buf) == 0);
1773 
1774 		buf->b_efunc = NULL;
1775 		buf->b_private = NULL;
1776 		kmem_cache_free(buf_cache, buf);
1777 		mutex_enter(&arc_eviction_mtx);
1778 	}
1779 	mutex_exit(&arc_eviction_mtx);
1780 }
1781 
1782 /*
1783  * Flush all *evictable* data from the cache for the given spa.
1784  * NOTE: this will not touch "active" (i.e. referenced) data.
1785  */
1786 void
1787 arc_flush(spa_t *spa)
1788 {
1789 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
1790 		(void) arc_evict(arc_mru, spa, -1, FALSE, ARC_BUFC_DATA);
1791 		if (spa)
1792 			break;
1793 	}
1794 	while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
1795 		(void) arc_evict(arc_mru, spa, -1, FALSE, ARC_BUFC_METADATA);
1796 		if (spa)
1797 			break;
1798 	}
1799 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
1800 		(void) arc_evict(arc_mfu, spa, -1, FALSE, ARC_BUFC_DATA);
1801 		if (spa)
1802 			break;
1803 	}
1804 	while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
1805 		(void) arc_evict(arc_mfu, spa, -1, FALSE, ARC_BUFC_METADATA);
1806 		if (spa)
1807 			break;
1808 	}
1809 
1810 	arc_evict_ghost(arc_mru_ghost, spa, -1);
1811 	arc_evict_ghost(arc_mfu_ghost, spa, -1);
1812 
1813 	mutex_enter(&arc_reclaim_thr_lock);
1814 	arc_do_user_evicts();
1815 	mutex_exit(&arc_reclaim_thr_lock);
1816 	ASSERT(spa || arc_eviction_list == NULL);
1817 }
1818 
1819 void
1820 arc_shrink(void)
1821 {
1822 	if (arc_c > arc_c_min) {
1823 		uint64_t to_free;
1824 
1825 #ifdef _KERNEL
1826 		to_free = MAX(arc_c >> arc_shrink_shift, ptob(needfree));
1827 #else
1828 		to_free = arc_c >> arc_shrink_shift;
1829 #endif
1830 		if (arc_c > arc_c_min + to_free)
1831 			atomic_add_64(&arc_c, -to_free);
1832 		else
1833 			arc_c = arc_c_min;
1834 
1835 		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
1836 		if (arc_c > arc_size)
1837 			arc_c = MAX(arc_size, arc_c_min);
1838 		if (arc_p > arc_c)
1839 			arc_p = (arc_c >> 1);
1840 		ASSERT(arc_c >= arc_c_min);
1841 		ASSERT((int64_t)arc_p >= 0);
1842 	}
1843 
1844 	if (arc_size > arc_c)
1845 		arc_adjust();
1846 }
1847 
1848 static int
1849 arc_reclaim_needed(void)
1850 {
1851 	uint64_t extra;
1852 
1853 #ifdef _KERNEL
1854 
1855 	if (needfree)
1856 		return (1);
1857 
1858 	/*
1859 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1860 	 */
1861 	extra = desfree;
1862 
1863 	/*
1864 	 * check that we're out of range of the pageout scanner.  It starts to
1865 	 * schedule paging if freemem is less than lotsfree and needfree.
1866 	 * lotsfree is the high-water mark for pageout, and needfree is the
1867 	 * number of needed free pages.  We add extra pages here to make sure
1868 	 * the scanner doesn't start up while we're freeing memory.
1869 	 */
1870 	if (freemem < lotsfree + needfree + extra)
1871 		return (1);
1872 
1873 	/*
1874 	 * check to make sure that swapfs has enough space so that anon
1875 	 * reservations can still succeed. anon_resvmem() checks that the
1876 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1877 	 * swap pages.  We also add a bit of extra here just to prevent
1878 	 * circumstances from getting really dire.
1879 	 */
1880 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1881 		return (1);
1882 
1883 #if defined(__i386)
1884 	/*
1885 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1886 	 * kernel heap space before we ever run out of available physical
1887 	 * memory.  Most checks of the size of the heap_area compare against
1888 	 * tune.t_minarmem, which is the minimum available real memory that we
1889 	 * can have in the system.  However, this is generally fixed at 25 pages
1890 	 * which is so low that it's useless.  In this comparison, we seek to
1891 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
1892 	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
1893 	 * free)
1894 	 */
1895 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1896 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1897 		return (1);
1898 #endif
1899 
1900 #else
1901 	if (spa_get_random(100) == 0)
1902 		return (1);
1903 #endif
1904 	return (0);
1905 }
1906 
1907 static void
1908 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1909 {
1910 	size_t			i;
1911 	kmem_cache_t		*prev_cache = NULL;
1912 	kmem_cache_t		*prev_data_cache = NULL;
1913 	extern kmem_cache_t	*zio_buf_cache[];
1914 	extern kmem_cache_t	*zio_data_buf_cache[];
1915 
1916 #ifdef _KERNEL
1917 	if (arc_meta_used >= arc_meta_limit) {
1918 		/*
1919 		 * We are exceeding our meta-data cache limit.
1920 		 * Purge some DNLC entries to release holds on meta-data.
1921 		 */
1922 		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
1923 	}
1924 #if defined(__i386)
1925 	/*
1926 	 * Reclaim unused memory from all kmem caches.
1927 	 */
1928 	kmem_reap();
1929 #endif
1930 #endif
1931 
1932 	/*
1933 	 * An aggressive reclamation will shrink the cache size as well as
1934 	 * reap free buffers from the arc kmem caches.
1935 	 */
1936 	if (strat == ARC_RECLAIM_AGGR)
1937 		arc_shrink();
1938 
1939 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1940 		if (zio_buf_cache[i] != prev_cache) {
1941 			prev_cache = zio_buf_cache[i];
1942 			kmem_cache_reap_now(zio_buf_cache[i]);
1943 		}
1944 		if (zio_data_buf_cache[i] != prev_data_cache) {
1945 			prev_data_cache = zio_data_buf_cache[i];
1946 			kmem_cache_reap_now(zio_data_buf_cache[i]);
1947 		}
1948 	}
1949 	kmem_cache_reap_now(buf_cache);
1950 	kmem_cache_reap_now(hdr_cache);
1951 }
1952 
1953 static void
1954 arc_reclaim_thread(void)
1955 {
1956 	clock_t			growtime = 0;
1957 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1958 	callb_cpr_t		cpr;
1959 
1960 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1961 
1962 	mutex_enter(&arc_reclaim_thr_lock);
1963 	while (arc_thread_exit == 0) {
1964 		if (arc_reclaim_needed()) {
1965 
1966 			if (arc_no_grow) {
1967 				if (last_reclaim == ARC_RECLAIM_CONS) {
1968 					last_reclaim = ARC_RECLAIM_AGGR;
1969 				} else {
1970 					last_reclaim = ARC_RECLAIM_CONS;
1971 				}
1972 			} else {
1973 				arc_no_grow = TRUE;
1974 				last_reclaim = ARC_RECLAIM_AGGR;
1975 				membar_producer();
1976 			}
1977 
1978 			/* reset the growth delay for every reclaim */
1979 			growtime = lbolt + (arc_grow_retry * hz);
1980 
1981 			arc_kmem_reap_now(last_reclaim);
1982 			arc_warm = B_TRUE;
1983 
1984 		} else if (arc_no_grow && lbolt >= growtime) {
1985 			arc_no_grow = FALSE;
1986 		}
1987 
1988 		if (2 * arc_c < arc_size +
1989 		    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size)
1990 			arc_adjust();
1991 
1992 		if (arc_eviction_list != NULL)
1993 			arc_do_user_evicts();
1994 
1995 		/* block until needed, or one second, whichever is shorter */
1996 		CALLB_CPR_SAFE_BEGIN(&cpr);
1997 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1998 		    &arc_reclaim_thr_lock, (lbolt + hz));
1999 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2000 	}
2001 
2002 	arc_thread_exit = 0;
2003 	cv_broadcast(&arc_reclaim_thr_cv);
2004 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
2005 	thread_exit();
2006 }
2007 
2008 /*
2009  * Adapt arc info given the number of bytes we are trying to add and
2010  * the state that we are comming from.  This function is only called
2011  * when we are adding new content to the cache.
2012  */
2013 static void
2014 arc_adapt(int bytes, arc_state_t *state)
2015 {
2016 	int mult;
2017 	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
2018 
2019 	if (state == arc_l2c_only)
2020 		return;
2021 
2022 	ASSERT(bytes > 0);
2023 	/*
2024 	 * Adapt the target size of the MRU list:
2025 	 *	- if we just hit in the MRU ghost list, then increase
2026 	 *	  the target size of the MRU list.
2027 	 *	- if we just hit in the MFU ghost list, then increase
2028 	 *	  the target size of the MFU list by decreasing the
2029 	 *	  target size of the MRU list.
2030 	 */
2031 	if (state == arc_mru_ghost) {
2032 		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2033 		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2034 
2035 		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2036 	} else if (state == arc_mfu_ghost) {
2037 		uint64_t delta;
2038 
2039 		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2040 		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2041 
2042 		delta = MIN(bytes * mult, arc_p);
2043 		arc_p = MAX(arc_p_min, arc_p - delta);
2044 	}
2045 	ASSERT((int64_t)arc_p >= 0);
2046 
2047 	if (arc_reclaim_needed()) {
2048 		cv_signal(&arc_reclaim_thr_cv);
2049 		return;
2050 	}
2051 
2052 	if (arc_no_grow)
2053 		return;
2054 
2055 	if (arc_c >= arc_c_max)
2056 		return;
2057 
2058 	/*
2059 	 * If we're within (2 * maxblocksize) bytes of the target
2060 	 * cache size, increment the target cache size
2061 	 */
2062 	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2063 		atomic_add_64(&arc_c, (int64_t)bytes);
2064 		if (arc_c > arc_c_max)
2065 			arc_c = arc_c_max;
2066 		else if (state == arc_anon)
2067 			atomic_add_64(&arc_p, (int64_t)bytes);
2068 		if (arc_p > arc_c)
2069 			arc_p = arc_c;
2070 	}
2071 	ASSERT((int64_t)arc_p >= 0);
2072 }
2073 
2074 /*
2075  * Check if the cache has reached its limits and eviction is required
2076  * prior to insert.
2077  */
2078 static int
2079 arc_evict_needed(arc_buf_contents_t type)
2080 {
2081 	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2082 		return (1);
2083 
2084 #ifdef _KERNEL
2085 	/*
2086 	 * If zio data pages are being allocated out of a separate heap segment,
2087 	 * then enforce that the size of available vmem for this area remains
2088 	 * above about 1/32nd free.
2089 	 */
2090 	if (type == ARC_BUFC_DATA && zio_arena != NULL &&
2091 	    vmem_size(zio_arena, VMEM_FREE) <
2092 	    (vmem_size(zio_arena, VMEM_ALLOC) >> 5))
2093 		return (1);
2094 #endif
2095 
2096 	if (arc_reclaim_needed())
2097 		return (1);
2098 
2099 	return (arc_size > arc_c);
2100 }
2101 
2102 /*
2103  * The buffer, supplied as the first argument, needs a data block.
2104  * So, if we are at cache max, determine which cache should be victimized.
2105  * We have the following cases:
2106  *
2107  * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2108  * In this situation if we're out of space, but the resident size of the MFU is
2109  * under the limit, victimize the MFU cache to satisfy this insertion request.
2110  *
2111  * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2112  * Here, we've used up all of the available space for the MRU, so we need to
2113  * evict from our own cache instead.  Evict from the set of resident MRU
2114  * entries.
2115  *
2116  * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2117  * c minus p represents the MFU space in the cache, since p is the size of the
2118  * cache that is dedicated to the MRU.  In this situation there's still space on
2119  * the MFU side, so the MRU side needs to be victimized.
2120  *
2121  * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2122  * MFU's resident set is consuming more space than it has been allotted.  In
2123  * this situation, we must victimize our own cache, the MFU, for this insertion.
2124  */
2125 static void
2126 arc_get_data_buf(arc_buf_t *buf)
2127 {
2128 	arc_state_t		*state = buf->b_hdr->b_state;
2129 	uint64_t		size = buf->b_hdr->b_size;
2130 	arc_buf_contents_t	type = buf->b_hdr->b_type;
2131 
2132 	arc_adapt(size, state);
2133 
2134 	/*
2135 	 * We have not yet reached cache maximum size,
2136 	 * just allocate a new buffer.
2137 	 */
2138 	if (!arc_evict_needed(type)) {
2139 		if (type == ARC_BUFC_METADATA) {
2140 			buf->b_data = zio_buf_alloc(size);
2141 			arc_space_consume(size, ARC_SPACE_DATA);
2142 		} else {
2143 			ASSERT(type == ARC_BUFC_DATA);
2144 			buf->b_data = zio_data_buf_alloc(size);
2145 			ARCSTAT_INCR(arcstat_data_size, size);
2146 			atomic_add_64(&arc_size, size);
2147 		}
2148 		goto out;
2149 	}
2150 
2151 	/*
2152 	 * If we are prefetching from the mfu ghost list, this buffer
2153 	 * will end up on the mru list; so steal space from there.
2154 	 */
2155 	if (state == arc_mfu_ghost)
2156 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2157 	else if (state == arc_mru_ghost)
2158 		state = arc_mru;
2159 
2160 	if (state == arc_mru || state == arc_anon) {
2161 		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2162 		state = (arc_mfu->arcs_lsize[type] >= size &&
2163 		    arc_p > mru_used) ? arc_mfu : arc_mru;
2164 	} else {
2165 		/* MFU cases */
2166 		uint64_t mfu_space = arc_c - arc_p;
2167 		state =  (arc_mru->arcs_lsize[type] >= size &&
2168 		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2169 	}
2170 	if ((buf->b_data = arc_evict(state, NULL, size, TRUE, type)) == NULL) {
2171 		if (type == ARC_BUFC_METADATA) {
2172 			buf->b_data = zio_buf_alloc(size);
2173 			arc_space_consume(size, ARC_SPACE_DATA);
2174 		} else {
2175 			ASSERT(type == ARC_BUFC_DATA);
2176 			buf->b_data = zio_data_buf_alloc(size);
2177 			ARCSTAT_INCR(arcstat_data_size, size);
2178 			atomic_add_64(&arc_size, size);
2179 		}
2180 		ARCSTAT_BUMP(arcstat_recycle_miss);
2181 	}
2182 	ASSERT(buf->b_data != NULL);
2183 out:
2184 	/*
2185 	 * Update the state size.  Note that ghost states have a
2186 	 * "ghost size" and so don't need to be updated.
2187 	 */
2188 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
2189 		arc_buf_hdr_t *hdr = buf->b_hdr;
2190 
2191 		atomic_add_64(&hdr->b_state->arcs_size, size);
2192 		if (list_link_active(&hdr->b_arc_node)) {
2193 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
2194 			atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2195 		}
2196 		/*
2197 		 * If we are growing the cache, and we are adding anonymous
2198 		 * data, and we have outgrown arc_p, update arc_p
2199 		 */
2200 		if (arc_size < arc_c && hdr->b_state == arc_anon &&
2201 		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2202 			arc_p = MIN(arc_c, arc_p + size);
2203 	}
2204 }
2205 
2206 /*
2207  * This routine is called whenever a buffer is accessed.
2208  * NOTE: the hash lock is dropped in this function.
2209  */
2210 static void
2211 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2212 {
2213 	ASSERT(MUTEX_HELD(hash_lock));
2214 
2215 	if (buf->b_state == arc_anon) {
2216 		/*
2217 		 * This buffer is not in the cache, and does not
2218 		 * appear in our "ghost" list.  Add the new buffer
2219 		 * to the MRU state.
2220 		 */
2221 
2222 		ASSERT(buf->b_arc_access == 0);
2223 		buf->b_arc_access = lbolt;
2224 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2225 		arc_change_state(arc_mru, buf, hash_lock);
2226 
2227 	} else if (buf->b_state == arc_mru) {
2228 		/*
2229 		 * If this buffer is here because of a prefetch, then either:
2230 		 * - clear the flag if this is a "referencing" read
2231 		 *   (any subsequent access will bump this into the MFU state).
2232 		 * or
2233 		 * - move the buffer to the head of the list if this is
2234 		 *   another prefetch (to make it less likely to be evicted).
2235 		 */
2236 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
2237 			if (refcount_count(&buf->b_refcnt) == 0) {
2238 				ASSERT(list_link_active(&buf->b_arc_node));
2239 			} else {
2240 				buf->b_flags &= ~ARC_PREFETCH;
2241 				ARCSTAT_BUMP(arcstat_mru_hits);
2242 			}
2243 			buf->b_arc_access = lbolt;
2244 			return;
2245 		}
2246 
2247 		/*
2248 		 * This buffer has been "accessed" only once so far,
2249 		 * but it is still in the cache. Move it to the MFU
2250 		 * state.
2251 		 */
2252 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
2253 			/*
2254 			 * More than 125ms have passed since we
2255 			 * instantiated this buffer.  Move it to the
2256 			 * most frequently used state.
2257 			 */
2258 			buf->b_arc_access = lbolt;
2259 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2260 			arc_change_state(arc_mfu, buf, hash_lock);
2261 		}
2262 		ARCSTAT_BUMP(arcstat_mru_hits);
2263 	} else if (buf->b_state == arc_mru_ghost) {
2264 		arc_state_t	*new_state;
2265 		/*
2266 		 * This buffer has been "accessed" recently, but
2267 		 * was evicted from the cache.  Move it to the
2268 		 * MFU state.
2269 		 */
2270 
2271 		if (buf->b_flags & ARC_PREFETCH) {
2272 			new_state = arc_mru;
2273 			if (refcount_count(&buf->b_refcnt) > 0)
2274 				buf->b_flags &= ~ARC_PREFETCH;
2275 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2276 		} else {
2277 			new_state = arc_mfu;
2278 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2279 		}
2280 
2281 		buf->b_arc_access = lbolt;
2282 		arc_change_state(new_state, buf, hash_lock);
2283 
2284 		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2285 	} else if (buf->b_state == arc_mfu) {
2286 		/*
2287 		 * This buffer has been accessed more than once and is
2288 		 * still in the cache.  Keep it in the MFU state.
2289 		 *
2290 		 * NOTE: an add_reference() that occurred when we did
2291 		 * the arc_read() will have kicked this off the list.
2292 		 * If it was a prefetch, we will explicitly move it to
2293 		 * the head of the list now.
2294 		 */
2295 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
2296 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
2297 			ASSERT(list_link_active(&buf->b_arc_node));
2298 		}
2299 		ARCSTAT_BUMP(arcstat_mfu_hits);
2300 		buf->b_arc_access = lbolt;
2301 	} else if (buf->b_state == arc_mfu_ghost) {
2302 		arc_state_t	*new_state = arc_mfu;
2303 		/*
2304 		 * This buffer has been accessed more than once but has
2305 		 * been evicted from the cache.  Move it back to the
2306 		 * MFU state.
2307 		 */
2308 
2309 		if (buf->b_flags & ARC_PREFETCH) {
2310 			/*
2311 			 * This is a prefetch access...
2312 			 * move this block back to the MRU state.
2313 			 */
2314 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
2315 			new_state = arc_mru;
2316 		}
2317 
2318 		buf->b_arc_access = lbolt;
2319 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2320 		arc_change_state(new_state, buf, hash_lock);
2321 
2322 		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2323 	} else if (buf->b_state == arc_l2c_only) {
2324 		/*
2325 		 * This buffer is on the 2nd Level ARC.
2326 		 */
2327 
2328 		buf->b_arc_access = lbolt;
2329 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2330 		arc_change_state(arc_mfu, buf, hash_lock);
2331 	} else {
2332 		ASSERT(!"invalid arc state");
2333 	}
2334 }
2335 
2336 /* a generic arc_done_func_t which you can use */
2337 /* ARGSUSED */
2338 void
2339 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2340 {
2341 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2342 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2343 }
2344 
2345 /* a generic arc_done_func_t */
2346 void
2347 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2348 {
2349 	arc_buf_t **bufp = arg;
2350 	if (zio && zio->io_error) {
2351 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
2352 		*bufp = NULL;
2353 	} else {
2354 		*bufp = buf;
2355 	}
2356 }
2357 
2358 static void
2359 arc_read_done(zio_t *zio)
2360 {
2361 	arc_buf_hdr_t	*hdr, *found;
2362 	arc_buf_t	*buf;
2363 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
2364 	kmutex_t	*hash_lock;
2365 	arc_callback_t	*callback_list, *acb;
2366 	int		freeable = FALSE;
2367 
2368 	buf = zio->io_private;
2369 	hdr = buf->b_hdr;
2370 
2371 	/*
2372 	 * The hdr was inserted into hash-table and removed from lists
2373 	 * prior to starting I/O.  We should find this header, since
2374 	 * it's in the hash table, and it should be legit since it's
2375 	 * not possible to evict it during the I/O.  The only possible
2376 	 * reason for it not to be found is if we were freed during the
2377 	 * read.
2378 	 */
2379 	found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
2380 	    &hash_lock);
2381 
2382 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
2383 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2384 	    (found == hdr && HDR_L2_READING(hdr)));
2385 
2386 	hdr->b_flags &= ~ARC_L2_EVICTED;
2387 	if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2388 		hdr->b_flags &= ~ARC_L2CACHE;
2389 
2390 	/* byteswap if necessary */
2391 	callback_list = hdr->b_acb;
2392 	ASSERT(callback_list != NULL);
2393 	if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
2394 		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
2395 		    byteswap_uint64_array :
2396 		    dmu_ot[BP_GET_TYPE(zio->io_bp)].ot_byteswap;
2397 		func(buf->b_data, hdr->b_size);
2398 	}
2399 
2400 	arc_cksum_compute(buf, B_FALSE);
2401 
2402 	/* create copies of the data buffer for the callers */
2403 	abuf = buf;
2404 	for (acb = callback_list; acb; acb = acb->acb_next) {
2405 		if (acb->acb_done) {
2406 			if (abuf == NULL)
2407 				abuf = arc_buf_clone(buf);
2408 			acb->acb_buf = abuf;
2409 			abuf = NULL;
2410 		}
2411 	}
2412 	hdr->b_acb = NULL;
2413 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2414 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
2415 	if (abuf == buf)
2416 		hdr->b_flags |= ARC_BUF_AVAILABLE;
2417 
2418 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
2419 
2420 	if (zio->io_error != 0) {
2421 		hdr->b_flags |= ARC_IO_ERROR;
2422 		if (hdr->b_state != arc_anon)
2423 			arc_change_state(arc_anon, hdr, hash_lock);
2424 		if (HDR_IN_HASH_TABLE(hdr))
2425 			buf_hash_remove(hdr);
2426 		freeable = refcount_is_zero(&hdr->b_refcnt);
2427 	}
2428 
2429 	/*
2430 	 * Broadcast before we drop the hash_lock to avoid the possibility
2431 	 * that the hdr (and hence the cv) might be freed before we get to
2432 	 * the cv_broadcast().
2433 	 */
2434 	cv_broadcast(&hdr->b_cv);
2435 
2436 	if (hash_lock) {
2437 		/*
2438 		 * Only call arc_access on anonymous buffers.  This is because
2439 		 * if we've issued an I/O for an evicted buffer, we've already
2440 		 * called arc_access (to prevent any simultaneous readers from
2441 		 * getting confused).
2442 		 */
2443 		if (zio->io_error == 0 && hdr->b_state == arc_anon)
2444 			arc_access(hdr, hash_lock);
2445 		mutex_exit(hash_lock);
2446 	} else {
2447 		/*
2448 		 * This block was freed while we waited for the read to
2449 		 * complete.  It has been removed from the hash table and
2450 		 * moved to the anonymous state (so that it won't show up
2451 		 * in the cache).
2452 		 */
2453 		ASSERT3P(hdr->b_state, ==, arc_anon);
2454 		freeable = refcount_is_zero(&hdr->b_refcnt);
2455 	}
2456 
2457 	/* execute each callback and free its structure */
2458 	while ((acb = callback_list) != NULL) {
2459 		if (acb->acb_done)
2460 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
2461 
2462 		if (acb->acb_zio_dummy != NULL) {
2463 			acb->acb_zio_dummy->io_error = zio->io_error;
2464 			zio_nowait(acb->acb_zio_dummy);
2465 		}
2466 
2467 		callback_list = acb->acb_next;
2468 		kmem_free(acb, sizeof (arc_callback_t));
2469 	}
2470 
2471 	if (freeable)
2472 		arc_hdr_destroy(hdr);
2473 }
2474 
2475 /*
2476  * "Read" the block block at the specified DVA (in bp) via the
2477  * cache.  If the block is found in the cache, invoke the provided
2478  * callback immediately and return.  Note that the `zio' parameter
2479  * in the callback will be NULL in this case, since no IO was
2480  * required.  If the block is not in the cache pass the read request
2481  * on to the spa with a substitute callback function, so that the
2482  * requested block will be added to the cache.
2483  *
2484  * If a read request arrives for a block that has a read in-progress,
2485  * either wait for the in-progress read to complete (and return the
2486  * results); or, if this is a read with a "done" func, add a record
2487  * to the read to invoke the "done" func when the read completes,
2488  * and return; or just return.
2489  *
2490  * arc_read_done() will invoke all the requested "done" functions
2491  * for readers of this block.
2492  *
2493  * Normal callers should use arc_read and pass the arc buffer and offset
2494  * for the bp.  But if you know you don't need locking, you can use
2495  * arc_read_bp.
2496  */
2497 int
2498 arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_buf_t *pbuf,
2499     arc_done_func_t *done, void *private, int priority, int zio_flags,
2500     uint32_t *arc_flags, const zbookmark_t *zb)
2501 {
2502 	int err;
2503 	arc_buf_hdr_t *hdr = pbuf->b_hdr;
2504 
2505 	ASSERT(!refcount_is_zero(&pbuf->b_hdr->b_refcnt));
2506 	ASSERT3U((char *)bp - (char *)pbuf->b_data, <, pbuf->b_hdr->b_size);
2507 	rw_enter(&pbuf->b_lock, RW_READER);
2508 
2509 	err = arc_read_nolock(pio, spa, bp, done, private, priority,
2510 	    zio_flags, arc_flags, zb);
2511 
2512 	ASSERT3P(hdr, ==, pbuf->b_hdr);
2513 	rw_exit(&pbuf->b_lock);
2514 	return (err);
2515 }
2516 
2517 int
2518 arc_read_nolock(zio_t *pio, spa_t *spa, blkptr_t *bp,
2519     arc_done_func_t *done, void *private, int priority, int zio_flags,
2520     uint32_t *arc_flags, const zbookmark_t *zb)
2521 {
2522 	arc_buf_hdr_t *hdr;
2523 	arc_buf_t *buf;
2524 	kmutex_t *hash_lock;
2525 	zio_t *rzio;
2526 
2527 top:
2528 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
2529 	if (hdr && hdr->b_datacnt > 0) {
2530 
2531 		*arc_flags |= ARC_CACHED;
2532 
2533 		if (HDR_IO_IN_PROGRESS(hdr)) {
2534 
2535 			if (*arc_flags & ARC_WAIT) {
2536 				cv_wait(&hdr->b_cv, hash_lock);
2537 				mutex_exit(hash_lock);
2538 				goto top;
2539 			}
2540 			ASSERT(*arc_flags & ARC_NOWAIT);
2541 
2542 			if (done) {
2543 				arc_callback_t	*acb = NULL;
2544 
2545 				acb = kmem_zalloc(sizeof (arc_callback_t),
2546 				    KM_SLEEP);
2547 				acb->acb_done = done;
2548 				acb->acb_private = private;
2549 				if (pio != NULL)
2550 					acb->acb_zio_dummy = zio_null(pio,
2551 					    spa, NULL, NULL, NULL, zio_flags);
2552 
2553 				ASSERT(acb->acb_done != NULL);
2554 				acb->acb_next = hdr->b_acb;
2555 				hdr->b_acb = acb;
2556 				add_reference(hdr, hash_lock, private);
2557 				mutex_exit(hash_lock);
2558 				return (0);
2559 			}
2560 			mutex_exit(hash_lock);
2561 			return (0);
2562 		}
2563 
2564 		ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2565 
2566 		if (done) {
2567 			add_reference(hdr, hash_lock, private);
2568 			/*
2569 			 * If this block is already in use, create a new
2570 			 * copy of the data so that we will be guaranteed
2571 			 * that arc_release() will always succeed.
2572 			 */
2573 			buf = hdr->b_buf;
2574 			ASSERT(buf);
2575 			ASSERT(buf->b_data);
2576 			if (HDR_BUF_AVAILABLE(hdr)) {
2577 				ASSERT(buf->b_efunc == NULL);
2578 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
2579 			} else {
2580 				buf = arc_buf_clone(buf);
2581 			}
2582 		} else if (*arc_flags & ARC_PREFETCH &&
2583 		    refcount_count(&hdr->b_refcnt) == 0) {
2584 			hdr->b_flags |= ARC_PREFETCH;
2585 		}
2586 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2587 		arc_access(hdr, hash_lock);
2588 		if (*arc_flags & ARC_L2CACHE)
2589 			hdr->b_flags |= ARC_L2CACHE;
2590 		mutex_exit(hash_lock);
2591 		ARCSTAT_BUMP(arcstat_hits);
2592 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
2593 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
2594 		    data, metadata, hits);
2595 
2596 		if (done)
2597 			done(NULL, buf, private);
2598 	} else {
2599 		uint64_t size = BP_GET_LSIZE(bp);
2600 		arc_callback_t	*acb;
2601 		vdev_t *vd = NULL;
2602 		daddr_t addr;
2603 		boolean_t devw = B_FALSE;
2604 
2605 		if (hdr == NULL) {
2606 			/* this block is not in the cache */
2607 			arc_buf_hdr_t	*exists;
2608 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
2609 			buf = arc_buf_alloc(spa, size, private, type);
2610 			hdr = buf->b_hdr;
2611 			hdr->b_dva = *BP_IDENTITY(bp);
2612 			hdr->b_birth = bp->blk_birth;
2613 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
2614 			exists = buf_hash_insert(hdr, &hash_lock);
2615 			if (exists) {
2616 				/* somebody beat us to the hash insert */
2617 				mutex_exit(hash_lock);
2618 				bzero(&hdr->b_dva, sizeof (dva_t));
2619 				hdr->b_birth = 0;
2620 				hdr->b_cksum0 = 0;
2621 				(void) arc_buf_remove_ref(buf, private);
2622 				goto top; /* restart the IO request */
2623 			}
2624 			/* if this is a prefetch, we don't have a reference */
2625 			if (*arc_flags & ARC_PREFETCH) {
2626 				(void) remove_reference(hdr, hash_lock,
2627 				    private);
2628 				hdr->b_flags |= ARC_PREFETCH;
2629 			}
2630 			if (*arc_flags & ARC_L2CACHE)
2631 				hdr->b_flags |= ARC_L2CACHE;
2632 			if (BP_GET_LEVEL(bp) > 0)
2633 				hdr->b_flags |= ARC_INDIRECT;
2634 		} else {
2635 			/* this block is in the ghost cache */
2636 			ASSERT(GHOST_STATE(hdr->b_state));
2637 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2638 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
2639 			ASSERT(hdr->b_buf == NULL);
2640 
2641 			/* if this is a prefetch, we don't have a reference */
2642 			if (*arc_flags & ARC_PREFETCH)
2643 				hdr->b_flags |= ARC_PREFETCH;
2644 			else
2645 				add_reference(hdr, hash_lock, private);
2646 			if (*arc_flags & ARC_L2CACHE)
2647 				hdr->b_flags |= ARC_L2CACHE;
2648 			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2649 			buf->b_hdr = hdr;
2650 			buf->b_data = NULL;
2651 			buf->b_efunc = NULL;
2652 			buf->b_private = NULL;
2653 			buf->b_next = NULL;
2654 			hdr->b_buf = buf;
2655 			arc_get_data_buf(buf);
2656 			ASSERT(hdr->b_datacnt == 0);
2657 			hdr->b_datacnt = 1;
2658 
2659 		}
2660 
2661 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2662 		acb->acb_done = done;
2663 		acb->acb_private = private;
2664 
2665 		ASSERT(hdr->b_acb == NULL);
2666 		hdr->b_acb = acb;
2667 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2668 
2669 		/*
2670 		 * If the buffer has been evicted, migrate it to a present state
2671 		 * before issuing the I/O.  Once we drop the hash-table lock,
2672 		 * the header will be marked as I/O in progress and have an
2673 		 * attached buffer.  At this point, anybody who finds this
2674 		 * buffer ought to notice that it's legit but has a pending I/O.
2675 		 */
2676 
2677 		if (GHOST_STATE(hdr->b_state))
2678 			arc_access(hdr, hash_lock);
2679 
2680 		if (HDR_L2CACHE(hdr) && hdr->b_l2hdr != NULL &&
2681 		    (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
2682 			devw = hdr->b_l2hdr->b_dev->l2ad_writing;
2683 			addr = hdr->b_l2hdr->b_daddr;
2684 			/*
2685 			 * Lock out device removal.
2686 			 */
2687 			if (vdev_is_dead(vd) ||
2688 			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
2689 				vd = NULL;
2690 		}
2691 
2692 		mutex_exit(hash_lock);
2693 
2694 		ASSERT3U(hdr->b_size, ==, size);
2695 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
2696 		    zbookmark_t *, zb);
2697 		ARCSTAT_BUMP(arcstat_misses);
2698 		ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
2699 		    demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
2700 		    data, metadata, misses);
2701 
2702 		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
2703 			/*
2704 			 * Read from the L2ARC if the following are true:
2705 			 * 1. The L2ARC vdev was previously cached.
2706 			 * 2. This buffer still has L2ARC metadata.
2707 			 * 3. This buffer isn't currently writing to the L2ARC.
2708 			 * 4. The L2ARC entry wasn't evicted, which may
2709 			 *    also have invalidated the vdev.
2710 			 * 5. This isn't prefetch and l2arc_noprefetch is set.
2711 			 */
2712 			if (hdr->b_l2hdr != NULL &&
2713 			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
2714 			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
2715 				l2arc_read_callback_t *cb;
2716 
2717 				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
2718 				ARCSTAT_BUMP(arcstat_l2_hits);
2719 
2720 				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
2721 				    KM_SLEEP);
2722 				cb->l2rcb_buf = buf;
2723 				cb->l2rcb_spa = spa;
2724 				cb->l2rcb_bp = *bp;
2725 				cb->l2rcb_zb = *zb;
2726 				cb->l2rcb_flags = zio_flags;
2727 
2728 				/*
2729 				 * l2arc read.  The SCL_L2ARC lock will be
2730 				 * released by l2arc_read_done().
2731 				 */
2732 				rzio = zio_read_phys(pio, vd, addr, size,
2733 				    buf->b_data, ZIO_CHECKSUM_OFF,
2734 				    l2arc_read_done, cb, priority, zio_flags |
2735 				    ZIO_FLAG_DONT_CACHE | ZIO_FLAG_CANFAIL |
2736 				    ZIO_FLAG_DONT_PROPAGATE |
2737 				    ZIO_FLAG_DONT_RETRY, B_FALSE);
2738 				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
2739 				    zio_t *, rzio);
2740 				ARCSTAT_INCR(arcstat_l2_read_bytes, size);
2741 
2742 				if (*arc_flags & ARC_NOWAIT) {
2743 					zio_nowait(rzio);
2744 					return (0);
2745 				}
2746 
2747 				ASSERT(*arc_flags & ARC_WAIT);
2748 				if (zio_wait(rzio) == 0)
2749 					return (0);
2750 
2751 				/* l2arc read error; goto zio_read() */
2752 			} else {
2753 				DTRACE_PROBE1(l2arc__miss,
2754 				    arc_buf_hdr_t *, hdr);
2755 				ARCSTAT_BUMP(arcstat_l2_misses);
2756 				if (HDR_L2_WRITING(hdr))
2757 					ARCSTAT_BUMP(arcstat_l2_rw_clash);
2758 				spa_config_exit(spa, SCL_L2ARC, vd);
2759 			}
2760 		} else {
2761 			if (vd != NULL)
2762 				spa_config_exit(spa, SCL_L2ARC, vd);
2763 			if (l2arc_ndev != 0) {
2764 				DTRACE_PROBE1(l2arc__miss,
2765 				    arc_buf_hdr_t *, hdr);
2766 				ARCSTAT_BUMP(arcstat_l2_misses);
2767 			}
2768 		}
2769 
2770 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
2771 		    arc_read_done, buf, priority, zio_flags, zb);
2772 
2773 		if (*arc_flags & ARC_WAIT)
2774 			return (zio_wait(rzio));
2775 
2776 		ASSERT(*arc_flags & ARC_NOWAIT);
2777 		zio_nowait(rzio);
2778 	}
2779 	return (0);
2780 }
2781 
2782 /*
2783  * arc_read() variant to support pool traversal.  If the block is already
2784  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2785  * The idea is that we don't want pool traversal filling up memory, but
2786  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2787  */
2788 int
2789 arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2790 {
2791 	arc_buf_hdr_t *hdr;
2792 	kmutex_t *hash_mtx;
2793 	int rc = 0;
2794 
2795 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2796 
2797 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
2798 		arc_buf_t *buf = hdr->b_buf;
2799 
2800 		ASSERT(buf);
2801 		while (buf->b_data == NULL) {
2802 			buf = buf->b_next;
2803 			ASSERT(buf);
2804 		}
2805 		bcopy(buf->b_data, data, hdr->b_size);
2806 	} else {
2807 		rc = ENOENT;
2808 	}
2809 
2810 	if (hash_mtx)
2811 		mutex_exit(hash_mtx);
2812 
2813 	return (rc);
2814 }
2815 
2816 void
2817 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
2818 {
2819 	ASSERT(buf->b_hdr != NULL);
2820 	ASSERT(buf->b_hdr->b_state != arc_anon);
2821 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
2822 	buf->b_efunc = func;
2823 	buf->b_private = private;
2824 }
2825 
2826 /*
2827  * This is used by the DMU to let the ARC know that a buffer is
2828  * being evicted, so the ARC should clean up.  If this arc buf
2829  * is not yet in the evicted state, it will be put there.
2830  */
2831 int
2832 arc_buf_evict(arc_buf_t *buf)
2833 {
2834 	arc_buf_hdr_t *hdr;
2835 	kmutex_t *hash_lock;
2836 	arc_buf_t **bufp;
2837 
2838 	rw_enter(&buf->b_lock, RW_WRITER);
2839 	hdr = buf->b_hdr;
2840 	if (hdr == NULL) {
2841 		/*
2842 		 * We are in arc_do_user_evicts().
2843 		 */
2844 		ASSERT(buf->b_data == NULL);
2845 		rw_exit(&buf->b_lock);
2846 		return (0);
2847 	} else if (buf->b_data == NULL) {
2848 		arc_buf_t copy = *buf; /* structure assignment */
2849 		/*
2850 		 * We are on the eviction list; process this buffer now
2851 		 * but let arc_do_user_evicts() do the reaping.
2852 		 */
2853 		buf->b_efunc = NULL;
2854 		rw_exit(&buf->b_lock);
2855 		VERIFY(copy.b_efunc(&copy) == 0);
2856 		return (1);
2857 	}
2858 	hash_lock = HDR_LOCK(hdr);
2859 	mutex_enter(hash_lock);
2860 
2861 	ASSERT(buf->b_hdr == hdr);
2862 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
2863 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
2864 
2865 	/*
2866 	 * Pull this buffer off of the hdr
2867 	 */
2868 	bufp = &hdr->b_buf;
2869 	while (*bufp != buf)
2870 		bufp = &(*bufp)->b_next;
2871 	*bufp = buf->b_next;
2872 
2873 	ASSERT(buf->b_data != NULL);
2874 	arc_buf_destroy(buf, FALSE, FALSE);
2875 
2876 	if (hdr->b_datacnt == 0) {
2877 		arc_state_t *old_state = hdr->b_state;
2878 		arc_state_t *evicted_state;
2879 
2880 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
2881 
2882 		evicted_state =
2883 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2884 
2885 		mutex_enter(&old_state->arcs_mtx);
2886 		mutex_enter(&evicted_state->arcs_mtx);
2887 
2888 		arc_change_state(evicted_state, hdr, hash_lock);
2889 		ASSERT(HDR_IN_HASH_TABLE(hdr));
2890 		hdr->b_flags |= ARC_IN_HASH_TABLE;
2891 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
2892 
2893 		mutex_exit(&evicted_state->arcs_mtx);
2894 		mutex_exit(&old_state->arcs_mtx);
2895 	}
2896 	mutex_exit(hash_lock);
2897 	rw_exit(&buf->b_lock);
2898 
2899 	VERIFY(buf->b_efunc(buf) == 0);
2900 	buf->b_efunc = NULL;
2901 	buf->b_private = NULL;
2902 	buf->b_hdr = NULL;
2903 	kmem_cache_free(buf_cache, buf);
2904 	return (1);
2905 }
2906 
2907 /*
2908  * Release this buffer from the cache.  This must be done
2909  * after a read and prior to modifying the buffer contents.
2910  * If the buffer has more than one reference, we must make
2911  * a new hdr for the buffer.
2912  */
2913 void
2914 arc_release(arc_buf_t *buf, void *tag)
2915 {
2916 	arc_buf_hdr_t *hdr;
2917 	kmutex_t *hash_lock;
2918 	l2arc_buf_hdr_t *l2hdr;
2919 	uint64_t buf_size;
2920 
2921 	rw_enter(&buf->b_lock, RW_WRITER);
2922 	hdr = buf->b_hdr;
2923 
2924 	/* this buffer is not on any list */
2925 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
2926 	ASSERT(!(hdr->b_flags & ARC_STORED));
2927 
2928 	if (hdr->b_state == arc_anon) {
2929 		/* this buffer is already released */
2930 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2931 		ASSERT(BUF_EMPTY(hdr));
2932 		ASSERT(buf->b_efunc == NULL);
2933 		arc_buf_thaw(buf);
2934 		rw_exit(&buf->b_lock);
2935 		return;
2936 	}
2937 
2938 	hash_lock = HDR_LOCK(hdr);
2939 	mutex_enter(hash_lock);
2940 
2941 	l2hdr = hdr->b_l2hdr;
2942 	if (l2hdr) {
2943 		mutex_enter(&l2arc_buflist_mtx);
2944 		hdr->b_l2hdr = NULL;
2945 		buf_size = hdr->b_size;
2946 	}
2947 
2948 	/*
2949 	 * Do we have more than one buf?
2950 	 */
2951 	if (hdr->b_datacnt > 1) {
2952 		arc_buf_hdr_t *nhdr;
2953 		arc_buf_t **bufp;
2954 		uint64_t blksz = hdr->b_size;
2955 		spa_t *spa = hdr->b_spa;
2956 		arc_buf_contents_t type = hdr->b_type;
2957 		uint32_t flags = hdr->b_flags;
2958 
2959 		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
2960 		/*
2961 		 * Pull the data off of this buf and attach it to
2962 		 * a new anonymous buf.
2963 		 */
2964 		(void) remove_reference(hdr, hash_lock, tag);
2965 		bufp = &hdr->b_buf;
2966 		while (*bufp != buf)
2967 			bufp = &(*bufp)->b_next;
2968 		*bufp = (*bufp)->b_next;
2969 		buf->b_next = NULL;
2970 
2971 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
2972 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
2973 		if (refcount_is_zero(&hdr->b_refcnt)) {
2974 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
2975 			ASSERT3U(*size, >=, hdr->b_size);
2976 			atomic_add_64(size, -hdr->b_size);
2977 		}
2978 		hdr->b_datacnt -= 1;
2979 		arc_cksum_verify(buf);
2980 
2981 		mutex_exit(hash_lock);
2982 
2983 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
2984 		nhdr->b_size = blksz;
2985 		nhdr->b_spa = spa;
2986 		nhdr->b_type = type;
2987 		nhdr->b_buf = buf;
2988 		nhdr->b_state = arc_anon;
2989 		nhdr->b_arc_access = 0;
2990 		nhdr->b_flags = flags & ARC_L2_WRITING;
2991 		nhdr->b_l2hdr = NULL;
2992 		nhdr->b_datacnt = 1;
2993 		nhdr->b_freeze_cksum = NULL;
2994 		(void) refcount_add(&nhdr->b_refcnt, tag);
2995 		buf->b_hdr = nhdr;
2996 		rw_exit(&buf->b_lock);
2997 		atomic_add_64(&arc_anon->arcs_size, blksz);
2998 	} else {
2999 		rw_exit(&buf->b_lock);
3000 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3001 		ASSERT(!list_link_active(&hdr->b_arc_node));
3002 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3003 		arc_change_state(arc_anon, hdr, hash_lock);
3004 		hdr->b_arc_access = 0;
3005 		mutex_exit(hash_lock);
3006 
3007 		bzero(&hdr->b_dva, sizeof (dva_t));
3008 		hdr->b_birth = 0;
3009 		hdr->b_cksum0 = 0;
3010 		arc_buf_thaw(buf);
3011 	}
3012 	buf->b_efunc = NULL;
3013 	buf->b_private = NULL;
3014 
3015 	if (l2hdr) {
3016 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3017 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3018 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3019 		mutex_exit(&l2arc_buflist_mtx);
3020 	}
3021 }
3022 
3023 int
3024 arc_released(arc_buf_t *buf)
3025 {
3026 	int released;
3027 
3028 	rw_enter(&buf->b_lock, RW_READER);
3029 	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3030 	rw_exit(&buf->b_lock);
3031 	return (released);
3032 }
3033 
3034 int
3035 arc_has_callback(arc_buf_t *buf)
3036 {
3037 	int callback;
3038 
3039 	rw_enter(&buf->b_lock, RW_READER);
3040 	callback = (buf->b_efunc != NULL);
3041 	rw_exit(&buf->b_lock);
3042 	return (callback);
3043 }
3044 
3045 #ifdef ZFS_DEBUG
3046 int
3047 arc_referenced(arc_buf_t *buf)
3048 {
3049 	int referenced;
3050 
3051 	rw_enter(&buf->b_lock, RW_READER);
3052 	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3053 	rw_exit(&buf->b_lock);
3054 	return (referenced);
3055 }
3056 #endif
3057 
3058 static void
3059 arc_write_ready(zio_t *zio)
3060 {
3061 	arc_write_callback_t *callback = zio->io_private;
3062 	arc_buf_t *buf = callback->awcb_buf;
3063 	arc_buf_hdr_t *hdr = buf->b_hdr;
3064 
3065 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3066 	callback->awcb_ready(zio, buf, callback->awcb_private);
3067 
3068 	/*
3069 	 * If the IO is already in progress, then this is a re-write
3070 	 * attempt, so we need to thaw and re-compute the cksum.
3071 	 * It is the responsibility of the callback to handle the
3072 	 * accounting for any re-write attempt.
3073 	 */
3074 	if (HDR_IO_IN_PROGRESS(hdr)) {
3075 		mutex_enter(&hdr->b_freeze_lock);
3076 		if (hdr->b_freeze_cksum != NULL) {
3077 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3078 			hdr->b_freeze_cksum = NULL;
3079 		}
3080 		mutex_exit(&hdr->b_freeze_lock);
3081 	}
3082 	arc_cksum_compute(buf, B_FALSE);
3083 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
3084 }
3085 
3086 static void
3087 arc_write_done(zio_t *zio)
3088 {
3089 	arc_write_callback_t *callback = zio->io_private;
3090 	arc_buf_t *buf = callback->awcb_buf;
3091 	arc_buf_hdr_t *hdr = buf->b_hdr;
3092 
3093 	hdr->b_acb = NULL;
3094 
3095 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3096 	hdr->b_birth = zio->io_bp->blk_birth;
3097 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3098 	/*
3099 	 * If the block to be written was all-zero, we may have
3100 	 * compressed it away.  In this case no write was performed
3101 	 * so there will be no dva/birth-date/checksum.  The buffer
3102 	 * must therefor remain anonymous (and uncached).
3103 	 */
3104 	if (!BUF_EMPTY(hdr)) {
3105 		arc_buf_hdr_t *exists;
3106 		kmutex_t *hash_lock;
3107 
3108 		arc_cksum_verify(buf);
3109 
3110 		exists = buf_hash_insert(hdr, &hash_lock);
3111 		if (exists) {
3112 			/*
3113 			 * This can only happen if we overwrite for
3114 			 * sync-to-convergence, because we remove
3115 			 * buffers from the hash table when we arc_free().
3116 			 */
3117 			ASSERT(zio->io_flags & ZIO_FLAG_IO_REWRITE);
3118 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
3119 			    BP_IDENTITY(zio->io_bp)));
3120 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
3121 			    zio->io_bp->blk_birth);
3122 
3123 			ASSERT(refcount_is_zero(&exists->b_refcnt));
3124 			arc_change_state(arc_anon, exists, hash_lock);
3125 			mutex_exit(hash_lock);
3126 			arc_hdr_destroy(exists);
3127 			exists = buf_hash_insert(hdr, &hash_lock);
3128 			ASSERT3P(exists, ==, NULL);
3129 		}
3130 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3131 		/* if it's not anon, we are doing a scrub */
3132 		if (hdr->b_state == arc_anon)
3133 			arc_access(hdr, hash_lock);
3134 		mutex_exit(hash_lock);
3135 	} else if (callback->awcb_done == NULL) {
3136 		int destroy_hdr;
3137 		/*
3138 		 * This is an anonymous buffer with no user callback,
3139 		 * destroy it if there are no active references.
3140 		 */
3141 		mutex_enter(&arc_eviction_mtx);
3142 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
3143 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3144 		mutex_exit(&arc_eviction_mtx);
3145 		if (destroy_hdr)
3146 			arc_hdr_destroy(hdr);
3147 	} else {
3148 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3149 	}
3150 	hdr->b_flags &= ~ARC_STORED;
3151 
3152 	if (callback->awcb_done) {
3153 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3154 		callback->awcb_done(zio, buf, callback->awcb_private);
3155 	}
3156 
3157 	kmem_free(callback, sizeof (arc_write_callback_t));
3158 }
3159 
3160 void
3161 write_policy(spa_t *spa, const writeprops_t *wp, zio_prop_t *zp)
3162 {
3163 	boolean_t ismd = (wp->wp_level > 0 || dmu_ot[wp->wp_type].ot_metadata);
3164 
3165 	/* Determine checksum setting */
3166 	if (ismd) {
3167 		/*
3168 		 * Metadata always gets checksummed.  If the data
3169 		 * checksum is multi-bit correctable, and it's not a
3170 		 * ZBT-style checksum, then it's suitable for metadata
3171 		 * as well.  Otherwise, the metadata checksum defaults
3172 		 * to fletcher4.
3173 		 */
3174 		if (zio_checksum_table[wp->wp_oschecksum].ci_correctable &&
3175 		    !zio_checksum_table[wp->wp_oschecksum].ci_zbt)
3176 			zp->zp_checksum = wp->wp_oschecksum;
3177 		else
3178 			zp->zp_checksum = ZIO_CHECKSUM_FLETCHER_4;
3179 	} else {
3180 		zp->zp_checksum = zio_checksum_select(wp->wp_dnchecksum,
3181 		    wp->wp_oschecksum);
3182 	}
3183 
3184 	/* Determine compression setting */
3185 	if (ismd) {
3186 		/*
3187 		 * XXX -- we should design a compression algorithm
3188 		 * that specializes in arrays of bps.
3189 		 */
3190 		zp->zp_compress = zfs_mdcomp_disable ? ZIO_COMPRESS_EMPTY :
3191 		    ZIO_COMPRESS_LZJB;
3192 	} else {
3193 		zp->zp_compress = zio_compress_select(wp->wp_dncompress,
3194 		    wp->wp_oscompress);
3195 	}
3196 
3197 	zp->zp_type = wp->wp_type;
3198 	zp->zp_level = wp->wp_level;
3199 	zp->zp_ndvas = MIN(wp->wp_copies + ismd, spa_max_replication(spa));
3200 }
3201 
3202 zio_t *
3203 arc_write(zio_t *pio, spa_t *spa, const writeprops_t *wp,
3204     boolean_t l2arc, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
3205     arc_done_func_t *ready, arc_done_func_t *done, void *private, int priority,
3206     int zio_flags, const zbookmark_t *zb)
3207 {
3208 	arc_buf_hdr_t *hdr = buf->b_hdr;
3209 	arc_write_callback_t *callback;
3210 	zio_t *zio;
3211 	zio_prop_t zp;
3212 
3213 	ASSERT(ready != NULL);
3214 	ASSERT(!HDR_IO_ERROR(hdr));
3215 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3216 	ASSERT(hdr->b_acb == 0);
3217 	if (l2arc)
3218 		hdr->b_flags |= ARC_L2CACHE;
3219 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3220 	callback->awcb_ready = ready;
3221 	callback->awcb_done = done;
3222 	callback->awcb_private = private;
3223 	callback->awcb_buf = buf;
3224 
3225 	write_policy(spa, wp, &zp);
3226 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, &zp,
3227 	    arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3228 
3229 	return (zio);
3230 }
3231 
3232 int
3233 arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
3234     zio_done_func_t *done, void *private, uint32_t arc_flags)
3235 {
3236 	arc_buf_hdr_t *ab;
3237 	kmutex_t *hash_lock;
3238 	zio_t	*zio;
3239 
3240 	/*
3241 	 * If this buffer is in the cache, release it, so it
3242 	 * can be re-used.
3243 	 */
3244 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
3245 	if (ab != NULL) {
3246 		/*
3247 		 * The checksum of blocks to free is not always
3248 		 * preserved (eg. on the deadlist).  However, if it is
3249 		 * nonzero, it should match what we have in the cache.
3250 		 */
3251 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
3252 		    bp->blk_cksum.zc_word[0] == ab->b_cksum0 ||
3253 		    bp->blk_fill == BLK_FILL_ALREADY_FREED);
3254 
3255 		if (ab->b_state != arc_anon)
3256 			arc_change_state(arc_anon, ab, hash_lock);
3257 		if (HDR_IO_IN_PROGRESS(ab)) {
3258 			/*
3259 			 * This should only happen when we prefetch.
3260 			 */
3261 			ASSERT(ab->b_flags & ARC_PREFETCH);
3262 			ASSERT3U(ab->b_datacnt, ==, 1);
3263 			ab->b_flags |= ARC_FREED_IN_READ;
3264 			if (HDR_IN_HASH_TABLE(ab))
3265 				buf_hash_remove(ab);
3266 			ab->b_arc_access = 0;
3267 			bzero(&ab->b_dva, sizeof (dva_t));
3268 			ab->b_birth = 0;
3269 			ab->b_cksum0 = 0;
3270 			ab->b_buf->b_efunc = NULL;
3271 			ab->b_buf->b_private = NULL;
3272 			mutex_exit(hash_lock);
3273 		} else if (refcount_is_zero(&ab->b_refcnt)) {
3274 			ab->b_flags |= ARC_FREE_IN_PROGRESS;
3275 			mutex_exit(hash_lock);
3276 			arc_hdr_destroy(ab);
3277 			ARCSTAT_BUMP(arcstat_deleted);
3278 		} else {
3279 			/*
3280 			 * We still have an active reference on this
3281 			 * buffer.  This can happen, e.g., from
3282 			 * dbuf_unoverride().
3283 			 */
3284 			ASSERT(!HDR_IN_HASH_TABLE(ab));
3285 			ab->b_arc_access = 0;
3286 			bzero(&ab->b_dva, sizeof (dva_t));
3287 			ab->b_birth = 0;
3288 			ab->b_cksum0 = 0;
3289 			ab->b_buf->b_efunc = NULL;
3290 			ab->b_buf->b_private = NULL;
3291 			mutex_exit(hash_lock);
3292 		}
3293 	}
3294 
3295 	zio = zio_free(pio, spa, txg, bp, done, private, ZIO_FLAG_MUSTSUCCEED);
3296 
3297 	if (arc_flags & ARC_WAIT)
3298 		return (zio_wait(zio));
3299 
3300 	ASSERT(arc_flags & ARC_NOWAIT);
3301 	zio_nowait(zio);
3302 
3303 	return (0);
3304 }
3305 
3306 static int
3307 arc_memory_throttle(uint64_t reserve, uint64_t txg)
3308 {
3309 #ifdef _KERNEL
3310 	uint64_t inflight_data = arc_anon->arcs_size;
3311 	uint64_t available_memory = ptob(freemem);
3312 	static uint64_t page_load = 0;
3313 	static uint64_t last_txg = 0;
3314 
3315 #if defined(__i386)
3316 	available_memory =
3317 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3318 #endif
3319 	if (available_memory >= zfs_write_limit_max)
3320 		return (0);
3321 
3322 	if (txg > last_txg) {
3323 		last_txg = txg;
3324 		page_load = 0;
3325 	}
3326 	/*
3327 	 * If we are in pageout, we know that memory is already tight,
3328 	 * the arc is already going to be evicting, so we just want to
3329 	 * continue to let page writes occur as quickly as possible.
3330 	 */
3331 	if (curproc == proc_pageout) {
3332 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
3333 			return (ERESTART);
3334 		/* Note: reserve is inflated, so we deflate */
3335 		page_load += reserve / 8;
3336 		return (0);
3337 	} else if (page_load > 0 && arc_reclaim_needed()) {
3338 		/* memory is low, delay before restarting */
3339 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3340 		return (EAGAIN);
3341 	}
3342 	page_load = 0;
3343 
3344 	if (arc_size > arc_c_min) {
3345 		uint64_t evictable_memory =
3346 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
3347 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
3348 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
3349 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
3350 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
3351 	}
3352 
3353 	if (inflight_data > available_memory / 4) {
3354 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3355 		return (ERESTART);
3356 	}
3357 #endif
3358 	return (0);
3359 }
3360 
3361 void
3362 arc_tempreserve_clear(uint64_t reserve)
3363 {
3364 	atomic_add_64(&arc_tempreserve, -reserve);
3365 	ASSERT((int64_t)arc_tempreserve >= 0);
3366 }
3367 
3368 int
3369 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3370 {
3371 	int error;
3372 
3373 #ifdef ZFS_DEBUG
3374 	/*
3375 	 * Once in a while, fail for no reason.  Everything should cope.
3376 	 */
3377 	if (spa_get_random(10000) == 0) {
3378 		dprintf("forcing random failure\n");
3379 		return (ERESTART);
3380 	}
3381 #endif
3382 	if (reserve > arc_c/4 && !arc_no_grow)
3383 		arc_c = MIN(arc_c_max, reserve * 4);
3384 	if (reserve > arc_c)
3385 		return (ENOMEM);
3386 
3387 	/*
3388 	 * Writes will, almost always, require additional memory allocations
3389 	 * in order to compress/encrypt/etc the data.  We therefor need to
3390 	 * make sure that there is sufficient available memory for this.
3391 	 */
3392 	if (error = arc_memory_throttle(reserve, txg))
3393 		return (error);
3394 
3395 	/*
3396 	 * Throttle writes when the amount of dirty data in the cache
3397 	 * gets too large.  We try to keep the cache less than half full
3398 	 * of dirty blocks so that our sync times don't grow too large.
3399 	 * Note: if two requests come in concurrently, we might let them
3400 	 * both succeed, when one of them should fail.  Not a huge deal.
3401 	 */
3402 	if (reserve + arc_tempreserve + arc_anon->arcs_size > arc_c / 2 &&
3403 	    arc_anon->arcs_size > arc_c / 4) {
3404 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3405 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3406 		    arc_tempreserve>>10,
3407 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3408 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3409 		    reserve>>10, arc_c>>10);
3410 		return (ERESTART);
3411 	}
3412 	atomic_add_64(&arc_tempreserve, reserve);
3413 	return (0);
3414 }
3415 
3416 void
3417 arc_init(void)
3418 {
3419 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3420 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3421 
3422 	/* Convert seconds to clock ticks */
3423 	arc_min_prefetch_lifespan = 1 * hz;
3424 
3425 	/* Start out with 1/8 of all memory */
3426 	arc_c = physmem * PAGESIZE / 8;
3427 
3428 #ifdef _KERNEL
3429 	/*
3430 	 * On architectures where the physical memory can be larger
3431 	 * than the addressable space (intel in 32-bit mode), we may
3432 	 * need to limit the cache to 1/8 of VM size.
3433 	 */
3434 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3435 #endif
3436 
3437 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
3438 	arc_c_min = MAX(arc_c / 4, 64<<20);
3439 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
3440 	if (arc_c * 8 >= 1<<30)
3441 		arc_c_max = (arc_c * 8) - (1<<30);
3442 	else
3443 		arc_c_max = arc_c_min;
3444 	arc_c_max = MAX(arc_c * 6, arc_c_max);
3445 
3446 	/*
3447 	 * Allow the tunables to override our calculations if they are
3448 	 * reasonable (ie. over 64MB)
3449 	 */
3450 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
3451 		arc_c_max = zfs_arc_max;
3452 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
3453 		arc_c_min = zfs_arc_min;
3454 
3455 	arc_c = arc_c_max;
3456 	arc_p = (arc_c >> 1);
3457 
3458 	/* limit meta-data to 1/4 of the arc capacity */
3459 	arc_meta_limit = arc_c_max / 4;
3460 
3461 	/* Allow the tunable to override if it is reasonable */
3462 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
3463 		arc_meta_limit = zfs_arc_meta_limit;
3464 
3465 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
3466 		arc_c_min = arc_meta_limit / 2;
3467 
3468 	if (zfs_arc_grow_retry > 0)
3469 		arc_grow_retry = zfs_arc_grow_retry;
3470 
3471 	if (zfs_arc_shrink_shift > 0)
3472 		arc_shrink_shift = zfs_arc_shrink_shift;
3473 
3474 	if (zfs_arc_p_min_shift > 0)
3475 		arc_p_min_shift = zfs_arc_p_min_shift;
3476 
3477 	/* if kmem_flags are set, lets try to use less memory */
3478 	if (kmem_debugging())
3479 		arc_c = arc_c / 2;
3480 	if (arc_c < arc_c_min)
3481 		arc_c = arc_c_min;
3482 
3483 	arc_anon = &ARC_anon;
3484 	arc_mru = &ARC_mru;
3485 	arc_mru_ghost = &ARC_mru_ghost;
3486 	arc_mfu = &ARC_mfu;
3487 	arc_mfu_ghost = &ARC_mfu_ghost;
3488 	arc_l2c_only = &ARC_l2c_only;
3489 	arc_size = 0;
3490 
3491 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3492 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3493 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3494 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3495 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3496 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3497 
3498 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
3499 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3500 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
3501 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3502 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
3503 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3504 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
3505 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3506 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
3507 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3508 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
3509 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3510 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
3511 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3512 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
3513 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3514 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
3515 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3516 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
3517 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3518 
3519 	buf_init();
3520 
3521 	arc_thread_exit = 0;
3522 	arc_eviction_list = NULL;
3523 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
3524 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3525 
3526 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
3527 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
3528 
3529 	if (arc_ksp != NULL) {
3530 		arc_ksp->ks_data = &arc_stats;
3531 		kstat_install(arc_ksp);
3532 	}
3533 
3534 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3535 	    TS_RUN, minclsyspri);
3536 
3537 	arc_dead = FALSE;
3538 	arc_warm = B_FALSE;
3539 
3540 	if (zfs_write_limit_max == 0)
3541 		zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
3542 	else
3543 		zfs_write_limit_shift = 0;
3544 	mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
3545 }
3546 
3547 void
3548 arc_fini(void)
3549 {
3550 	mutex_enter(&arc_reclaim_thr_lock);
3551 	arc_thread_exit = 1;
3552 	while (arc_thread_exit != 0)
3553 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3554 	mutex_exit(&arc_reclaim_thr_lock);
3555 
3556 	arc_flush(NULL);
3557 
3558 	arc_dead = TRUE;
3559 
3560 	if (arc_ksp != NULL) {
3561 		kstat_delete(arc_ksp);
3562 		arc_ksp = NULL;
3563 	}
3564 
3565 	mutex_destroy(&arc_eviction_mtx);
3566 	mutex_destroy(&arc_reclaim_thr_lock);
3567 	cv_destroy(&arc_reclaim_thr_cv);
3568 
3569 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
3570 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
3571 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
3572 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
3573 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
3574 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
3575 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
3576 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3577 
3578 	mutex_destroy(&arc_anon->arcs_mtx);
3579 	mutex_destroy(&arc_mru->arcs_mtx);
3580 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
3581 	mutex_destroy(&arc_mfu->arcs_mtx);
3582 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
3583 	mutex_destroy(&arc_l2c_only->arcs_mtx);
3584 
3585 	mutex_destroy(&zfs_write_limit_lock);
3586 
3587 	buf_fini();
3588 }
3589 
3590 /*
3591  * Level 2 ARC
3592  *
3593  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
3594  * It uses dedicated storage devices to hold cached data, which are populated
3595  * using large infrequent writes.  The main role of this cache is to boost
3596  * the performance of random read workloads.  The intended L2ARC devices
3597  * include short-stroked disks, solid state disks, and other media with
3598  * substantially faster read latency than disk.
3599  *
3600  *                 +-----------------------+
3601  *                 |         ARC           |
3602  *                 +-----------------------+
3603  *                    |         ^     ^
3604  *                    |         |     |
3605  *      l2arc_feed_thread()    arc_read()
3606  *                    |         |     |
3607  *                    |  l2arc read   |
3608  *                    V         |     |
3609  *               +---------------+    |
3610  *               |     L2ARC     |    |
3611  *               +---------------+    |
3612  *                   |    ^           |
3613  *          l2arc_write() |           |
3614  *                   |    |           |
3615  *                   V    |           |
3616  *                 +-------+      +-------+
3617  *                 | vdev  |      | vdev  |
3618  *                 | cache |      | cache |
3619  *                 +-------+      +-------+
3620  *                 +=========+     .-----.
3621  *                 :  L2ARC  :    |-_____-|
3622  *                 : devices :    | Disks |
3623  *                 +=========+    `-_____-'
3624  *
3625  * Read requests are satisfied from the following sources, in order:
3626  *
3627  *	1) ARC
3628  *	2) vdev cache of L2ARC devices
3629  *	3) L2ARC devices
3630  *	4) vdev cache of disks
3631  *	5) disks
3632  *
3633  * Some L2ARC device types exhibit extremely slow write performance.
3634  * To accommodate for this there are some significant differences between
3635  * the L2ARC and traditional cache design:
3636  *
3637  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
3638  * the ARC behave as usual, freeing buffers and placing headers on ghost
3639  * lists.  The ARC does not send buffers to the L2ARC during eviction as
3640  * this would add inflated write latencies for all ARC memory pressure.
3641  *
3642  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
3643  * It does this by periodically scanning buffers from the eviction-end of
3644  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3645  * not already there.  It scans until a headroom of buffers is satisfied,
3646  * which itself is a buffer for ARC eviction.  The thread that does this is
3647  * l2arc_feed_thread(), illustrated below; example sizes are included to
3648  * provide a better sense of ratio than this diagram:
3649  *
3650  *	       head -->                        tail
3651  *	        +---------------------+----------+
3652  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
3653  *	        +---------------------+----------+   |   o L2ARC eligible
3654  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
3655  *	        +---------------------+----------+   |
3656  *	             15.9 Gbytes      ^ 32 Mbytes    |
3657  *	                           headroom          |
3658  *	                                      l2arc_feed_thread()
3659  *	                                             |
3660  *	                 l2arc write hand <--[oooo]--'
3661  *	                         |           8 Mbyte
3662  *	                         |          write max
3663  *	                         V
3664  *		  +==============================+
3665  *	L2ARC dev |####|#|###|###|    |####| ... |
3666  *	          +==============================+
3667  *	                     32 Gbytes
3668  *
3669  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
3670  * evicted, then the L2ARC has cached a buffer much sooner than it probably
3671  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
3672  * safe to say that this is an uncommon case, since buffers at the end of
3673  * the ARC lists have moved there due to inactivity.
3674  *
3675  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
3676  * then the L2ARC simply misses copying some buffers.  This serves as a
3677  * pressure valve to prevent heavy read workloads from both stalling the ARC
3678  * with waits and clogging the L2ARC with writes.  This also helps prevent
3679  * the potential for the L2ARC to churn if it attempts to cache content too
3680  * quickly, such as during backups of the entire pool.
3681  *
3682  * 5. After system boot and before the ARC has filled main memory, there are
3683  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
3684  * lists can remain mostly static.  Instead of searching from tail of these
3685  * lists as pictured, the l2arc_feed_thread() will search from the list heads
3686  * for eligible buffers, greatly increasing its chance of finding them.
3687  *
3688  * The L2ARC device write speed is also boosted during this time so that
3689  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
3690  * there are no L2ARC reads, and no fear of degrading read performance
3691  * through increased writes.
3692  *
3693  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
3694  * the vdev queue can aggregate them into larger and fewer writes.  Each
3695  * device is written to in a rotor fashion, sweeping writes through
3696  * available space then repeating.
3697  *
3698  * 7. The L2ARC does not store dirty content.  It never needs to flush
3699  * write buffers back to disk based storage.
3700  *
3701  * 8. If an ARC buffer is written (and dirtied) which also exists in the
3702  * L2ARC, the now stale L2ARC buffer is immediately dropped.
3703  *
3704  * The performance of the L2ARC can be tweaked by a number of tunables, which
3705  * may be necessary for different workloads:
3706  *
3707  *	l2arc_write_max		max write bytes per interval
3708  *	l2arc_write_boost	extra write bytes during device warmup
3709  *	l2arc_noprefetch	skip caching prefetched buffers
3710  *	l2arc_headroom		number of max device writes to precache
3711  *	l2arc_feed_secs		seconds between L2ARC writing
3712  *
3713  * Tunables may be removed or added as future performance improvements are
3714  * integrated, and also may become zpool properties.
3715  *
3716  * There are three key functions that control how the L2ARC warms up:
3717  *
3718  *	l2arc_write_eligible()	check if a buffer is eligible to cache
3719  *	l2arc_write_size()	calculate how much to write
3720  *	l2arc_write_interval()	calculate sleep delay between writes
3721  *
3722  * These three functions determine what to write, how much, and how quickly
3723  * to send writes.
3724  */
3725 
3726 static boolean_t
3727 l2arc_write_eligible(spa_t *spa, arc_buf_hdr_t *ab)
3728 {
3729 	/*
3730 	 * A buffer is *not* eligible for the L2ARC if it:
3731 	 * 1. belongs to a different spa.
3732 	 * 2. has no attached buffer.
3733 	 * 3. is already cached on the L2ARC.
3734 	 * 4. has an I/O in progress (it may be an incomplete read).
3735 	 * 5. is flagged not eligible (zfs property).
3736 	 */
3737 	if (ab->b_spa != spa || ab->b_buf == NULL || ab->b_l2hdr != NULL ||
3738 	    HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
3739 		return (B_FALSE);
3740 
3741 	return (B_TRUE);
3742 }
3743 
3744 static uint64_t
3745 l2arc_write_size(l2arc_dev_t *dev)
3746 {
3747 	uint64_t size;
3748 
3749 	size = dev->l2ad_write;
3750 
3751 	if (arc_warm == B_FALSE)
3752 		size += dev->l2ad_boost;
3753 
3754 	return (size);
3755 
3756 }
3757 
3758 static clock_t
3759 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
3760 {
3761 	clock_t interval, next;
3762 
3763 	/*
3764 	 * If the ARC lists are busy, increase our write rate; if the
3765 	 * lists are stale, idle back.  This is achieved by checking
3766 	 * how much we previously wrote - if it was more than half of
3767 	 * what we wanted, schedule the next write much sooner.
3768 	 */
3769 	if (l2arc_feed_again && wrote > (wanted / 2))
3770 		interval = (hz * l2arc_feed_min_ms) / 1000;
3771 	else
3772 		interval = hz * l2arc_feed_secs;
3773 
3774 	next = MAX(lbolt, MIN(lbolt + interval, began + interval));
3775 
3776 	return (next);
3777 }
3778 
3779 static void
3780 l2arc_hdr_stat_add(void)
3781 {
3782 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
3783 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
3784 }
3785 
3786 static void
3787 l2arc_hdr_stat_remove(void)
3788 {
3789 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
3790 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
3791 }
3792 
3793 /*
3794  * Cycle through L2ARC devices.  This is how L2ARC load balances.
3795  * If a device is returned, this also returns holding the spa config lock.
3796  */
3797 static l2arc_dev_t *
3798 l2arc_dev_get_next(void)
3799 {
3800 	l2arc_dev_t *first, *next = NULL;
3801 
3802 	/*
3803 	 * Lock out the removal of spas (spa_namespace_lock), then removal
3804 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
3805 	 * both locks will be dropped and a spa config lock held instead.
3806 	 */
3807 	mutex_enter(&spa_namespace_lock);
3808 	mutex_enter(&l2arc_dev_mtx);
3809 
3810 	/* if there are no vdevs, there is nothing to do */
3811 	if (l2arc_ndev == 0)
3812 		goto out;
3813 
3814 	first = NULL;
3815 	next = l2arc_dev_last;
3816 	do {
3817 		/* loop around the list looking for a non-faulted vdev */
3818 		if (next == NULL) {
3819 			next = list_head(l2arc_dev_list);
3820 		} else {
3821 			next = list_next(l2arc_dev_list, next);
3822 			if (next == NULL)
3823 				next = list_head(l2arc_dev_list);
3824 		}
3825 
3826 		/* if we have come back to the start, bail out */
3827 		if (first == NULL)
3828 			first = next;
3829 		else if (next == first)
3830 			break;
3831 
3832 	} while (vdev_is_dead(next->l2ad_vdev));
3833 
3834 	/* if we were unable to find any usable vdevs, return NULL */
3835 	if (vdev_is_dead(next->l2ad_vdev))
3836 		next = NULL;
3837 
3838 	l2arc_dev_last = next;
3839 
3840 out:
3841 	mutex_exit(&l2arc_dev_mtx);
3842 
3843 	/*
3844 	 * Grab the config lock to prevent the 'next' device from being
3845 	 * removed while we are writing to it.
3846 	 */
3847 	if (next != NULL)
3848 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
3849 	mutex_exit(&spa_namespace_lock);
3850 
3851 	return (next);
3852 }
3853 
3854 /*
3855  * Free buffers that were tagged for destruction.
3856  */
3857 static void
3858 l2arc_do_free_on_write()
3859 {
3860 	list_t *buflist;
3861 	l2arc_data_free_t *df, *df_prev;
3862 
3863 	mutex_enter(&l2arc_free_on_write_mtx);
3864 	buflist = l2arc_free_on_write;
3865 
3866 	for (df = list_tail(buflist); df; df = df_prev) {
3867 		df_prev = list_prev(buflist, df);
3868 		ASSERT(df->l2df_data != NULL);
3869 		ASSERT(df->l2df_func != NULL);
3870 		df->l2df_func(df->l2df_data, df->l2df_size);
3871 		list_remove(buflist, df);
3872 		kmem_free(df, sizeof (l2arc_data_free_t));
3873 	}
3874 
3875 	mutex_exit(&l2arc_free_on_write_mtx);
3876 }
3877 
3878 /*
3879  * A write to a cache device has completed.  Update all headers to allow
3880  * reads from these buffers to begin.
3881  */
3882 static void
3883 l2arc_write_done(zio_t *zio)
3884 {
3885 	l2arc_write_callback_t *cb;
3886 	l2arc_dev_t *dev;
3887 	list_t *buflist;
3888 	arc_buf_hdr_t *head, *ab, *ab_prev;
3889 	l2arc_buf_hdr_t *abl2;
3890 	kmutex_t *hash_lock;
3891 
3892 	cb = zio->io_private;
3893 	ASSERT(cb != NULL);
3894 	dev = cb->l2wcb_dev;
3895 	ASSERT(dev != NULL);
3896 	head = cb->l2wcb_head;
3897 	ASSERT(head != NULL);
3898 	buflist = dev->l2ad_buflist;
3899 	ASSERT(buflist != NULL);
3900 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
3901 	    l2arc_write_callback_t *, cb);
3902 
3903 	if (zio->io_error != 0)
3904 		ARCSTAT_BUMP(arcstat_l2_writes_error);
3905 
3906 	mutex_enter(&l2arc_buflist_mtx);
3907 
3908 	/*
3909 	 * All writes completed, or an error was hit.
3910 	 */
3911 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
3912 		ab_prev = list_prev(buflist, ab);
3913 
3914 		hash_lock = HDR_LOCK(ab);
3915 		if (!mutex_tryenter(hash_lock)) {
3916 			/*
3917 			 * This buffer misses out.  It may be in a stage
3918 			 * of eviction.  Its ARC_L2_WRITING flag will be
3919 			 * left set, denying reads to this buffer.
3920 			 */
3921 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
3922 			continue;
3923 		}
3924 
3925 		if (zio->io_error != 0) {
3926 			/*
3927 			 * Error - drop L2ARC entry.
3928 			 */
3929 			list_remove(buflist, ab);
3930 			abl2 = ab->b_l2hdr;
3931 			ab->b_l2hdr = NULL;
3932 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
3933 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
3934 		}
3935 
3936 		/*
3937 		 * Allow ARC to begin reads to this L2ARC entry.
3938 		 */
3939 		ab->b_flags &= ~ARC_L2_WRITING;
3940 
3941 		mutex_exit(hash_lock);
3942 	}
3943 
3944 	atomic_inc_64(&l2arc_writes_done);
3945 	list_remove(buflist, head);
3946 	kmem_cache_free(hdr_cache, head);
3947 	mutex_exit(&l2arc_buflist_mtx);
3948 
3949 	l2arc_do_free_on_write();
3950 
3951 	kmem_free(cb, sizeof (l2arc_write_callback_t));
3952 }
3953 
3954 /*
3955  * A read to a cache device completed.  Validate buffer contents before
3956  * handing over to the regular ARC routines.
3957  */
3958 static void
3959 l2arc_read_done(zio_t *zio)
3960 {
3961 	l2arc_read_callback_t *cb;
3962 	arc_buf_hdr_t *hdr;
3963 	arc_buf_t *buf;
3964 	kmutex_t *hash_lock;
3965 	int equal;
3966 
3967 	ASSERT(zio->io_vd != NULL);
3968 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
3969 
3970 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
3971 
3972 	cb = zio->io_private;
3973 	ASSERT(cb != NULL);
3974 	buf = cb->l2rcb_buf;
3975 	ASSERT(buf != NULL);
3976 	hdr = buf->b_hdr;
3977 	ASSERT(hdr != NULL);
3978 
3979 	hash_lock = HDR_LOCK(hdr);
3980 	mutex_enter(hash_lock);
3981 
3982 	/*
3983 	 * Check this survived the L2ARC journey.
3984 	 */
3985 	equal = arc_cksum_equal(buf);
3986 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
3987 		mutex_exit(hash_lock);
3988 		zio->io_private = buf;
3989 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
3990 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
3991 		arc_read_done(zio);
3992 	} else {
3993 		mutex_exit(hash_lock);
3994 		/*
3995 		 * Buffer didn't survive caching.  Increment stats and
3996 		 * reissue to the original storage device.
3997 		 */
3998 		if (zio->io_error != 0) {
3999 			ARCSTAT_BUMP(arcstat_l2_io_error);
4000 		} else {
4001 			zio->io_error = EIO;
4002 		}
4003 		if (!equal)
4004 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4005 
4006 		/*
4007 		 * If there's no waiter, issue an async i/o to the primary
4008 		 * storage now.  If there *is* a waiter, the caller must
4009 		 * issue the i/o in a context where it's OK to block.
4010 		 */
4011 		if (zio->io_waiter == NULL) {
4012 			zio_t *pio = zio_unique_parent(zio);
4013 
4014 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4015 
4016 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4017 			    buf->b_data, zio->io_size, arc_read_done, buf,
4018 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4019 		}
4020 	}
4021 
4022 	kmem_free(cb, sizeof (l2arc_read_callback_t));
4023 }
4024 
4025 /*
4026  * This is the list priority from which the L2ARC will search for pages to
4027  * cache.  This is used within loops (0..3) to cycle through lists in the
4028  * desired order.  This order can have a significant effect on cache
4029  * performance.
4030  *
4031  * Currently the metadata lists are hit first, MFU then MRU, followed by
4032  * the data lists.  This function returns a locked list, and also returns
4033  * the lock pointer.
4034  */
4035 static list_t *
4036 l2arc_list_locked(int list_num, kmutex_t **lock)
4037 {
4038 	list_t *list;
4039 
4040 	ASSERT(list_num >= 0 && list_num <= 3);
4041 
4042 	switch (list_num) {
4043 	case 0:
4044 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4045 		*lock = &arc_mfu->arcs_mtx;
4046 		break;
4047 	case 1:
4048 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4049 		*lock = &arc_mru->arcs_mtx;
4050 		break;
4051 	case 2:
4052 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4053 		*lock = &arc_mfu->arcs_mtx;
4054 		break;
4055 	case 3:
4056 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4057 		*lock = &arc_mru->arcs_mtx;
4058 		break;
4059 	}
4060 
4061 	ASSERT(!(MUTEX_HELD(*lock)));
4062 	mutex_enter(*lock);
4063 	return (list);
4064 }
4065 
4066 /*
4067  * Evict buffers from the device write hand to the distance specified in
4068  * bytes.  This distance may span populated buffers, it may span nothing.
4069  * This is clearing a region on the L2ARC device ready for writing.
4070  * If the 'all' boolean is set, every buffer is evicted.
4071  */
4072 static void
4073 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4074 {
4075 	list_t *buflist;
4076 	l2arc_buf_hdr_t *abl2;
4077 	arc_buf_hdr_t *ab, *ab_prev;
4078 	kmutex_t *hash_lock;
4079 	uint64_t taddr;
4080 
4081 	buflist = dev->l2ad_buflist;
4082 
4083 	if (buflist == NULL)
4084 		return;
4085 
4086 	if (!all && dev->l2ad_first) {
4087 		/*
4088 		 * This is the first sweep through the device.  There is
4089 		 * nothing to evict.
4090 		 */
4091 		return;
4092 	}
4093 
4094 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4095 		/*
4096 		 * When nearing the end of the device, evict to the end
4097 		 * before the device write hand jumps to the start.
4098 		 */
4099 		taddr = dev->l2ad_end;
4100 	} else {
4101 		taddr = dev->l2ad_hand + distance;
4102 	}
4103 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4104 	    uint64_t, taddr, boolean_t, all);
4105 
4106 top:
4107 	mutex_enter(&l2arc_buflist_mtx);
4108 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
4109 		ab_prev = list_prev(buflist, ab);
4110 
4111 		hash_lock = HDR_LOCK(ab);
4112 		if (!mutex_tryenter(hash_lock)) {
4113 			/*
4114 			 * Missed the hash lock.  Retry.
4115 			 */
4116 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4117 			mutex_exit(&l2arc_buflist_mtx);
4118 			mutex_enter(hash_lock);
4119 			mutex_exit(hash_lock);
4120 			goto top;
4121 		}
4122 
4123 		if (HDR_L2_WRITE_HEAD(ab)) {
4124 			/*
4125 			 * We hit a write head node.  Leave it for
4126 			 * l2arc_write_done().
4127 			 */
4128 			list_remove(buflist, ab);
4129 			mutex_exit(hash_lock);
4130 			continue;
4131 		}
4132 
4133 		if (!all && ab->b_l2hdr != NULL &&
4134 		    (ab->b_l2hdr->b_daddr > taddr ||
4135 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4136 			/*
4137 			 * We've evicted to the target address,
4138 			 * or the end of the device.
4139 			 */
4140 			mutex_exit(hash_lock);
4141 			break;
4142 		}
4143 
4144 		if (HDR_FREE_IN_PROGRESS(ab)) {
4145 			/*
4146 			 * Already on the path to destruction.
4147 			 */
4148 			mutex_exit(hash_lock);
4149 			continue;
4150 		}
4151 
4152 		if (ab->b_state == arc_l2c_only) {
4153 			ASSERT(!HDR_L2_READING(ab));
4154 			/*
4155 			 * This doesn't exist in the ARC.  Destroy.
4156 			 * arc_hdr_destroy() will call list_remove()
4157 			 * and decrement arcstat_l2_size.
4158 			 */
4159 			arc_change_state(arc_anon, ab, hash_lock);
4160 			arc_hdr_destroy(ab);
4161 		} else {
4162 			/*
4163 			 * Invalidate issued or about to be issued
4164 			 * reads, since we may be about to write
4165 			 * over this location.
4166 			 */
4167 			if (HDR_L2_READING(ab)) {
4168 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
4169 				ab->b_flags |= ARC_L2_EVICTED;
4170 			}
4171 
4172 			/*
4173 			 * Tell ARC this no longer exists in L2ARC.
4174 			 */
4175 			if (ab->b_l2hdr != NULL) {
4176 				abl2 = ab->b_l2hdr;
4177 				ab->b_l2hdr = NULL;
4178 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4179 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4180 			}
4181 			list_remove(buflist, ab);
4182 
4183 			/*
4184 			 * This may have been leftover after a
4185 			 * failed write.
4186 			 */
4187 			ab->b_flags &= ~ARC_L2_WRITING;
4188 		}
4189 		mutex_exit(hash_lock);
4190 	}
4191 	mutex_exit(&l2arc_buflist_mtx);
4192 
4193 	spa_l2cache_space_update(dev->l2ad_vdev, 0, -(taddr - dev->l2ad_evict));
4194 	dev->l2ad_evict = taddr;
4195 }
4196 
4197 /*
4198  * Find and write ARC buffers to the L2ARC device.
4199  *
4200  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4201  * for reading until they have completed writing.
4202  */
4203 static uint64_t
4204 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
4205 {
4206 	arc_buf_hdr_t *ab, *ab_prev, *head;
4207 	l2arc_buf_hdr_t *hdrl2;
4208 	list_t *list;
4209 	uint64_t passed_sz, write_sz, buf_sz, headroom;
4210 	void *buf_data;
4211 	kmutex_t *hash_lock, *list_lock;
4212 	boolean_t have_lock, full;
4213 	l2arc_write_callback_t *cb;
4214 	zio_t *pio, *wzio;
4215 
4216 	ASSERT(dev->l2ad_vdev != NULL);
4217 
4218 	pio = NULL;
4219 	write_sz = 0;
4220 	full = B_FALSE;
4221 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4222 	head->b_flags |= ARC_L2_WRITE_HEAD;
4223 
4224 	/*
4225 	 * Copy buffers for L2ARC writing.
4226 	 */
4227 	mutex_enter(&l2arc_buflist_mtx);
4228 	for (int try = 0; try <= 3; try++) {
4229 		list = l2arc_list_locked(try, &list_lock);
4230 		passed_sz = 0;
4231 
4232 		/*
4233 		 * L2ARC fast warmup.
4234 		 *
4235 		 * Until the ARC is warm and starts to evict, read from the
4236 		 * head of the ARC lists rather than the tail.
4237 		 */
4238 		headroom = target_sz * l2arc_headroom;
4239 		if (arc_warm == B_FALSE)
4240 			ab = list_head(list);
4241 		else
4242 			ab = list_tail(list);
4243 
4244 		for (; ab; ab = ab_prev) {
4245 			if (arc_warm == B_FALSE)
4246 				ab_prev = list_next(list, ab);
4247 			else
4248 				ab_prev = list_prev(list, ab);
4249 
4250 			hash_lock = HDR_LOCK(ab);
4251 			have_lock = MUTEX_HELD(hash_lock);
4252 			if (!have_lock && !mutex_tryenter(hash_lock)) {
4253 				/*
4254 				 * Skip this buffer rather than waiting.
4255 				 */
4256 				continue;
4257 			}
4258 
4259 			passed_sz += ab->b_size;
4260 			if (passed_sz > headroom) {
4261 				/*
4262 				 * Searched too far.
4263 				 */
4264 				mutex_exit(hash_lock);
4265 				break;
4266 			}
4267 
4268 			if (!l2arc_write_eligible(spa, ab)) {
4269 				mutex_exit(hash_lock);
4270 				continue;
4271 			}
4272 
4273 			if ((write_sz + ab->b_size) > target_sz) {
4274 				full = B_TRUE;
4275 				mutex_exit(hash_lock);
4276 				break;
4277 			}
4278 
4279 			if (pio == NULL) {
4280 				/*
4281 				 * Insert a dummy header on the buflist so
4282 				 * l2arc_write_done() can find where the
4283 				 * write buffers begin without searching.
4284 				 */
4285 				list_insert_head(dev->l2ad_buflist, head);
4286 
4287 				cb = kmem_alloc(
4288 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
4289 				cb->l2wcb_dev = dev;
4290 				cb->l2wcb_head = head;
4291 				pio = zio_root(spa, l2arc_write_done, cb,
4292 				    ZIO_FLAG_CANFAIL);
4293 			}
4294 
4295 			/*
4296 			 * Create and add a new L2ARC header.
4297 			 */
4298 			hdrl2 = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
4299 			hdrl2->b_dev = dev;
4300 			hdrl2->b_daddr = dev->l2ad_hand;
4301 
4302 			ab->b_flags |= ARC_L2_WRITING;
4303 			ab->b_l2hdr = hdrl2;
4304 			list_insert_head(dev->l2ad_buflist, ab);
4305 			buf_data = ab->b_buf->b_data;
4306 			buf_sz = ab->b_size;
4307 
4308 			/*
4309 			 * Compute and store the buffer cksum before
4310 			 * writing.  On debug the cksum is verified first.
4311 			 */
4312 			arc_cksum_verify(ab->b_buf);
4313 			arc_cksum_compute(ab->b_buf, B_TRUE);
4314 
4315 			mutex_exit(hash_lock);
4316 
4317 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
4318 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
4319 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
4320 			    ZIO_FLAG_CANFAIL, B_FALSE);
4321 
4322 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
4323 			    zio_t *, wzio);
4324 			(void) zio_nowait(wzio);
4325 
4326 			/*
4327 			 * Keep the clock hand suitably device-aligned.
4328 			 */
4329 			buf_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
4330 
4331 			write_sz += buf_sz;
4332 			dev->l2ad_hand += buf_sz;
4333 		}
4334 
4335 		mutex_exit(list_lock);
4336 
4337 		if (full == B_TRUE)
4338 			break;
4339 	}
4340 	mutex_exit(&l2arc_buflist_mtx);
4341 
4342 	if (pio == NULL) {
4343 		ASSERT3U(write_sz, ==, 0);
4344 		kmem_cache_free(hdr_cache, head);
4345 		return (0);
4346 	}
4347 
4348 	ASSERT3U(write_sz, <=, target_sz);
4349 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
4350 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_sz);
4351 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
4352 	spa_l2cache_space_update(dev->l2ad_vdev, 0, write_sz);
4353 
4354 	/*
4355 	 * Bump device hand to the device start if it is approaching the end.
4356 	 * l2arc_evict() will already have evicted ahead for this case.
4357 	 */
4358 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
4359 		spa_l2cache_space_update(dev->l2ad_vdev, 0,
4360 		    dev->l2ad_end - dev->l2ad_hand);
4361 		dev->l2ad_hand = dev->l2ad_start;
4362 		dev->l2ad_evict = dev->l2ad_start;
4363 		dev->l2ad_first = B_FALSE;
4364 	}
4365 
4366 	dev->l2ad_writing = B_TRUE;
4367 	(void) zio_wait(pio);
4368 	dev->l2ad_writing = B_FALSE;
4369 
4370 	return (write_sz);
4371 }
4372 
4373 /*
4374  * This thread feeds the L2ARC at regular intervals.  This is the beating
4375  * heart of the L2ARC.
4376  */
4377 static void
4378 l2arc_feed_thread(void)
4379 {
4380 	callb_cpr_t cpr;
4381 	l2arc_dev_t *dev;
4382 	spa_t *spa;
4383 	uint64_t size, wrote;
4384 	clock_t begin, next = lbolt;
4385 
4386 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
4387 
4388 	mutex_enter(&l2arc_feed_thr_lock);
4389 
4390 	while (l2arc_thread_exit == 0) {
4391 		CALLB_CPR_SAFE_BEGIN(&cpr);
4392 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
4393 		    next);
4394 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
4395 		next = lbolt + hz;
4396 
4397 		/*
4398 		 * Quick check for L2ARC devices.
4399 		 */
4400 		mutex_enter(&l2arc_dev_mtx);
4401 		if (l2arc_ndev == 0) {
4402 			mutex_exit(&l2arc_dev_mtx);
4403 			continue;
4404 		}
4405 		mutex_exit(&l2arc_dev_mtx);
4406 		begin = lbolt;
4407 
4408 		/*
4409 		 * This selects the next l2arc device to write to, and in
4410 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
4411 		 * will return NULL if there are now no l2arc devices or if
4412 		 * they are all faulted.
4413 		 *
4414 		 * If a device is returned, its spa's config lock is also
4415 		 * held to prevent device removal.  l2arc_dev_get_next()
4416 		 * will grab and release l2arc_dev_mtx.
4417 		 */
4418 		if ((dev = l2arc_dev_get_next()) == NULL)
4419 			continue;
4420 
4421 		spa = dev->l2ad_spa;
4422 		ASSERT(spa != NULL);
4423 
4424 		/*
4425 		 * Avoid contributing to memory pressure.
4426 		 */
4427 		if (arc_reclaim_needed()) {
4428 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
4429 			spa_config_exit(spa, SCL_L2ARC, dev);
4430 			continue;
4431 		}
4432 
4433 		ARCSTAT_BUMP(arcstat_l2_feeds);
4434 
4435 		size = l2arc_write_size(dev);
4436 
4437 		/*
4438 		 * Evict L2ARC buffers that will be overwritten.
4439 		 */
4440 		l2arc_evict(dev, size, B_FALSE);
4441 
4442 		/*
4443 		 * Write ARC buffers.
4444 		 */
4445 		wrote = l2arc_write_buffers(spa, dev, size);
4446 
4447 		/*
4448 		 * Calculate interval between writes.
4449 		 */
4450 		next = l2arc_write_interval(begin, size, wrote);
4451 		spa_config_exit(spa, SCL_L2ARC, dev);
4452 	}
4453 
4454 	l2arc_thread_exit = 0;
4455 	cv_broadcast(&l2arc_feed_thr_cv);
4456 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
4457 	thread_exit();
4458 }
4459 
4460 boolean_t
4461 l2arc_vdev_present(vdev_t *vd)
4462 {
4463 	l2arc_dev_t *dev;
4464 
4465 	mutex_enter(&l2arc_dev_mtx);
4466 	for (dev = list_head(l2arc_dev_list); dev != NULL;
4467 	    dev = list_next(l2arc_dev_list, dev)) {
4468 		if (dev->l2ad_vdev == vd)
4469 			break;
4470 	}
4471 	mutex_exit(&l2arc_dev_mtx);
4472 
4473 	return (dev != NULL);
4474 }
4475 
4476 /*
4477  * Add a vdev for use by the L2ARC.  By this point the spa has already
4478  * validated the vdev and opened it.
4479  */
4480 void
4481 l2arc_add_vdev(spa_t *spa, vdev_t *vd, uint64_t start, uint64_t end)
4482 {
4483 	l2arc_dev_t *adddev;
4484 
4485 	ASSERT(!l2arc_vdev_present(vd));
4486 
4487 	/*
4488 	 * Create a new l2arc device entry.
4489 	 */
4490 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
4491 	adddev->l2ad_spa = spa;
4492 	adddev->l2ad_vdev = vd;
4493 	adddev->l2ad_write = l2arc_write_max;
4494 	adddev->l2ad_boost = l2arc_write_boost;
4495 	adddev->l2ad_start = start;
4496 	adddev->l2ad_end = end;
4497 	adddev->l2ad_hand = adddev->l2ad_start;
4498 	adddev->l2ad_evict = adddev->l2ad_start;
4499 	adddev->l2ad_first = B_TRUE;
4500 	adddev->l2ad_writing = B_FALSE;
4501 	ASSERT3U(adddev->l2ad_write, >, 0);
4502 
4503 	/*
4504 	 * This is a list of all ARC buffers that are still valid on the
4505 	 * device.
4506 	 */
4507 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
4508 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
4509 	    offsetof(arc_buf_hdr_t, b_l2node));
4510 
4511 	spa_l2cache_space_update(vd, adddev->l2ad_end - adddev->l2ad_hand, 0);
4512 
4513 	/*
4514 	 * Add device to global list
4515 	 */
4516 	mutex_enter(&l2arc_dev_mtx);
4517 	list_insert_head(l2arc_dev_list, adddev);
4518 	atomic_inc_64(&l2arc_ndev);
4519 	mutex_exit(&l2arc_dev_mtx);
4520 }
4521 
4522 /*
4523  * Remove a vdev from the L2ARC.
4524  */
4525 void
4526 l2arc_remove_vdev(vdev_t *vd)
4527 {
4528 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
4529 
4530 	/*
4531 	 * Find the device by vdev
4532 	 */
4533 	mutex_enter(&l2arc_dev_mtx);
4534 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
4535 		nextdev = list_next(l2arc_dev_list, dev);
4536 		if (vd == dev->l2ad_vdev) {
4537 			remdev = dev;
4538 			break;
4539 		}
4540 	}
4541 	ASSERT(remdev != NULL);
4542 
4543 	/*
4544 	 * Remove device from global list
4545 	 */
4546 	list_remove(l2arc_dev_list, remdev);
4547 	l2arc_dev_last = NULL;		/* may have been invalidated */
4548 	atomic_dec_64(&l2arc_ndev);
4549 	mutex_exit(&l2arc_dev_mtx);
4550 
4551 	/*
4552 	 * Clear all buflists and ARC references.  L2ARC device flush.
4553 	 */
4554 	l2arc_evict(remdev, 0, B_TRUE);
4555 	list_destroy(remdev->l2ad_buflist);
4556 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
4557 	kmem_free(remdev, sizeof (l2arc_dev_t));
4558 }
4559 
4560 void
4561 l2arc_init(void)
4562 {
4563 	l2arc_thread_exit = 0;
4564 	l2arc_ndev = 0;
4565 	l2arc_writes_sent = 0;
4566 	l2arc_writes_done = 0;
4567 
4568 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4569 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
4570 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
4571 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
4572 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
4573 
4574 	l2arc_dev_list = &L2ARC_dev_list;
4575 	l2arc_free_on_write = &L2ARC_free_on_write;
4576 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
4577 	    offsetof(l2arc_dev_t, l2ad_node));
4578 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
4579 	    offsetof(l2arc_data_free_t, l2df_list_node));
4580 }
4581 
4582 void
4583 l2arc_fini(void)
4584 {
4585 	/*
4586 	 * This is called from dmu_fini(), which is called from spa_fini();
4587 	 * Because of this, we can assume that all l2arc devices have
4588 	 * already been removed when the pools themselves were removed.
4589 	 */
4590 
4591 	l2arc_do_free_on_write();
4592 
4593 	mutex_destroy(&l2arc_feed_thr_lock);
4594 	cv_destroy(&l2arc_feed_thr_cv);
4595 	mutex_destroy(&l2arc_dev_mtx);
4596 	mutex_destroy(&l2arc_buflist_mtx);
4597 	mutex_destroy(&l2arc_free_on_write_mtx);
4598 
4599 	list_destroy(l2arc_dev_list);
4600 	list_destroy(l2arc_free_on_write);
4601 }
4602 
4603 void
4604 l2arc_start(void)
4605 {
4606 	if (!(spa_mode_global & FWRITE))
4607 		return;
4608 
4609 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
4610 	    TS_RUN, minclsyspri);
4611 }
4612 
4613 void
4614 l2arc_stop(void)
4615 {
4616 	if (!(spa_mode_global & FWRITE))
4617 		return;
4618 
4619 	mutex_enter(&l2arc_feed_thr_lock);
4620 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
4621 	l2arc_thread_exit = 1;
4622 	while (l2arc_thread_exit != 0)
4623 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
4624 	mutex_exit(&l2arc_feed_thr_lock);
4625 }
4626