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