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