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