xref: /titanic_52/usr/src/uts/common/fs/zfs/arc.c (revision 2ac302890e472bf0c11db192dd18f12ded6043f6)
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  * Notify the arc that a block was freed, and thus will never be used again.
3115  */
3116 void
3117 arc_freed(spa_t *spa, const blkptr_t *bp)
3118 {
3119 	arc_buf_hdr_t *hdr;
3120 	kmutex_t *hash_lock;
3121 	uint64_t guid = spa_load_guid(spa);
3122 
3123 	hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3124 	    &hash_lock);
3125 	if (hdr == NULL)
3126 		return;
3127 	if (HDR_BUF_AVAILABLE(hdr)) {
3128 		arc_buf_t *buf = hdr->b_buf;
3129 		add_reference(hdr, hash_lock, FTAG);
3130 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3131 		mutex_exit(hash_lock);
3132 
3133 		arc_release(buf, FTAG);
3134 		(void) arc_buf_remove_ref(buf, FTAG);
3135 	} else {
3136 		mutex_exit(hash_lock);
3137 	}
3138 
3139 }
3140 
3141 /*
3142  * This is used by the DMU to let the ARC know that a buffer is
3143  * being evicted, so the ARC should clean up.  If this arc buf
3144  * is not yet in the evicted state, it will be put there.
3145  */
3146 int
3147 arc_buf_evict(arc_buf_t *buf)
3148 {
3149 	arc_buf_hdr_t *hdr;
3150 	kmutex_t *hash_lock;
3151 	arc_buf_t **bufp;
3152 
3153 	mutex_enter(&buf->b_evict_lock);
3154 	hdr = buf->b_hdr;
3155 	if (hdr == NULL) {
3156 		/*
3157 		 * We are in arc_do_user_evicts().
3158 		 */
3159 		ASSERT(buf->b_data == NULL);
3160 		mutex_exit(&buf->b_evict_lock);
3161 		return (0);
3162 	} else if (buf->b_data == NULL) {
3163 		arc_buf_t copy = *buf; /* structure assignment */
3164 		/*
3165 		 * We are on the eviction list; process this buffer now
3166 		 * but let arc_do_user_evicts() do the reaping.
3167 		 */
3168 		buf->b_efunc = NULL;
3169 		mutex_exit(&buf->b_evict_lock);
3170 		VERIFY(copy.b_efunc(&copy) == 0);
3171 		return (1);
3172 	}
3173 	hash_lock = HDR_LOCK(hdr);
3174 	mutex_enter(hash_lock);
3175 	hdr = buf->b_hdr;
3176 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3177 
3178 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3179 	ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3180 
3181 	/*
3182 	 * Pull this buffer off of the hdr
3183 	 */
3184 	bufp = &hdr->b_buf;
3185 	while (*bufp != buf)
3186 		bufp = &(*bufp)->b_next;
3187 	*bufp = buf->b_next;
3188 
3189 	ASSERT(buf->b_data != NULL);
3190 	arc_buf_destroy(buf, FALSE, FALSE);
3191 
3192 	if (hdr->b_datacnt == 0) {
3193 		arc_state_t *old_state = hdr->b_state;
3194 		arc_state_t *evicted_state;
3195 
3196 		ASSERT(hdr->b_buf == NULL);
3197 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
3198 
3199 		evicted_state =
3200 		    (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3201 
3202 		mutex_enter(&old_state->arcs_mtx);
3203 		mutex_enter(&evicted_state->arcs_mtx);
3204 
3205 		arc_change_state(evicted_state, hdr, hash_lock);
3206 		ASSERT(HDR_IN_HASH_TABLE(hdr));
3207 		hdr->b_flags |= ARC_IN_HASH_TABLE;
3208 		hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3209 
3210 		mutex_exit(&evicted_state->arcs_mtx);
3211 		mutex_exit(&old_state->arcs_mtx);
3212 	}
3213 	mutex_exit(hash_lock);
3214 	mutex_exit(&buf->b_evict_lock);
3215 
3216 	VERIFY(buf->b_efunc(buf) == 0);
3217 	buf->b_efunc = NULL;
3218 	buf->b_private = NULL;
3219 	buf->b_hdr = NULL;
3220 	buf->b_next = NULL;
3221 	kmem_cache_free(buf_cache, buf);
3222 	return (1);
3223 }
3224 
3225 /*
3226  * Release this buffer from the cache.  This must be done
3227  * after a read and prior to modifying the buffer contents.
3228  * If the buffer has more than one reference, we must make
3229  * a new hdr for the buffer.
3230  */
3231 void
3232 arc_release(arc_buf_t *buf, void *tag)
3233 {
3234 	arc_buf_hdr_t *hdr;
3235 	kmutex_t *hash_lock = NULL;
3236 	l2arc_buf_hdr_t *l2hdr;
3237 	uint64_t buf_size;
3238 
3239 	/*
3240 	 * It would be nice to assert that if it's DMU metadata (level >
3241 	 * 0 || it's the dnode file), then it must be syncing context.
3242 	 * But we don't know that information at this level.
3243 	 */
3244 
3245 	mutex_enter(&buf->b_evict_lock);
3246 	hdr = buf->b_hdr;
3247 
3248 	/* this buffer is not on any list */
3249 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3250 
3251 	if (hdr->b_state == arc_anon) {
3252 		/* this buffer is already released */
3253 		ASSERT(buf->b_efunc == NULL);
3254 	} else {
3255 		hash_lock = HDR_LOCK(hdr);
3256 		mutex_enter(hash_lock);
3257 		hdr = buf->b_hdr;
3258 		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3259 	}
3260 
3261 	l2hdr = hdr->b_l2hdr;
3262 	if (l2hdr) {
3263 		mutex_enter(&l2arc_buflist_mtx);
3264 		hdr->b_l2hdr = NULL;
3265 	}
3266 	buf_size = hdr->b_size;
3267 
3268 	/*
3269 	 * Do we have more than one buf?
3270 	 */
3271 	if (hdr->b_datacnt > 1) {
3272 		arc_buf_hdr_t *nhdr;
3273 		arc_buf_t **bufp;
3274 		uint64_t blksz = hdr->b_size;
3275 		uint64_t spa = hdr->b_spa;
3276 		arc_buf_contents_t type = hdr->b_type;
3277 		uint32_t flags = hdr->b_flags;
3278 
3279 		ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3280 		/*
3281 		 * Pull the data off of this hdr and attach it to
3282 		 * a new anonymous hdr.
3283 		 */
3284 		(void) remove_reference(hdr, hash_lock, tag);
3285 		bufp = &hdr->b_buf;
3286 		while (*bufp != buf)
3287 			bufp = &(*bufp)->b_next;
3288 		*bufp = buf->b_next;
3289 		buf->b_next = NULL;
3290 
3291 		ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3292 		atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3293 		if (refcount_is_zero(&hdr->b_refcnt)) {
3294 			uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3295 			ASSERT3U(*size, >=, hdr->b_size);
3296 			atomic_add_64(size, -hdr->b_size);
3297 		}
3298 
3299 		/*
3300 		 * We're releasing a duplicate user data buffer, update
3301 		 * our statistics accordingly.
3302 		 */
3303 		if (hdr->b_type == ARC_BUFC_DATA) {
3304 			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3305 			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3306 			    -hdr->b_size);
3307 		}
3308 		hdr->b_datacnt -= 1;
3309 		arc_cksum_verify(buf);
3310 		arc_buf_unwatch(buf);
3311 
3312 		mutex_exit(hash_lock);
3313 
3314 		nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3315 		nhdr->b_size = blksz;
3316 		nhdr->b_spa = spa;
3317 		nhdr->b_type = type;
3318 		nhdr->b_buf = buf;
3319 		nhdr->b_state = arc_anon;
3320 		nhdr->b_arc_access = 0;
3321 		nhdr->b_flags = flags & ARC_L2_WRITING;
3322 		nhdr->b_l2hdr = NULL;
3323 		nhdr->b_datacnt = 1;
3324 		nhdr->b_freeze_cksum = NULL;
3325 		(void) refcount_add(&nhdr->b_refcnt, tag);
3326 		buf->b_hdr = nhdr;
3327 		mutex_exit(&buf->b_evict_lock);
3328 		atomic_add_64(&arc_anon->arcs_size, blksz);
3329 	} else {
3330 		mutex_exit(&buf->b_evict_lock);
3331 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3332 		ASSERT(!list_link_active(&hdr->b_arc_node));
3333 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3334 		if (hdr->b_state != arc_anon)
3335 			arc_change_state(arc_anon, hdr, hash_lock);
3336 		hdr->b_arc_access = 0;
3337 		if (hash_lock)
3338 			mutex_exit(hash_lock);
3339 
3340 		buf_discard_identity(hdr);
3341 		arc_buf_thaw(buf);
3342 	}
3343 	buf->b_efunc = NULL;
3344 	buf->b_private = NULL;
3345 
3346 	if (l2hdr) {
3347 		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3348 		list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3349 		kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3350 		ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3351 		mutex_exit(&l2arc_buflist_mtx);
3352 	}
3353 }
3354 
3355 int
3356 arc_released(arc_buf_t *buf)
3357 {
3358 	int released;
3359 
3360 	mutex_enter(&buf->b_evict_lock);
3361 	released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3362 	mutex_exit(&buf->b_evict_lock);
3363 	return (released);
3364 }
3365 
3366 int
3367 arc_has_callback(arc_buf_t *buf)
3368 {
3369 	int callback;
3370 
3371 	mutex_enter(&buf->b_evict_lock);
3372 	callback = (buf->b_efunc != NULL);
3373 	mutex_exit(&buf->b_evict_lock);
3374 	return (callback);
3375 }
3376 
3377 #ifdef ZFS_DEBUG
3378 int
3379 arc_referenced(arc_buf_t *buf)
3380 {
3381 	int referenced;
3382 
3383 	mutex_enter(&buf->b_evict_lock);
3384 	referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3385 	mutex_exit(&buf->b_evict_lock);
3386 	return (referenced);
3387 }
3388 #endif
3389 
3390 static void
3391 arc_write_ready(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(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3398 	callback->awcb_ready(zio, buf, callback->awcb_private);
3399 
3400 	/*
3401 	 * If the IO is already in progress, then this is a re-write
3402 	 * attempt, so we need to thaw and re-compute the cksum.
3403 	 * It is the responsibility of the callback to handle the
3404 	 * accounting for any re-write attempt.
3405 	 */
3406 	if (HDR_IO_IN_PROGRESS(hdr)) {
3407 		mutex_enter(&hdr->b_freeze_lock);
3408 		if (hdr->b_freeze_cksum != NULL) {
3409 			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3410 			hdr->b_freeze_cksum = NULL;
3411 		}
3412 		mutex_exit(&hdr->b_freeze_lock);
3413 	}
3414 	arc_cksum_compute(buf, B_FALSE);
3415 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
3416 }
3417 
3418 static void
3419 arc_write_done(zio_t *zio)
3420 {
3421 	arc_write_callback_t *callback = zio->io_private;
3422 	arc_buf_t *buf = callback->awcb_buf;
3423 	arc_buf_hdr_t *hdr = buf->b_hdr;
3424 
3425 	ASSERT(hdr->b_acb == NULL);
3426 
3427 	if (zio->io_error == 0) {
3428 		hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3429 		hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3430 		hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3431 	} else {
3432 		ASSERT(BUF_EMPTY(hdr));
3433 	}
3434 
3435 	/*
3436 	 * If the block to be written was all-zero, we may have
3437 	 * compressed it away.  In this case no write was performed
3438 	 * so there will be no dva/birth/checksum.  The buffer must
3439 	 * therefore remain anonymous (and uncached).
3440 	 */
3441 	if (!BUF_EMPTY(hdr)) {
3442 		arc_buf_hdr_t *exists;
3443 		kmutex_t *hash_lock;
3444 
3445 		ASSERT(zio->io_error == 0);
3446 
3447 		arc_cksum_verify(buf);
3448 
3449 		exists = buf_hash_insert(hdr, &hash_lock);
3450 		if (exists) {
3451 			/*
3452 			 * This can only happen if we overwrite for
3453 			 * sync-to-convergence, because we remove
3454 			 * buffers from the hash table when we arc_free().
3455 			 */
3456 			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3457 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3458 					panic("bad overwrite, hdr=%p exists=%p",
3459 					    (void *)hdr, (void *)exists);
3460 				ASSERT(refcount_is_zero(&exists->b_refcnt));
3461 				arc_change_state(arc_anon, exists, hash_lock);
3462 				mutex_exit(hash_lock);
3463 				arc_hdr_destroy(exists);
3464 				exists = buf_hash_insert(hdr, &hash_lock);
3465 				ASSERT3P(exists, ==, NULL);
3466 			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3467 				/* nopwrite */
3468 				ASSERT(zio->io_prop.zp_nopwrite);
3469 				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3470 					panic("bad nopwrite, hdr=%p exists=%p",
3471 					    (void *)hdr, (void *)exists);
3472 			} else {
3473 				/* Dedup */
3474 				ASSERT(hdr->b_datacnt == 1);
3475 				ASSERT(hdr->b_state == arc_anon);
3476 				ASSERT(BP_GET_DEDUP(zio->io_bp));
3477 				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3478 			}
3479 		}
3480 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3481 		/* if it's not anon, we are doing a scrub */
3482 		if (!exists && hdr->b_state == arc_anon)
3483 			arc_access(hdr, hash_lock);
3484 		mutex_exit(hash_lock);
3485 	} else {
3486 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3487 	}
3488 
3489 	ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3490 	callback->awcb_done(zio, buf, callback->awcb_private);
3491 
3492 	kmem_free(callback, sizeof (arc_write_callback_t));
3493 }
3494 
3495 zio_t *
3496 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3497     blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3498     const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *done,
3499     void *private, int priority, int zio_flags, const zbookmark_t *zb)
3500 {
3501 	arc_buf_hdr_t *hdr = buf->b_hdr;
3502 	arc_write_callback_t *callback;
3503 	zio_t *zio;
3504 
3505 	ASSERT(ready != NULL);
3506 	ASSERT(done != NULL);
3507 	ASSERT(!HDR_IO_ERROR(hdr));
3508 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3509 	ASSERT(hdr->b_acb == NULL);
3510 	if (l2arc)
3511 		hdr->b_flags |= ARC_L2CACHE;
3512 	if (l2arc_compress)
3513 		hdr->b_flags |= ARC_L2COMPRESS;
3514 	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
3515 	callback->awcb_ready = ready;
3516 	callback->awcb_done = done;
3517 	callback->awcb_private = private;
3518 	callback->awcb_buf = buf;
3519 
3520 	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3521 	    arc_write_ready, arc_write_done, callback, priority, zio_flags, zb);
3522 
3523 	return (zio);
3524 }
3525 
3526 static int
3527 arc_memory_throttle(uint64_t reserve, uint64_t inflight_data, uint64_t txg)
3528 {
3529 #ifdef _KERNEL
3530 	uint64_t available_memory = ptob(freemem);
3531 	static uint64_t page_load = 0;
3532 	static uint64_t last_txg = 0;
3533 
3534 #if defined(__i386)
3535 	available_memory =
3536 	    MIN(available_memory, vmem_size(heap_arena, VMEM_FREE));
3537 #endif
3538 	if (available_memory >= zfs_write_limit_max)
3539 		return (0);
3540 
3541 	if (txg > last_txg) {
3542 		last_txg = txg;
3543 		page_load = 0;
3544 	}
3545 	/*
3546 	 * If we are in pageout, we know that memory is already tight,
3547 	 * the arc is already going to be evicting, so we just want to
3548 	 * continue to let page writes occur as quickly as possible.
3549 	 */
3550 	if (curproc == proc_pageout) {
3551 		if (page_load > MAX(ptob(minfree), available_memory) / 4)
3552 			return (SET_ERROR(ERESTART));
3553 		/* Note: reserve is inflated, so we deflate */
3554 		page_load += reserve / 8;
3555 		return (0);
3556 	} else if (page_load > 0 && arc_reclaim_needed()) {
3557 		/* memory is low, delay before restarting */
3558 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3559 		return (SET_ERROR(EAGAIN));
3560 	}
3561 	page_load = 0;
3562 
3563 	if (arc_size > arc_c_min) {
3564 		uint64_t evictable_memory =
3565 		    arc_mru->arcs_lsize[ARC_BUFC_DATA] +
3566 		    arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
3567 		    arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
3568 		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
3569 		available_memory += MIN(evictable_memory, arc_size - arc_c_min);
3570 	}
3571 
3572 	if (inflight_data > available_memory / 4) {
3573 		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3574 		return (SET_ERROR(ERESTART));
3575 	}
3576 #endif
3577 	return (0);
3578 }
3579 
3580 void
3581 arc_tempreserve_clear(uint64_t reserve)
3582 {
3583 	atomic_add_64(&arc_tempreserve, -reserve);
3584 	ASSERT((int64_t)arc_tempreserve >= 0);
3585 }
3586 
3587 int
3588 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3589 {
3590 	int error;
3591 	uint64_t anon_size;
3592 
3593 #ifdef ZFS_DEBUG
3594 	/*
3595 	 * Once in a while, fail for no reason.  Everything should cope.
3596 	 */
3597 	if (spa_get_random(10000) == 0) {
3598 		dprintf("forcing random failure\n");
3599 		return (SET_ERROR(ERESTART));
3600 	}
3601 #endif
3602 	if (reserve > arc_c/4 && !arc_no_grow)
3603 		arc_c = MIN(arc_c_max, reserve * 4);
3604 	if (reserve > arc_c)
3605 		return (SET_ERROR(ENOMEM));
3606 
3607 	/*
3608 	 * Don't count loaned bufs as in flight dirty data to prevent long
3609 	 * network delays from blocking transactions that are ready to be
3610 	 * assigned to a txg.
3611 	 */
3612 	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3613 
3614 	/*
3615 	 * Writes will, almost always, require additional memory allocations
3616 	 * in order to compress/encrypt/etc the data.  We therefor need to
3617 	 * make sure that there is sufficient available memory for this.
3618 	 */
3619 	if (error = arc_memory_throttle(reserve, anon_size, txg))
3620 		return (error);
3621 
3622 	/*
3623 	 * Throttle writes when the amount of dirty data in the cache
3624 	 * gets too large.  We try to keep the cache less than half full
3625 	 * of dirty blocks so that our sync times don't grow too large.
3626 	 * Note: if two requests come in concurrently, we might let them
3627 	 * both succeed, when one of them should fail.  Not a huge deal.
3628 	 */
3629 
3630 	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3631 	    anon_size > arc_c / 4) {
3632 		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3633 		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3634 		    arc_tempreserve>>10,
3635 		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3636 		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3637 		    reserve>>10, arc_c>>10);
3638 		return (SET_ERROR(ERESTART));
3639 	}
3640 	atomic_add_64(&arc_tempreserve, reserve);
3641 	return (0);
3642 }
3643 
3644 void
3645 arc_init(void)
3646 {
3647 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
3648 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
3649 
3650 	/* Convert seconds to clock ticks */
3651 	arc_min_prefetch_lifespan = 1 * hz;
3652 
3653 	/* Start out with 1/8 of all memory */
3654 	arc_c = physmem * PAGESIZE / 8;
3655 
3656 #ifdef _KERNEL
3657 	/*
3658 	 * On architectures where the physical memory can be larger
3659 	 * than the addressable space (intel in 32-bit mode), we may
3660 	 * need to limit the cache to 1/8 of VM size.
3661 	 */
3662 	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
3663 #endif
3664 
3665 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
3666 	arc_c_min = MAX(arc_c / 4, 64<<20);
3667 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
3668 	if (arc_c * 8 >= 1<<30)
3669 		arc_c_max = (arc_c * 8) - (1<<30);
3670 	else
3671 		arc_c_max = arc_c_min;
3672 	arc_c_max = MAX(arc_c * 6, arc_c_max);
3673 
3674 	/*
3675 	 * Allow the tunables to override our calculations if they are
3676 	 * reasonable (ie. over 64MB)
3677 	 */
3678 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
3679 		arc_c_max = zfs_arc_max;
3680 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
3681 		arc_c_min = zfs_arc_min;
3682 
3683 	arc_c = arc_c_max;
3684 	arc_p = (arc_c >> 1);
3685 
3686 	/* limit meta-data to 1/4 of the arc capacity */
3687 	arc_meta_limit = arc_c_max / 4;
3688 
3689 	/* Allow the tunable to override if it is reasonable */
3690 	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
3691 		arc_meta_limit = zfs_arc_meta_limit;
3692 
3693 	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
3694 		arc_c_min = arc_meta_limit / 2;
3695 
3696 	if (zfs_arc_grow_retry > 0)
3697 		arc_grow_retry = zfs_arc_grow_retry;
3698 
3699 	if (zfs_arc_shrink_shift > 0)
3700 		arc_shrink_shift = zfs_arc_shrink_shift;
3701 
3702 	if (zfs_arc_p_min_shift > 0)
3703 		arc_p_min_shift = zfs_arc_p_min_shift;
3704 
3705 	/* if kmem_flags are set, lets try to use less memory */
3706 	if (kmem_debugging())
3707 		arc_c = arc_c / 2;
3708 	if (arc_c < arc_c_min)
3709 		arc_c = arc_c_min;
3710 
3711 	arc_anon = &ARC_anon;
3712 	arc_mru = &ARC_mru;
3713 	arc_mru_ghost = &ARC_mru_ghost;
3714 	arc_mfu = &ARC_mfu;
3715 	arc_mfu_ghost = &ARC_mfu_ghost;
3716 	arc_l2c_only = &ARC_l2c_only;
3717 	arc_size = 0;
3718 
3719 	mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3720 	mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3721 	mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3722 	mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3723 	mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3724 	mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
3725 
3726 	list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
3727 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3728 	list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
3729 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3730 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
3731 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3732 	list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
3733 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3734 	list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
3735 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3736 	list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
3737 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3738 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
3739 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3740 	list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
3741 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3742 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
3743 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3744 	list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
3745 	    sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
3746 
3747 	buf_init();
3748 
3749 	arc_thread_exit = 0;
3750 	arc_eviction_list = NULL;
3751 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
3752 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
3753 
3754 	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
3755 	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
3756 
3757 	if (arc_ksp != NULL) {
3758 		arc_ksp->ks_data = &arc_stats;
3759 		kstat_install(arc_ksp);
3760 	}
3761 
3762 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
3763 	    TS_RUN, minclsyspri);
3764 
3765 	arc_dead = FALSE;
3766 	arc_warm = B_FALSE;
3767 
3768 	if (zfs_write_limit_max == 0)
3769 		zfs_write_limit_max = ptob(physmem) >> zfs_write_limit_shift;
3770 	else
3771 		zfs_write_limit_shift = 0;
3772 	mutex_init(&zfs_write_limit_lock, NULL, MUTEX_DEFAULT, NULL);
3773 }
3774 
3775 void
3776 arc_fini(void)
3777 {
3778 	mutex_enter(&arc_reclaim_thr_lock);
3779 	arc_thread_exit = 1;
3780 	while (arc_thread_exit != 0)
3781 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
3782 	mutex_exit(&arc_reclaim_thr_lock);
3783 
3784 	arc_flush(NULL);
3785 
3786 	arc_dead = TRUE;
3787 
3788 	if (arc_ksp != NULL) {
3789 		kstat_delete(arc_ksp);
3790 		arc_ksp = NULL;
3791 	}
3792 
3793 	mutex_destroy(&arc_eviction_mtx);
3794 	mutex_destroy(&arc_reclaim_thr_lock);
3795 	cv_destroy(&arc_reclaim_thr_cv);
3796 
3797 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
3798 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
3799 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
3800 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
3801 	list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
3802 	list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
3803 	list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
3804 	list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
3805 
3806 	mutex_destroy(&arc_anon->arcs_mtx);
3807 	mutex_destroy(&arc_mru->arcs_mtx);
3808 	mutex_destroy(&arc_mru_ghost->arcs_mtx);
3809 	mutex_destroy(&arc_mfu->arcs_mtx);
3810 	mutex_destroy(&arc_mfu_ghost->arcs_mtx);
3811 	mutex_destroy(&arc_l2c_only->arcs_mtx);
3812 
3813 	mutex_destroy(&zfs_write_limit_lock);
3814 
3815 	buf_fini();
3816 
3817 	ASSERT(arc_loaned_bytes == 0);
3818 }
3819 
3820 /*
3821  * Level 2 ARC
3822  *
3823  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
3824  * It uses dedicated storage devices to hold cached data, which are populated
3825  * using large infrequent writes.  The main role of this cache is to boost
3826  * the performance of random read workloads.  The intended L2ARC devices
3827  * include short-stroked disks, solid state disks, and other media with
3828  * substantially faster read latency than disk.
3829  *
3830  *                 +-----------------------+
3831  *                 |         ARC           |
3832  *                 +-----------------------+
3833  *                    |         ^     ^
3834  *                    |         |     |
3835  *      l2arc_feed_thread()    arc_read()
3836  *                    |         |     |
3837  *                    |  l2arc read   |
3838  *                    V         |     |
3839  *               +---------------+    |
3840  *               |     L2ARC     |    |
3841  *               +---------------+    |
3842  *                   |    ^           |
3843  *          l2arc_write() |           |
3844  *                   |    |           |
3845  *                   V    |           |
3846  *                 +-------+      +-------+
3847  *                 | vdev  |      | vdev  |
3848  *                 | cache |      | cache |
3849  *                 +-------+      +-------+
3850  *                 +=========+     .-----.
3851  *                 :  L2ARC  :    |-_____-|
3852  *                 : devices :    | Disks |
3853  *                 +=========+    `-_____-'
3854  *
3855  * Read requests are satisfied from the following sources, in order:
3856  *
3857  *	1) ARC
3858  *	2) vdev cache of L2ARC devices
3859  *	3) L2ARC devices
3860  *	4) vdev cache of disks
3861  *	5) disks
3862  *
3863  * Some L2ARC device types exhibit extremely slow write performance.
3864  * To accommodate for this there are some significant differences between
3865  * the L2ARC and traditional cache design:
3866  *
3867  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
3868  * the ARC behave as usual, freeing buffers and placing headers on ghost
3869  * lists.  The ARC does not send buffers to the L2ARC during eviction as
3870  * this would add inflated write latencies for all ARC memory pressure.
3871  *
3872  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
3873  * It does this by periodically scanning buffers from the eviction-end of
3874  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
3875  * not already there. It scans until a headroom of buffers is satisfied,
3876  * which itself is a buffer for ARC eviction. If a compressible buffer is
3877  * found during scanning and selected for writing to an L2ARC device, we
3878  * temporarily boost scanning headroom during the next scan cycle to make
3879  * sure we adapt to compression effects (which might significantly reduce
3880  * the data volume we write to L2ARC). The thread that does this is
3881  * l2arc_feed_thread(), illustrated below; example sizes are included to
3882  * provide a better sense of ratio than this diagram:
3883  *
3884  *	       head -->                        tail
3885  *	        +---------------------+----------+
3886  *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
3887  *	        +---------------------+----------+   |   o L2ARC eligible
3888  *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
3889  *	        +---------------------+----------+   |
3890  *	             15.9 Gbytes      ^ 32 Mbytes    |
3891  *	                           headroom          |
3892  *	                                      l2arc_feed_thread()
3893  *	                                             |
3894  *	                 l2arc write hand <--[oooo]--'
3895  *	                         |           8 Mbyte
3896  *	                         |          write max
3897  *	                         V
3898  *		  +==============================+
3899  *	L2ARC dev |####|#|###|###|    |####| ... |
3900  *	          +==============================+
3901  *	                     32 Gbytes
3902  *
3903  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
3904  * evicted, then the L2ARC has cached a buffer much sooner than it probably
3905  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
3906  * safe to say that this is an uncommon case, since buffers at the end of
3907  * the ARC lists have moved there due to inactivity.
3908  *
3909  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
3910  * then the L2ARC simply misses copying some buffers.  This serves as a
3911  * pressure valve to prevent heavy read workloads from both stalling the ARC
3912  * with waits and clogging the L2ARC with writes.  This also helps prevent
3913  * the potential for the L2ARC to churn if it attempts to cache content too
3914  * quickly, such as during backups of the entire pool.
3915  *
3916  * 5. After system boot and before the ARC has filled main memory, there are
3917  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
3918  * lists can remain mostly static.  Instead of searching from tail of these
3919  * lists as pictured, the l2arc_feed_thread() will search from the list heads
3920  * for eligible buffers, greatly increasing its chance of finding them.
3921  *
3922  * The L2ARC device write speed is also boosted during this time so that
3923  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
3924  * there are no L2ARC reads, and no fear of degrading read performance
3925  * through increased writes.
3926  *
3927  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
3928  * the vdev queue can aggregate them into larger and fewer writes.  Each
3929  * device is written to in a rotor fashion, sweeping writes through
3930  * available space then repeating.
3931  *
3932  * 7. The L2ARC does not store dirty content.  It never needs to flush
3933  * write buffers back to disk based storage.
3934  *
3935  * 8. If an ARC buffer is written (and dirtied) which also exists in the
3936  * L2ARC, the now stale L2ARC buffer is immediately dropped.
3937  *
3938  * The performance of the L2ARC can be tweaked by a number of tunables, which
3939  * may be necessary for different workloads:
3940  *
3941  *	l2arc_write_max		max write bytes per interval
3942  *	l2arc_write_boost	extra write bytes during device warmup
3943  *	l2arc_noprefetch	skip caching prefetched buffers
3944  *	l2arc_headroom		number of max device writes to precache
3945  *	l2arc_headroom_boost	when we find compressed buffers during ARC
3946  *				scanning, we multiply headroom by this
3947  *				percentage factor for the next scan cycle,
3948  *				since more compressed buffers are likely to
3949  *				be present
3950  *	l2arc_feed_secs		seconds between L2ARC writing
3951  *
3952  * Tunables may be removed or added as future performance improvements are
3953  * integrated, and also may become zpool properties.
3954  *
3955  * There are three key functions that control how the L2ARC warms up:
3956  *
3957  *	l2arc_write_eligible()	check if a buffer is eligible to cache
3958  *	l2arc_write_size()	calculate how much to write
3959  *	l2arc_write_interval()	calculate sleep delay between writes
3960  *
3961  * These three functions determine what to write, how much, and how quickly
3962  * to send writes.
3963  */
3964 
3965 static boolean_t
3966 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
3967 {
3968 	/*
3969 	 * A buffer is *not* eligible for the L2ARC if it:
3970 	 * 1. belongs to a different spa.
3971 	 * 2. is already cached on the L2ARC.
3972 	 * 3. has an I/O in progress (it may be an incomplete read).
3973 	 * 4. is flagged not eligible (zfs property).
3974 	 */
3975 	if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
3976 	    HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
3977 		return (B_FALSE);
3978 
3979 	return (B_TRUE);
3980 }
3981 
3982 static uint64_t
3983 l2arc_write_size(void)
3984 {
3985 	uint64_t size;
3986 
3987 	/*
3988 	 * Make sure our globals have meaningful values in case the user
3989 	 * altered them.
3990 	 */
3991 	size = l2arc_write_max;
3992 	if (size == 0) {
3993 		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
3994 		    "be greater than zero, resetting it to the default (%d)",
3995 		    L2ARC_WRITE_SIZE);
3996 		size = l2arc_write_max = L2ARC_WRITE_SIZE;
3997 	}
3998 
3999 	if (arc_warm == B_FALSE)
4000 		size += l2arc_write_boost;
4001 
4002 	return (size);
4003 
4004 }
4005 
4006 static clock_t
4007 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4008 {
4009 	clock_t interval, next, now;
4010 
4011 	/*
4012 	 * If the ARC lists are busy, increase our write rate; if the
4013 	 * lists are stale, idle back.  This is achieved by checking
4014 	 * how much we previously wrote - if it was more than half of
4015 	 * what we wanted, schedule the next write much sooner.
4016 	 */
4017 	if (l2arc_feed_again && wrote > (wanted / 2))
4018 		interval = (hz * l2arc_feed_min_ms) / 1000;
4019 	else
4020 		interval = hz * l2arc_feed_secs;
4021 
4022 	now = ddi_get_lbolt();
4023 	next = MAX(now, MIN(now + interval, began + interval));
4024 
4025 	return (next);
4026 }
4027 
4028 static void
4029 l2arc_hdr_stat_add(void)
4030 {
4031 	ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE + L2HDR_SIZE);
4032 	ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4033 }
4034 
4035 static void
4036 l2arc_hdr_stat_remove(void)
4037 {
4038 	ARCSTAT_INCR(arcstat_l2_hdr_size, -(HDR_SIZE + L2HDR_SIZE));
4039 	ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4040 }
4041 
4042 /*
4043  * Cycle through L2ARC devices.  This is how L2ARC load balances.
4044  * If a device is returned, this also returns holding the spa config lock.
4045  */
4046 static l2arc_dev_t *
4047 l2arc_dev_get_next(void)
4048 {
4049 	l2arc_dev_t *first, *next = NULL;
4050 
4051 	/*
4052 	 * Lock out the removal of spas (spa_namespace_lock), then removal
4053 	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
4054 	 * both locks will be dropped and a spa config lock held instead.
4055 	 */
4056 	mutex_enter(&spa_namespace_lock);
4057 	mutex_enter(&l2arc_dev_mtx);
4058 
4059 	/* if there are no vdevs, there is nothing to do */
4060 	if (l2arc_ndev == 0)
4061 		goto out;
4062 
4063 	first = NULL;
4064 	next = l2arc_dev_last;
4065 	do {
4066 		/* loop around the list looking for a non-faulted vdev */
4067 		if (next == NULL) {
4068 			next = list_head(l2arc_dev_list);
4069 		} else {
4070 			next = list_next(l2arc_dev_list, next);
4071 			if (next == NULL)
4072 				next = list_head(l2arc_dev_list);
4073 		}
4074 
4075 		/* if we have come back to the start, bail out */
4076 		if (first == NULL)
4077 			first = next;
4078 		else if (next == first)
4079 			break;
4080 
4081 	} while (vdev_is_dead(next->l2ad_vdev));
4082 
4083 	/* if we were unable to find any usable vdevs, return NULL */
4084 	if (vdev_is_dead(next->l2ad_vdev))
4085 		next = NULL;
4086 
4087 	l2arc_dev_last = next;
4088 
4089 out:
4090 	mutex_exit(&l2arc_dev_mtx);
4091 
4092 	/*
4093 	 * Grab the config lock to prevent the 'next' device from being
4094 	 * removed while we are writing to it.
4095 	 */
4096 	if (next != NULL)
4097 		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4098 	mutex_exit(&spa_namespace_lock);
4099 
4100 	return (next);
4101 }
4102 
4103 /*
4104  * Free buffers that were tagged for destruction.
4105  */
4106 static void
4107 l2arc_do_free_on_write()
4108 {
4109 	list_t *buflist;
4110 	l2arc_data_free_t *df, *df_prev;
4111 
4112 	mutex_enter(&l2arc_free_on_write_mtx);
4113 	buflist = l2arc_free_on_write;
4114 
4115 	for (df = list_tail(buflist); df; df = df_prev) {
4116 		df_prev = list_prev(buflist, df);
4117 		ASSERT(df->l2df_data != NULL);
4118 		ASSERT(df->l2df_func != NULL);
4119 		df->l2df_func(df->l2df_data, df->l2df_size);
4120 		list_remove(buflist, df);
4121 		kmem_free(df, sizeof (l2arc_data_free_t));
4122 	}
4123 
4124 	mutex_exit(&l2arc_free_on_write_mtx);
4125 }
4126 
4127 /*
4128  * A write to a cache device has completed.  Update all headers to allow
4129  * reads from these buffers to begin.
4130  */
4131 static void
4132 l2arc_write_done(zio_t *zio)
4133 {
4134 	l2arc_write_callback_t *cb;
4135 	l2arc_dev_t *dev;
4136 	list_t *buflist;
4137 	arc_buf_hdr_t *head, *ab, *ab_prev;
4138 	l2arc_buf_hdr_t *abl2;
4139 	kmutex_t *hash_lock;
4140 
4141 	cb = zio->io_private;
4142 	ASSERT(cb != NULL);
4143 	dev = cb->l2wcb_dev;
4144 	ASSERT(dev != NULL);
4145 	head = cb->l2wcb_head;
4146 	ASSERT(head != NULL);
4147 	buflist = dev->l2ad_buflist;
4148 	ASSERT(buflist != NULL);
4149 	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4150 	    l2arc_write_callback_t *, cb);
4151 
4152 	if (zio->io_error != 0)
4153 		ARCSTAT_BUMP(arcstat_l2_writes_error);
4154 
4155 	mutex_enter(&l2arc_buflist_mtx);
4156 
4157 	/*
4158 	 * All writes completed, or an error was hit.
4159 	 */
4160 	for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4161 		ab_prev = list_prev(buflist, ab);
4162 
4163 		hash_lock = HDR_LOCK(ab);
4164 		if (!mutex_tryenter(hash_lock)) {
4165 			/*
4166 			 * This buffer misses out.  It may be in a stage
4167 			 * of eviction.  Its ARC_L2_WRITING flag will be
4168 			 * left set, denying reads to this buffer.
4169 			 */
4170 			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4171 			continue;
4172 		}
4173 
4174 		abl2 = ab->b_l2hdr;
4175 
4176 		/*
4177 		 * Release the temporary compressed buffer as soon as possible.
4178 		 */
4179 		if (abl2->b_compress != ZIO_COMPRESS_OFF)
4180 			l2arc_release_cdata_buf(ab);
4181 
4182 		if (zio->io_error != 0) {
4183 			/*
4184 			 * Error - drop L2ARC entry.
4185 			 */
4186 			list_remove(buflist, ab);
4187 			ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4188 			ab->b_l2hdr = NULL;
4189 			kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4190 			ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4191 		}
4192 
4193 		/*
4194 		 * Allow ARC to begin reads to this L2ARC entry.
4195 		 */
4196 		ab->b_flags &= ~ARC_L2_WRITING;
4197 
4198 		mutex_exit(hash_lock);
4199 	}
4200 
4201 	atomic_inc_64(&l2arc_writes_done);
4202 	list_remove(buflist, head);
4203 	kmem_cache_free(hdr_cache, head);
4204 	mutex_exit(&l2arc_buflist_mtx);
4205 
4206 	l2arc_do_free_on_write();
4207 
4208 	kmem_free(cb, sizeof (l2arc_write_callback_t));
4209 }
4210 
4211 /*
4212  * A read to a cache device completed.  Validate buffer contents before
4213  * handing over to the regular ARC routines.
4214  */
4215 static void
4216 l2arc_read_done(zio_t *zio)
4217 {
4218 	l2arc_read_callback_t *cb;
4219 	arc_buf_hdr_t *hdr;
4220 	arc_buf_t *buf;
4221 	kmutex_t *hash_lock;
4222 	int equal;
4223 
4224 	ASSERT(zio->io_vd != NULL);
4225 	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4226 
4227 	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4228 
4229 	cb = zio->io_private;
4230 	ASSERT(cb != NULL);
4231 	buf = cb->l2rcb_buf;
4232 	ASSERT(buf != NULL);
4233 
4234 	hash_lock = HDR_LOCK(buf->b_hdr);
4235 	mutex_enter(hash_lock);
4236 	hdr = buf->b_hdr;
4237 	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4238 
4239 	/*
4240 	 * If the buffer was compressed, decompress it first.
4241 	 */
4242 	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4243 		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4244 	ASSERT(zio->io_data != NULL);
4245 
4246 	/*
4247 	 * Check this survived the L2ARC journey.
4248 	 */
4249 	equal = arc_cksum_equal(buf);
4250 	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4251 		mutex_exit(hash_lock);
4252 		zio->io_private = buf;
4253 		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
4254 		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
4255 		arc_read_done(zio);
4256 	} else {
4257 		mutex_exit(hash_lock);
4258 		/*
4259 		 * Buffer didn't survive caching.  Increment stats and
4260 		 * reissue to the original storage device.
4261 		 */
4262 		if (zio->io_error != 0) {
4263 			ARCSTAT_BUMP(arcstat_l2_io_error);
4264 		} else {
4265 			zio->io_error = SET_ERROR(EIO);
4266 		}
4267 		if (!equal)
4268 			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4269 
4270 		/*
4271 		 * If there's no waiter, issue an async i/o to the primary
4272 		 * storage now.  If there *is* a waiter, the caller must
4273 		 * issue the i/o in a context where it's OK to block.
4274 		 */
4275 		if (zio->io_waiter == NULL) {
4276 			zio_t *pio = zio_unique_parent(zio);
4277 
4278 			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4279 
4280 			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4281 			    buf->b_data, zio->io_size, arc_read_done, buf,
4282 			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4283 		}
4284 	}
4285 
4286 	kmem_free(cb, sizeof (l2arc_read_callback_t));
4287 }
4288 
4289 /*
4290  * This is the list priority from which the L2ARC will search for pages to
4291  * cache.  This is used within loops (0..3) to cycle through lists in the
4292  * desired order.  This order can have a significant effect on cache
4293  * performance.
4294  *
4295  * Currently the metadata lists are hit first, MFU then MRU, followed by
4296  * the data lists.  This function returns a locked list, and also returns
4297  * the lock pointer.
4298  */
4299 static list_t *
4300 l2arc_list_locked(int list_num, kmutex_t **lock)
4301 {
4302 	list_t *list = NULL;
4303 
4304 	ASSERT(list_num >= 0 && list_num <= 3);
4305 
4306 	switch (list_num) {
4307 	case 0:
4308 		list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4309 		*lock = &arc_mfu->arcs_mtx;
4310 		break;
4311 	case 1:
4312 		list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4313 		*lock = &arc_mru->arcs_mtx;
4314 		break;
4315 	case 2:
4316 		list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4317 		*lock = &arc_mfu->arcs_mtx;
4318 		break;
4319 	case 3:
4320 		list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4321 		*lock = &arc_mru->arcs_mtx;
4322 		break;
4323 	}
4324 
4325 	ASSERT(!(MUTEX_HELD(*lock)));
4326 	mutex_enter(*lock);
4327 	return (list);
4328 }
4329 
4330 /*
4331  * Evict buffers from the device write hand to the distance specified in
4332  * bytes.  This distance may span populated buffers, it may span nothing.
4333  * This is clearing a region on the L2ARC device ready for writing.
4334  * If the 'all' boolean is set, every buffer is evicted.
4335  */
4336 static void
4337 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4338 {
4339 	list_t *buflist;
4340 	l2arc_buf_hdr_t *abl2;
4341 	arc_buf_hdr_t *ab, *ab_prev;
4342 	kmutex_t *hash_lock;
4343 	uint64_t taddr;
4344 
4345 	buflist = dev->l2ad_buflist;
4346 
4347 	if (buflist == NULL)
4348 		return;
4349 
4350 	if (!all && dev->l2ad_first) {
4351 		/*
4352 		 * This is the first sweep through the device.  There is
4353 		 * nothing to evict.
4354 		 */
4355 		return;
4356 	}
4357 
4358 	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4359 		/*
4360 		 * When nearing the end of the device, evict to the end
4361 		 * before the device write hand jumps to the start.
4362 		 */
4363 		taddr = dev->l2ad_end;
4364 	} else {
4365 		taddr = dev->l2ad_hand + distance;
4366 	}
4367 	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4368 	    uint64_t, taddr, boolean_t, all);
4369 
4370 top:
4371 	mutex_enter(&l2arc_buflist_mtx);
4372 	for (ab = list_tail(buflist); ab; ab = ab_prev) {
4373 		ab_prev = list_prev(buflist, ab);
4374 
4375 		hash_lock = HDR_LOCK(ab);
4376 		if (!mutex_tryenter(hash_lock)) {
4377 			/*
4378 			 * Missed the hash lock.  Retry.
4379 			 */
4380 			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4381 			mutex_exit(&l2arc_buflist_mtx);
4382 			mutex_enter(hash_lock);
4383 			mutex_exit(hash_lock);
4384 			goto top;
4385 		}
4386 
4387 		if (HDR_L2_WRITE_HEAD(ab)) {
4388 			/*
4389 			 * We hit a write head node.  Leave it for
4390 			 * l2arc_write_done().
4391 			 */
4392 			list_remove(buflist, ab);
4393 			mutex_exit(hash_lock);
4394 			continue;
4395 		}
4396 
4397 		if (!all && ab->b_l2hdr != NULL &&
4398 		    (ab->b_l2hdr->b_daddr > taddr ||
4399 		    ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4400 			/*
4401 			 * We've evicted to the target address,
4402 			 * or the end of the device.
4403 			 */
4404 			mutex_exit(hash_lock);
4405 			break;
4406 		}
4407 
4408 		if (HDR_FREE_IN_PROGRESS(ab)) {
4409 			/*
4410 			 * Already on the path to destruction.
4411 			 */
4412 			mutex_exit(hash_lock);
4413 			continue;
4414 		}
4415 
4416 		if (ab->b_state == arc_l2c_only) {
4417 			ASSERT(!HDR_L2_READING(ab));
4418 			/*
4419 			 * This doesn't exist in the ARC.  Destroy.
4420 			 * arc_hdr_destroy() will call list_remove()
4421 			 * and decrement arcstat_l2_size.
4422 			 */
4423 			arc_change_state(arc_anon, ab, hash_lock);
4424 			arc_hdr_destroy(ab);
4425 		} else {
4426 			/*
4427 			 * Invalidate issued or about to be issued
4428 			 * reads, since we may be about to write
4429 			 * over this location.
4430 			 */
4431 			if (HDR_L2_READING(ab)) {
4432 				ARCSTAT_BUMP(arcstat_l2_evict_reading);
4433 				ab->b_flags |= ARC_L2_EVICTED;
4434 			}
4435 
4436 			/*
4437 			 * Tell ARC this no longer exists in L2ARC.
4438 			 */
4439 			if (ab->b_l2hdr != NULL) {
4440 				abl2 = ab->b_l2hdr;
4441 				ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4442 				ab->b_l2hdr = NULL;
4443 				kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4444 				ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4445 			}
4446 			list_remove(buflist, ab);
4447 
4448 			/*
4449 			 * This may have been leftover after a
4450 			 * failed write.
4451 			 */
4452 			ab->b_flags &= ~ARC_L2_WRITING;
4453 		}
4454 		mutex_exit(hash_lock);
4455 	}
4456 	mutex_exit(&l2arc_buflist_mtx);
4457 
4458 	vdev_space_update(dev->l2ad_vdev, -(taddr - dev->l2ad_evict), 0, 0);
4459 	dev->l2ad_evict = taddr;
4460 }
4461 
4462 /*
4463  * Find and write ARC buffers to the L2ARC device.
4464  *
4465  * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4466  * for reading until they have completed writing.
4467  * The headroom_boost is an in-out parameter used to maintain headroom boost
4468  * state between calls to this function.
4469  *
4470  * Returns the number of bytes actually written (which may be smaller than
4471  * the delta by which the device hand has changed due to alignment).
4472  */
4473 static uint64_t
4474 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4475     boolean_t *headroom_boost)
4476 {
4477 	arc_buf_hdr_t *ab, *ab_prev, *head;
4478 	list_t *list;
4479 	uint64_t write_asize, write_psize, write_sz, headroom,
4480 	    buf_compress_minsz;
4481 	void *buf_data;
4482 	kmutex_t *list_lock;
4483 	boolean_t full;
4484 	l2arc_write_callback_t *cb;
4485 	zio_t *pio, *wzio;
4486 	uint64_t guid = spa_load_guid(spa);
4487 	const boolean_t do_headroom_boost = *headroom_boost;
4488 
4489 	ASSERT(dev->l2ad_vdev != NULL);
4490 
4491 	/* Lower the flag now, we might want to raise it again later. */
4492 	*headroom_boost = B_FALSE;
4493 
4494 	pio = NULL;
4495 	write_sz = write_asize = write_psize = 0;
4496 	full = B_FALSE;
4497 	head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4498 	head->b_flags |= ARC_L2_WRITE_HEAD;
4499 
4500 	/*
4501 	 * We will want to try to compress buffers that are at least 2x the
4502 	 * device sector size.
4503 	 */
4504 	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4505 
4506 	/*
4507 	 * Copy buffers for L2ARC writing.
4508 	 */
4509 	mutex_enter(&l2arc_buflist_mtx);
4510 	for (int try = 0; try <= 3; try++) {
4511 		uint64_t passed_sz = 0;
4512 
4513 		list = l2arc_list_locked(try, &list_lock);
4514 
4515 		/*
4516 		 * L2ARC fast warmup.
4517 		 *
4518 		 * Until the ARC is warm and starts to evict, read from the
4519 		 * head of the ARC lists rather than the tail.
4520 		 */
4521 		if (arc_warm == B_FALSE)
4522 			ab = list_head(list);
4523 		else
4524 			ab = list_tail(list);
4525 
4526 		headroom = target_sz * l2arc_headroom;
4527 		if (do_headroom_boost)
4528 			headroom = (headroom * l2arc_headroom_boost) / 100;
4529 
4530 		for (; ab; ab = ab_prev) {
4531 			l2arc_buf_hdr_t *l2hdr;
4532 			kmutex_t *hash_lock;
4533 			uint64_t buf_sz;
4534 
4535 			if (arc_warm == B_FALSE)
4536 				ab_prev = list_next(list, ab);
4537 			else
4538 				ab_prev = list_prev(list, ab);
4539 
4540 			hash_lock = HDR_LOCK(ab);
4541 			if (!mutex_tryenter(hash_lock)) {
4542 				/*
4543 				 * Skip this buffer rather than waiting.
4544 				 */
4545 				continue;
4546 			}
4547 
4548 			passed_sz += ab->b_size;
4549 			if (passed_sz > headroom) {
4550 				/*
4551 				 * Searched too far.
4552 				 */
4553 				mutex_exit(hash_lock);
4554 				break;
4555 			}
4556 
4557 			if (!l2arc_write_eligible(guid, ab)) {
4558 				mutex_exit(hash_lock);
4559 				continue;
4560 			}
4561 
4562 			if ((write_sz + ab->b_size) > target_sz) {
4563 				full = B_TRUE;
4564 				mutex_exit(hash_lock);
4565 				break;
4566 			}
4567 
4568 			if (pio == NULL) {
4569 				/*
4570 				 * Insert a dummy header on the buflist so
4571 				 * l2arc_write_done() can find where the
4572 				 * write buffers begin without searching.
4573 				 */
4574 				list_insert_head(dev->l2ad_buflist, head);
4575 
4576 				cb = kmem_alloc(
4577 				    sizeof (l2arc_write_callback_t), KM_SLEEP);
4578 				cb->l2wcb_dev = dev;
4579 				cb->l2wcb_head = head;
4580 				pio = zio_root(spa, l2arc_write_done, cb,
4581 				    ZIO_FLAG_CANFAIL);
4582 			}
4583 
4584 			/*
4585 			 * Create and add a new L2ARC header.
4586 			 */
4587 			l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t), KM_SLEEP);
4588 			l2hdr->b_dev = dev;
4589 			ab->b_flags |= ARC_L2_WRITING;
4590 
4591 			/*
4592 			 * Temporarily stash the data buffer in b_tmp_cdata.
4593 			 * The subsequent write step will pick it up from
4594 			 * there. This is because can't access ab->b_buf
4595 			 * without holding the hash_lock, which we in turn
4596 			 * can't access without holding the ARC list locks
4597 			 * (which we want to avoid during compression/writing).
4598 			 */
4599 			l2hdr->b_compress = ZIO_COMPRESS_OFF;
4600 			l2hdr->b_asize = ab->b_size;
4601 			l2hdr->b_tmp_cdata = ab->b_buf->b_data;
4602 
4603 			buf_sz = ab->b_size;
4604 			ab->b_l2hdr = l2hdr;
4605 
4606 			list_insert_head(dev->l2ad_buflist, ab);
4607 
4608 			/*
4609 			 * Compute and store the buffer cksum before
4610 			 * writing.  On debug the cksum is verified first.
4611 			 */
4612 			arc_cksum_verify(ab->b_buf);
4613 			arc_cksum_compute(ab->b_buf, B_TRUE);
4614 
4615 			mutex_exit(hash_lock);
4616 
4617 			write_sz += buf_sz;
4618 		}
4619 
4620 		mutex_exit(list_lock);
4621 
4622 		if (full == B_TRUE)
4623 			break;
4624 	}
4625 
4626 	/* No buffers selected for writing? */
4627 	if (pio == NULL) {
4628 		ASSERT0(write_sz);
4629 		mutex_exit(&l2arc_buflist_mtx);
4630 		kmem_cache_free(hdr_cache, head);
4631 		return (0);
4632 	}
4633 
4634 	/*
4635 	 * Now start writing the buffers. We're starting at the write head
4636 	 * and work backwards, retracing the course of the buffer selector
4637 	 * loop above.
4638 	 */
4639 	for (ab = list_prev(dev->l2ad_buflist, head); ab;
4640 	    ab = list_prev(dev->l2ad_buflist, ab)) {
4641 		l2arc_buf_hdr_t *l2hdr;
4642 		uint64_t buf_sz;
4643 
4644 		/*
4645 		 * We shouldn't need to lock the buffer here, since we flagged
4646 		 * it as ARC_L2_WRITING in the previous step, but we must take
4647 		 * care to only access its L2 cache parameters. In particular,
4648 		 * ab->b_buf may be invalid by now due to ARC eviction.
4649 		 */
4650 		l2hdr = ab->b_l2hdr;
4651 		l2hdr->b_daddr = dev->l2ad_hand;
4652 
4653 		if ((ab->b_flags & ARC_L2COMPRESS) &&
4654 		    l2hdr->b_asize >= buf_compress_minsz) {
4655 			if (l2arc_compress_buf(l2hdr)) {
4656 				/*
4657 				 * If compression succeeded, enable headroom
4658 				 * boost on the next scan cycle.
4659 				 */
4660 				*headroom_boost = B_TRUE;
4661 			}
4662 		}
4663 
4664 		/*
4665 		 * Pick up the buffer data we had previously stashed away
4666 		 * (and now potentially also compressed).
4667 		 */
4668 		buf_data = l2hdr->b_tmp_cdata;
4669 		buf_sz = l2hdr->b_asize;
4670 
4671 		/* Compression may have squashed the buffer to zero length. */
4672 		if (buf_sz != 0) {
4673 			uint64_t buf_p_sz;
4674 
4675 			wzio = zio_write_phys(pio, dev->l2ad_vdev,
4676 			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
4677 			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
4678 			    ZIO_FLAG_CANFAIL, B_FALSE);
4679 
4680 			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
4681 			    zio_t *, wzio);
4682 			(void) zio_nowait(wzio);
4683 
4684 			write_asize += buf_sz;
4685 			/*
4686 			 * Keep the clock hand suitably device-aligned.
4687 			 */
4688 			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
4689 			write_psize += buf_p_sz;
4690 			dev->l2ad_hand += buf_p_sz;
4691 		}
4692 	}
4693 
4694 	mutex_exit(&l2arc_buflist_mtx);
4695 
4696 	ASSERT3U(write_asize, <=, target_sz);
4697 	ARCSTAT_BUMP(arcstat_l2_writes_sent);
4698 	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
4699 	ARCSTAT_INCR(arcstat_l2_size, write_sz);
4700 	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
4701 	vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
4702 
4703 	/*
4704 	 * Bump device hand to the device start if it is approaching the end.
4705 	 * l2arc_evict() will already have evicted ahead for this case.
4706 	 */
4707 	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
4708 		vdev_space_update(dev->l2ad_vdev,
4709 		    dev->l2ad_end - dev->l2ad_hand, 0, 0);
4710 		dev->l2ad_hand = dev->l2ad_start;
4711 		dev->l2ad_evict = dev->l2ad_start;
4712 		dev->l2ad_first = B_FALSE;
4713 	}
4714 
4715 	dev->l2ad_writing = B_TRUE;
4716 	(void) zio_wait(pio);
4717 	dev->l2ad_writing = B_FALSE;
4718 
4719 	return (write_asize);
4720 }
4721 
4722 /*
4723  * Compresses an L2ARC buffer.
4724  * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
4725  * size in l2hdr->b_asize. This routine tries to compress the data and
4726  * depending on the compression result there are three possible outcomes:
4727  * *) The buffer was incompressible. The original l2hdr contents were left
4728  *    untouched and are ready for writing to an L2 device.
4729  * *) The buffer was all-zeros, so there is no need to write it to an L2
4730  *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
4731  *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
4732  * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
4733  *    data buffer which holds the compressed data to be written, and b_asize
4734  *    tells us how much data there is. b_compress is set to the appropriate
4735  *    compression algorithm. Once writing is done, invoke
4736  *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
4737  *
4738  * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
4739  * buffer was incompressible).
4740  */
4741 static boolean_t
4742 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
4743 {
4744 	void *cdata;
4745 	size_t csize, len;
4746 
4747 	ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
4748 	ASSERT(l2hdr->b_tmp_cdata != NULL);
4749 
4750 	len = l2hdr->b_asize;
4751 	cdata = zio_data_buf_alloc(len);
4752 	csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
4753 	    cdata, l2hdr->b_asize);
4754 
4755 	if (csize == 0) {
4756 		/* zero block, indicate that there's nothing to write */
4757 		zio_data_buf_free(cdata, len);
4758 		l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
4759 		l2hdr->b_asize = 0;
4760 		l2hdr->b_tmp_cdata = NULL;
4761 		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
4762 		return (B_TRUE);
4763 	} else if (csize > 0 && csize < len) {
4764 		/*
4765 		 * Compression succeeded, we'll keep the cdata around for
4766 		 * writing and release it afterwards.
4767 		 */
4768 		l2hdr->b_compress = ZIO_COMPRESS_LZ4;
4769 		l2hdr->b_asize = csize;
4770 		l2hdr->b_tmp_cdata = cdata;
4771 		ARCSTAT_BUMP(arcstat_l2_compress_successes);
4772 		return (B_TRUE);
4773 	} else {
4774 		/*
4775 		 * Compression failed, release the compressed buffer.
4776 		 * l2hdr will be left unmodified.
4777 		 */
4778 		zio_data_buf_free(cdata, len);
4779 		ARCSTAT_BUMP(arcstat_l2_compress_failures);
4780 		return (B_FALSE);
4781 	}
4782 }
4783 
4784 /*
4785  * Decompresses a zio read back from an l2arc device. On success, the
4786  * underlying zio's io_data buffer is overwritten by the uncompressed
4787  * version. On decompression error (corrupt compressed stream), the
4788  * zio->io_error value is set to signal an I/O error.
4789  *
4790  * Please note that the compressed data stream is not checksummed, so
4791  * if the underlying device is experiencing data corruption, we may feed
4792  * corrupt data to the decompressor, so the decompressor needs to be
4793  * able to handle this situation (LZ4 does).
4794  */
4795 static void
4796 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
4797 {
4798 	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
4799 
4800 	if (zio->io_error != 0) {
4801 		/*
4802 		 * An io error has occured, just restore the original io
4803 		 * size in preparation for a main pool read.
4804 		 */
4805 		zio->io_orig_size = zio->io_size = hdr->b_size;
4806 		return;
4807 	}
4808 
4809 	if (c == ZIO_COMPRESS_EMPTY) {
4810 		/*
4811 		 * An empty buffer results in a null zio, which means we
4812 		 * need to fill its io_data after we're done restoring the
4813 		 * buffer's contents.
4814 		 */
4815 		ASSERT(hdr->b_buf != NULL);
4816 		bzero(hdr->b_buf->b_data, hdr->b_size);
4817 		zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
4818 	} else {
4819 		ASSERT(zio->io_data != NULL);
4820 		/*
4821 		 * We copy the compressed data from the start of the arc buffer
4822 		 * (the zio_read will have pulled in only what we need, the
4823 		 * rest is garbage which we will overwrite at decompression)
4824 		 * and then decompress back to the ARC data buffer. This way we
4825 		 * can minimize copying by simply decompressing back over the
4826 		 * original compressed data (rather than decompressing to an
4827 		 * aux buffer and then copying back the uncompressed buffer,
4828 		 * which is likely to be much larger).
4829 		 */
4830 		uint64_t csize;
4831 		void *cdata;
4832 
4833 		csize = zio->io_size;
4834 		cdata = zio_data_buf_alloc(csize);
4835 		bcopy(zio->io_data, cdata, csize);
4836 		if (zio_decompress_data(c, cdata, zio->io_data, csize,
4837 		    hdr->b_size) != 0)
4838 			zio->io_error = EIO;
4839 		zio_data_buf_free(cdata, csize);
4840 	}
4841 
4842 	/* Restore the expected uncompressed IO size. */
4843 	zio->io_orig_size = zio->io_size = hdr->b_size;
4844 }
4845 
4846 /*
4847  * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
4848  * This buffer serves as a temporary holder of compressed data while
4849  * the buffer entry is being written to an l2arc device. Once that is
4850  * done, we can dispose of it.
4851  */
4852 static void
4853 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
4854 {
4855 	l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
4856 
4857 	if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
4858 		/*
4859 		 * If the data was compressed, then we've allocated a
4860 		 * temporary buffer for it, so now we need to release it.
4861 		 */
4862 		ASSERT(l2hdr->b_tmp_cdata != NULL);
4863 		zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
4864 	}
4865 	l2hdr->b_tmp_cdata = NULL;
4866 }
4867 
4868 /*
4869  * This thread feeds the L2ARC at regular intervals.  This is the beating
4870  * heart of the L2ARC.
4871  */
4872 static void
4873 l2arc_feed_thread(void)
4874 {
4875 	callb_cpr_t cpr;
4876 	l2arc_dev_t *dev;
4877 	spa_t *spa;
4878 	uint64_t size, wrote;
4879 	clock_t begin, next = ddi_get_lbolt();
4880 	boolean_t headroom_boost = B_FALSE;
4881 
4882 	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
4883 
4884 	mutex_enter(&l2arc_feed_thr_lock);
4885 
4886 	while (l2arc_thread_exit == 0) {
4887 		CALLB_CPR_SAFE_BEGIN(&cpr);
4888 		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
4889 		    next);
4890 		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
4891 		next = ddi_get_lbolt() + hz;
4892 
4893 		/*
4894 		 * Quick check for L2ARC devices.
4895 		 */
4896 		mutex_enter(&l2arc_dev_mtx);
4897 		if (l2arc_ndev == 0) {
4898 			mutex_exit(&l2arc_dev_mtx);
4899 			continue;
4900 		}
4901 		mutex_exit(&l2arc_dev_mtx);
4902 		begin = ddi_get_lbolt();
4903 
4904 		/*
4905 		 * This selects the next l2arc device to write to, and in
4906 		 * doing so the next spa to feed from: dev->l2ad_spa.   This
4907 		 * will return NULL if there are now no l2arc devices or if
4908 		 * they are all faulted.
4909 		 *
4910 		 * If a device is returned, its spa's config lock is also
4911 		 * held to prevent device removal.  l2arc_dev_get_next()
4912 		 * will grab and release l2arc_dev_mtx.
4913 		 */
4914 		if ((dev = l2arc_dev_get_next()) == NULL)
4915 			continue;
4916 
4917 		spa = dev->l2ad_spa;
4918 		ASSERT(spa != NULL);
4919 
4920 		/*
4921 		 * If the pool is read-only then force the feed thread to
4922 		 * sleep a little longer.
4923 		 */
4924 		if (!spa_writeable(spa)) {
4925 			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
4926 			spa_config_exit(spa, SCL_L2ARC, dev);
4927 			continue;
4928 		}
4929 
4930 		/*
4931 		 * Avoid contributing to memory pressure.
4932 		 */
4933 		if (arc_reclaim_needed()) {
4934 			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
4935 			spa_config_exit(spa, SCL_L2ARC, dev);
4936 			continue;
4937 		}
4938 
4939 		ARCSTAT_BUMP(arcstat_l2_feeds);
4940 
4941 		size = l2arc_write_size();
4942 
4943 		/*
4944 		 * Evict L2ARC buffers that will be overwritten.
4945 		 */
4946 		l2arc_evict(dev, size, B_FALSE);
4947 
4948 		/*
4949 		 * Write ARC buffers.
4950 		 */
4951 		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
4952 
4953 		/*
4954 		 * Calculate interval between writes.
4955 		 */
4956 		next = l2arc_write_interval(begin, size, wrote);
4957 		spa_config_exit(spa, SCL_L2ARC, dev);
4958 	}
4959 
4960 	l2arc_thread_exit = 0;
4961 	cv_broadcast(&l2arc_feed_thr_cv);
4962 	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
4963 	thread_exit();
4964 }
4965 
4966 boolean_t
4967 l2arc_vdev_present(vdev_t *vd)
4968 {
4969 	l2arc_dev_t *dev;
4970 
4971 	mutex_enter(&l2arc_dev_mtx);
4972 	for (dev = list_head(l2arc_dev_list); dev != NULL;
4973 	    dev = list_next(l2arc_dev_list, dev)) {
4974 		if (dev->l2ad_vdev == vd)
4975 			break;
4976 	}
4977 	mutex_exit(&l2arc_dev_mtx);
4978 
4979 	return (dev != NULL);
4980 }
4981 
4982 /*
4983  * Add a vdev for use by the L2ARC.  By this point the spa has already
4984  * validated the vdev and opened it.
4985  */
4986 void
4987 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
4988 {
4989 	l2arc_dev_t *adddev;
4990 
4991 	ASSERT(!l2arc_vdev_present(vd));
4992 
4993 	/*
4994 	 * Create a new l2arc device entry.
4995 	 */
4996 	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
4997 	adddev->l2ad_spa = spa;
4998 	adddev->l2ad_vdev = vd;
4999 	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5000 	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5001 	adddev->l2ad_hand = adddev->l2ad_start;
5002 	adddev->l2ad_evict = adddev->l2ad_start;
5003 	adddev->l2ad_first = B_TRUE;
5004 	adddev->l2ad_writing = B_FALSE;
5005 
5006 	/*
5007 	 * This is a list of all ARC buffers that are still valid on the
5008 	 * device.
5009 	 */
5010 	adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5011 	list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5012 	    offsetof(arc_buf_hdr_t, b_l2node));
5013 
5014 	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5015 
5016 	/*
5017 	 * Add device to global list
5018 	 */
5019 	mutex_enter(&l2arc_dev_mtx);
5020 	list_insert_head(l2arc_dev_list, adddev);
5021 	atomic_inc_64(&l2arc_ndev);
5022 	mutex_exit(&l2arc_dev_mtx);
5023 }
5024 
5025 /*
5026  * Remove a vdev from the L2ARC.
5027  */
5028 void
5029 l2arc_remove_vdev(vdev_t *vd)
5030 {
5031 	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5032 
5033 	/*
5034 	 * Find the device by vdev
5035 	 */
5036 	mutex_enter(&l2arc_dev_mtx);
5037 	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5038 		nextdev = list_next(l2arc_dev_list, dev);
5039 		if (vd == dev->l2ad_vdev) {
5040 			remdev = dev;
5041 			break;
5042 		}
5043 	}
5044 	ASSERT(remdev != NULL);
5045 
5046 	/*
5047 	 * Remove device from global list
5048 	 */
5049 	list_remove(l2arc_dev_list, remdev);
5050 	l2arc_dev_last = NULL;		/* may have been invalidated */
5051 	atomic_dec_64(&l2arc_ndev);
5052 	mutex_exit(&l2arc_dev_mtx);
5053 
5054 	/*
5055 	 * Clear all buflists and ARC references.  L2ARC device flush.
5056 	 */
5057 	l2arc_evict(remdev, 0, B_TRUE);
5058 	list_destroy(remdev->l2ad_buflist);
5059 	kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5060 	kmem_free(remdev, sizeof (l2arc_dev_t));
5061 }
5062 
5063 void
5064 l2arc_init(void)
5065 {
5066 	l2arc_thread_exit = 0;
5067 	l2arc_ndev = 0;
5068 	l2arc_writes_sent = 0;
5069 	l2arc_writes_done = 0;
5070 
5071 	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5072 	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5073 	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5074 	mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5075 	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5076 
5077 	l2arc_dev_list = &L2ARC_dev_list;
5078 	l2arc_free_on_write = &L2ARC_free_on_write;
5079 	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5080 	    offsetof(l2arc_dev_t, l2ad_node));
5081 	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5082 	    offsetof(l2arc_data_free_t, l2df_list_node));
5083 }
5084 
5085 void
5086 l2arc_fini(void)
5087 {
5088 	/*
5089 	 * This is called from dmu_fini(), which is called from spa_fini();
5090 	 * Because of this, we can assume that all l2arc devices have
5091 	 * already been removed when the pools themselves were removed.
5092 	 */
5093 
5094 	l2arc_do_free_on_write();
5095 
5096 	mutex_destroy(&l2arc_feed_thr_lock);
5097 	cv_destroy(&l2arc_feed_thr_cv);
5098 	mutex_destroy(&l2arc_dev_mtx);
5099 	mutex_destroy(&l2arc_buflist_mtx);
5100 	mutex_destroy(&l2arc_free_on_write_mtx);
5101 
5102 	list_destroy(l2arc_dev_list);
5103 	list_destroy(l2arc_free_on_write);
5104 }
5105 
5106 void
5107 l2arc_start(void)
5108 {
5109 	if (!(spa_mode_global & FWRITE))
5110 		return;
5111 
5112 	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5113 	    TS_RUN, minclsyspri);
5114 }
5115 
5116 void
5117 l2arc_stop(void)
5118 {
5119 	if (!(spa_mode_global & FWRITE))
5120 		return;
5121 
5122 	mutex_enter(&l2arc_feed_thr_lock);
5123 	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
5124 	l2arc_thread_exit = 1;
5125 	while (l2arc_thread_exit != 0)
5126 		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5127 	mutex_exit(&l2arc_feed_thr_lock);
5128 }
5129