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