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