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