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