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