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